From a6928f7139e6f14211e18f0656ac994bcbaf44f0 Mon Sep 17 00:00:00 2001 From: xiaoyijun <10806653+xiaoyijun@users.noreply.github.com> Date: Fri, 23 Jan 2026 09:36:43 +0000 Subject: [PATCH] chore: update translations and generated content --- docs/references/js/README.md | 8 +- docs/references/js/classes/MCPAuth.md | 74 +++--- .../js/classes/MCPAuthAuthServerError.md | 80 +++--- .../js/classes/MCPAuthBearerAuthError.md | 80 +++--- .../js/classes/MCPAuthConfigError.md | 80 +++--- docs/references/js/classes/MCPAuthError.md | 78 +++--- .../classes/MCPAuthTokenVerificationError.md | 80 +++--- .../js/functions/createVerifyJwt.md | 10 +- .../js/functions/fetchServerConfig.md | 16 +- .../fetchServerConfigByWellKnownUrl.md | 12 +- docs/references/js/functions/getIssuer.md | 6 +- .../js/functions/handleBearerAuth.md | 8 +- .../js/type-aliases/AuthServerConfigError.md | 8 +- .../type-aliases/AuthServerConfigWarning.md | 6 +- .../type-aliases/AuthServerDiscoveryConfig.md | 10 +- .../js/type-aliases/AuthServerModeConfig.md | 8 +- .../AuthorizationServerMetadata.md | 2 +- .../js/type-aliases/BearerAuthConfig.md | 22 +- .../CamelCaseAuthorizationServerMetadata.md | 2 +- .../CamelCaseProtectedResourceMetadata.md | 2 +- .../MCPAuthBearerAuthErrorDetails.md | 12 +- .../type-aliases/ResolvedAuthServerConfig.md | 10 +- .../type-aliases/ResourceServerModeConfig.md | 4 +- .../js/type-aliases/ValidateIssuerFunction.md | 8 +- .../type-aliases/VerifyAccessTokenFunction.md | 6 +- .../authorizationServerMetadataSchema.md | 2 +- ...elCaseAuthorizationServerMetadataSchema.md | 2 +- ...amelCaseProtectedResourceMetadataSchema.md | 2 +- .../current/references/js/README.md | 3 + .../current/references/js/classes/MCPAuth.md | 85 ++++--- .../js/classes/MCPAuthAuthServerError.md | 114 +++------ .../js/classes/MCPAuthBearerAuthError.md | 118 +++------ .../js/classes/MCPAuthConfigError.md | 109 +++------ .../references/js/classes/MCPAuthError.md | 116 +++------ .../classes/MCPAuthTokenVerificationError.md | 111 +++------ .../js/functions/createVerifyJwt.md | 4 +- .../js/functions/fetchServerConfig.md | 18 +- .../fetchServerConfigByWellKnownUrl.md | 21 +- .../references/js/functions/getIssuer.md | 24 ++ .../js/functions/handleBearerAuth.md | 10 +- .../js/type-aliases/AuthServerConfig.md | 46 +--- .../type-aliases/AuthServerConfigWarning.md | 4 +- .../type-aliases/AuthServerDiscoveryConfig.md | 59 +++++ .../js/type-aliases/AuthServerModeConfig.md | 2 +- .../AuthorizationServerMetadata.md | 223 +---------------- .../js/type-aliases/BearerAuthConfig.md | 11 +- .../CamelCaseAuthorizationServerMetadata.md | 166 +------------ .../CamelCaseProtectedResourceMetadata.md | 110 +-------- .../type-aliases/ProtectedResourceMetadata.md | 150 +----------- .../type-aliases/ResolvedAuthServerConfig.md | 53 ++++ .../type-aliases/ResourceServerModeConfig.md | 2 +- .../js/type-aliases/ValidateIssuerFunction.md | 4 +- .../type-aliases/VerifyAccessTokenFunction.md | 2 +- .../authorizationServerMetadataSchema.md | 28 ++- ...elCaseAuthorizationServerMetadataSchema.md | 26 +- ...amelCaseProtectedResourceMetadataSchema.md | 20 +- .../protectedResourceMetadataSchema.md | 20 +- .../current/references/js/README.md | 5 +- .../current/references/js/classes/MCPAuth.md | 106 ++++---- .../js/classes/MCPAuthAuthServerError.md | 116 +++------ .../js/classes/MCPAuthBearerAuthError.md | 115 +++------ .../js/classes/MCPAuthConfigError.md | 115 +++------ .../references/js/classes/MCPAuthError.md | 122 +++------- .../classes/MCPAuthTokenVerificationError.md | 116 +++------ .../js/functions/createVerifyJwt.md | 8 +- .../js/functions/fetchServerConfig.md | 10 +- .../fetchServerConfigByWellKnownUrl.md | 12 +- .../references/js/functions/getIssuer.md | 24 ++ .../js/functions/handleBearerAuth.md | 2 +- .../js/type-aliases/AuthServerConfig.md | 43 +--- .../type-aliases/AuthServerDiscoveryConfig.md | 58 +++++ .../AuthorizationServerMetadata.md | 225 +---------------- .../js/type-aliases/BearerAuthConfig.md | 25 +- .../CamelCaseAuthorizationServerMetadata.md | 168 +------------ .../CamelCaseProtectedResourceMetadata.md | 110 +-------- .../type-aliases/ProtectedResourceMetadata.md | 150 +----------- .../type-aliases/ResolvedAuthServerConfig.md | 52 ++++ .../type-aliases/VerifyAccessTokenFunction.md | 6 +- .../authorizationServerMetadataSchema.md | 28 ++- ...elCaseAuthorizationServerMetadataSchema.md | 26 +- ...amelCaseProtectedResourceMetadataSchema.md | 20 +- .../protectedResourceMetadataSchema.md | 18 +- .../current/references/js/README.md | 3 + .../current/references/js/classes/MCPAuth.md | 141 ++++++----- .../js/classes/MCPAuthAuthServerError.md | 124 +++------- .../js/classes/MCPAuthBearerAuthError.md | 116 +++------ .../js/classes/MCPAuthConfigError.md | 116 +++------ .../references/js/classes/MCPAuthError.md | 118 +++------ .../classes/MCPAuthTokenVerificationError.md | 114 +++------ .../js/functions/createVerifyJwt.md | 2 +- .../js/functions/fetchServerConfig.md | 10 +- .../fetchServerConfigByWellKnownUrl.md | 10 +- .../references/js/functions/getIssuer.md | 24 ++ .../js/functions/handleBearerAuth.md | 8 +- .../js/type-aliases/AuthServerConfig.md | 47 +--- .../js/type-aliases/AuthServerConfigError.md | 2 +- .../type-aliases/AuthServerConfigWarning.md | 2 +- .../type-aliases/AuthServerDiscoveryConfig.md | 57 +++++ .../js/type-aliases/AuthServerModeConfig.md | 4 +- .../AuthorizationServerMetadata.md | 229 +----------------- .../js/type-aliases/BearerAuthConfig.md | 8 +- .../CamelCaseAuthorizationServerMetadata.md | 168 +------------ .../CamelCaseProtectedResourceMetadata.md | 112 +-------- .../type-aliases/ProtectedResourceMetadata.md | 150 +----------- .../type-aliases/ResolvedAuthServerConfig.md | 53 ++++ .../js/type-aliases/ValidateIssuerFunction.md | 7 +- .../authorizationServerMetadataSchema.md | 26 +- ...elCaseAuthorizationServerMetadataSchema.md | 26 +- ...amelCaseProtectedResourceMetadataSchema.md | 20 +- .../protectedResourceMetadataSchema.md | 18 +- .../current/references/js/README.md | 3 + .../current/references/js/classes/MCPAuth.md | 103 +++++--- .../js/classes/MCPAuthAuthServerError.md | 110 +++------ .../js/classes/MCPAuthBearerAuthError.md | 111 +++------ .../js/classes/MCPAuthConfigError.md | 107 +++----- .../references/js/classes/MCPAuthError.md | 116 +++------ .../classes/MCPAuthTokenVerificationError.md | 110 +++------ .../js/functions/createVerifyJwt.md | 6 +- .../js/functions/fetchServerConfig.md | 18 +- .../fetchServerConfigByWellKnownUrl.md | 10 +- .../references/js/functions/getIssuer.md | 24 ++ .../js/functions/handleBearerAuth.md | 10 +- .../js/type-aliases/AuthServerConfig.md | 44 +--- .../type-aliases/AuthServerConfigWarning.md | 2 +- .../type-aliases/AuthServerDiscoveryConfig.md | 57 +++++ .../js/type-aliases/AuthServerModeConfig.md | 4 +- .../AuthorizationServerMetadata.md | 217 +---------------- .../js/type-aliases/BearerAuthConfig.md | 14 +- .../CamelCaseAuthorizationServerMetadata.md | 170 +------------ .../CamelCaseProtectedResourceMetadata.md | 112 +-------- .../type-aliases/ProtectedResourceMetadata.md | 144 +---------- .../type-aliases/ResolvedAuthServerConfig.md | 49 ++++ .../type-aliases/ResourceServerModeConfig.md | 2 +- .../js/type-aliases/ValidateIssuerFunction.md | 4 +- .../type-aliases/VerifyAccessTokenFunction.md | 10 +- .../authorizationServerMetadataSchema.md | 32 ++- ...elCaseAuthorizationServerMetadataSchema.md | 30 ++- ...amelCaseProtectedResourceMetadataSchema.md | 18 +- .../protectedResourceMetadataSchema.md | 18 +- .../current/references/js/README.md | 5 +- .../current/references/js/classes/MCPAuth.md | 81 +++++-- .../js/classes/MCPAuthAuthServerError.md | 110 +++------ .../js/classes/MCPAuthBearerAuthError.md | 109 +++------ .../js/classes/MCPAuthConfigError.md | 112 +++------ .../references/js/classes/MCPAuthError.md | 118 +++------ .../classes/MCPAuthTokenVerificationError.md | 108 +++------ .../js/functions/createVerifyJwt.md | 10 +- .../js/functions/fetchServerConfig.md | 22 +- .../fetchServerConfigByWellKnownUrl.md | 14 +- .../references/js/functions/getIssuer.md | 24 ++ .../js/functions/handleBearerAuth.md | 12 +- .../js/type-aliases/AuthServerConfig.md | 44 +--- .../type-aliases/AuthServerConfigWarning.md | 2 +- .../type-aliases/AuthServerDiscoveryConfig.md | 57 +++++ .../AuthorizationServerMetadata.md | 217 +---------------- .../js/type-aliases/BearerAuthConfig.md | 28 +-- .../CamelCaseAuthorizationServerMetadata.md | 170 +------------ .../CamelCaseProtectedResourceMetadata.md | 112 +-------- .../MCPAuthBearerAuthErrorDetails.md | 4 +- .../type-aliases/ProtectedResourceMetadata.md | 143 +---------- .../type-aliases/ResolvedAuthServerConfig.md | 49 ++++ .../type-aliases/ResourceServerModeConfig.md | 2 +- .../js/type-aliases/ValidateIssuerFunction.md | 2 +- .../type-aliases/VerifyAccessTokenFunction.md | 8 +- .../authorizationServerMetadataSchema.md | 30 ++- ...elCaseAuthorizationServerMetadataSchema.md | 30 ++- ...amelCaseProtectedResourceMetadataSchema.md | 22 +- .../protectedResourceMetadataSchema.md | 18 +- .../current/references/js/README.md | 3 + .../current/references/js/classes/MCPAuth.md | 80 ++++-- .../js/classes/MCPAuthAuthServerError.md | 118 +++------ .../js/classes/MCPAuthBearerAuthError.md | 118 +++------ .../js/classes/MCPAuthConfigError.md | 120 +++------ .../references/js/classes/MCPAuthError.md | 119 +++------ .../classes/MCPAuthTokenVerificationError.md | 116 +++------ .../js/functions/fetchServerConfig.md | 16 +- .../fetchServerConfigByWellKnownUrl.md | 8 +- .../references/js/functions/getIssuer.md | 24 ++ .../js/functions/handleBearerAuth.md | 8 +- .../js/type-aliases/AuthServerConfig.md | 46 +--- .../type-aliases/AuthServerConfigWarning.md | 4 +- .../type-aliases/AuthServerDiscoveryConfig.md | 57 +++++ .../AuthorizationServerMetadata.md | 227 +---------------- .../js/type-aliases/BearerAuthConfig.md | 8 +- .../CamelCaseAuthorizationServerMetadata.md | 168 +------------ .../CamelCaseProtectedResourceMetadata.md | 112 +-------- .../type-aliases/ProtectedResourceMetadata.md | 149 +----------- .../type-aliases/ResolvedAuthServerConfig.md | 53 ++++ .../js/type-aliases/ValidateIssuerFunction.md | 6 +- .../type-aliases/VerifyAccessTokenFunction.md | 8 +- .../authorizationServerMetadataSchema.md | 26 +- ...elCaseAuthorizationServerMetadataSchema.md | 30 ++- ...amelCaseProtectedResourceMetadataSchema.md | 22 +- .../protectedResourceMetadataSchema.md | 18 +- .../current/references/js/README.md | 3 + .../current/references/js/classes/MCPAuth.md | 82 +++++-- .../js/classes/MCPAuthAuthServerError.md | 109 +++------ .../js/classes/MCPAuthBearerAuthError.md | 112 +++------ .../js/classes/MCPAuthConfigError.md | 113 +++------ .../references/js/classes/MCPAuthError.md | 115 +++------ .../classes/MCPAuthTokenVerificationError.md | 110 +++------ .../js/functions/createVerifyJwt.md | 12 +- .../js/functions/fetchServerConfig.md | 10 +- .../fetchServerConfigByWellKnownUrl.md | 10 +- .../references/js/functions/getIssuer.md | 24 ++ .../js/functions/handleBearerAuth.md | 6 +- .../js/type-aliases/AuthServerConfig.md | 45 +--- .../js/type-aliases/AuthServerConfigError.md | 2 +- .../type-aliases/AuthServerConfigWarning.md | 4 +- .../type-aliases/AuthServerDiscoveryConfig.md | 57 +++++ .../AuthorizationServerMetadata.md | 212 +--------------- .../js/type-aliases/BearerAuthConfig.md | 12 +- .../CamelCaseAuthorizationServerMetadata.md | 170 +------------ .../CamelCaseProtectedResourceMetadata.md | 112 +-------- .../type-aliases/ProtectedResourceMetadata.md | 143 +---------- .../type-aliases/ResolvedAuthServerConfig.md | 49 ++++ .../js/type-aliases/ValidateIssuerFunction.md | 6 +- .../type-aliases/VerifyAccessTokenFunction.md | 4 +- .../authorizationServerMetadataSchema.md | 28 ++- ...elCaseAuthorizationServerMetadataSchema.md | 28 ++- ...amelCaseProtectedResourceMetadataSchema.md | 20 +- .../protectedResourceMetadataSchema.md | 18 +- .../current/references/js/README.md | 13 +- .../current/references/js/classes/MCPAuth.md | 103 +++++--- .../js/classes/MCPAuthAuthServerError.md | 107 +++----- .../js/classes/MCPAuthBearerAuthError.md | 113 +++------ .../js/classes/MCPAuthConfigError.md | 111 +++------ .../references/js/classes/MCPAuthError.md | 118 +++------ .../classes/MCPAuthTokenVerificationError.md | 106 +++----- .../js/functions/createVerifyJwt.md | 10 +- .../js/functions/fetchServerConfig.md | 18 +- .../fetchServerConfigByWellKnownUrl.md | 10 +- .../references/js/functions/getIssuer.md | 24 ++ .../js/functions/handleBearerAuth.md | 8 +- .../js/type-aliases/AuthServerConfig.md | 46 +--- .../js/type-aliases/AuthServerConfigError.md | 4 +- .../type-aliases/AuthServerDiscoveryConfig.md | 57 +++++ .../AuthorizationServerMetadata.md | 224 +---------------- .../js/type-aliases/BearerAuthConfig.md | 28 +-- .../CamelCaseAuthorizationServerMetadata.md | 170 +------------ .../CamelCaseProtectedResourceMetadata.md | 114 +-------- .../MCPAuthBearerAuthErrorDetails.md | 4 +- .../type-aliases/ProtectedResourceMetadata.md | 142 +---------- .../type-aliases/ResolvedAuthServerConfig.md | 49 ++++ .../type-aliases/ResourceServerModeConfig.md | 4 +- .../js/type-aliases/ValidateIssuerFunction.md | 6 +- .../type-aliases/VerifyAccessTokenFunction.md | 8 +- .../authorizationServerMetadataSchema.md | 28 ++- ...elCaseAuthorizationServerMetadataSchema.md | 28 ++- ...amelCaseProtectedResourceMetadataSchema.md | 22 +- .../protectedResourceMetadataSchema.md | 20 +- 251 files changed, 4410 insertions(+), 9575 deletions(-) create mode 100644 i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md create mode 100644 i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md create mode 100644 i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md create mode 100644 i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md create mode 100644 i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md create mode 100644 i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md create mode 100644 i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md create mode 100644 i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md create mode 100644 i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md create mode 100644 i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md create mode 100644 i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md create mode 100644 i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md create mode 100644 i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md create mode 100644 i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md create mode 100644 i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md create mode 100644 i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md create mode 100644 i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md create mode 100644 i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md create mode 100644 i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md create mode 100644 i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md create mode 100644 i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md create mode 100644 i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md create mode 100644 i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md create mode 100644 i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md diff --git a/docs/references/js/README.md b/docs/references/js/README.md index 06a9529..b7e76f3 100644 --- a/docs/references/js/README.md +++ b/docs/references/js/README.md @@ -4,7 +4,7 @@ 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) @@ -13,7 +13,7 @@ sidebar_label: Node.js SDK - [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) @@ -40,7 +40,7 @@ sidebar_label: Node.js SDK - [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) - [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) -## Variables +## Variables {#variables} - [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) - [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) @@ -53,7 +53,7 @@ sidebar_label: Node.js SDK - [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) diff --git a/docs/references/js/classes/MCPAuth.md b/docs/references/js/classes/MCPAuth.md index 7c5e0d1..629de38 100644 --- a/docs/references/js/classes/MCPAuth.md +++ b/docs/references/js/classes/MCPAuth.md @@ -10,13 +10,13 @@ authentication policies for your protected resources. It is initialized with your server configurations and provides a `bearerAuth` method to generate Express middleware for token-based authentication. -## Example +## Example {#example} -### Usage in `resource server` mode +### Usage in `resource server` mode {#usage-in-resource-server-mode} This is the recommended approach for new applications. -#### Option 1: Discovery config (recommended for edge runtimes) +#### 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. @@ -42,7 +42,7 @@ const mcpAuth = new MCPAuth({ }); ``` -#### Option 2: Resolved config (pre-fetched metadata) +#### 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. @@ -67,7 +67,7 @@ const mcpAuth = new MCPAuth({ }); ``` -#### Using the middleware +#### Using the middleware {#using-the-middleware} ```ts // Mount the router to handle Protected Resource Metadata @@ -88,7 +88,7 @@ app.get( ); ``` -### Legacy Usage in `authorization server` mode (Deprecated) +### Legacy Usage in `authorization server` mode (Deprecated) {#legacy-usage-in-authorization-server-mode-deprecated} This approach is supported for backward compatibility. @@ -116,9 +116,9 @@ app.get( ); ``` -## Constructors +## Constructors {#constructors} -### Constructor +### Constructor {#constructor} ```ts new MCPAuth(config: MCPAuthConfig): MCPAuth; @@ -127,21 +127,21 @@ new MCPAuth(config: MCPAuthConfig): MCPAuth; Creates an instance of MCPAuth. It validates the entire configuration upfront to fail fast on errors. -#### Parameters +#### Parameters {#parameters} -##### config +##### config {#config} [`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) The authentication configuration. -#### Returns +#### Returns {#returns} `MCPAuth` -## Properties +## Properties {#properties} -### config +### config {#config} ```ts readonly config: MCPAuthConfig; @@ -149,11 +149,11 @@ readonly config: MCPAuthConfig; The authentication configuration. -## Methods +## Methods {#methods} -### bearerAuth() +### bearerAuth() {#bearerauth} -#### Call Signature +#### Call Signature {#call-signature} ```ts bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; @@ -162,9 +162,9 @@ bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit @@ -188,19 +188,19 @@ Optional configuration for the Bearer auth handler. [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) for the available configuration options (excluding `verifyAccessToken` and `issuer`). -##### Returns +##### Returns {#returns} `RequestHandler` An Express middleware function that verifies the access token and adds the verification result to the request object (`req.auth`). -##### See +##### See {#see} [handleBearerAuth](/references/js/functions/handleBearerAuth.md) for the implementation details and the extended types of the `req.auth` (`AuthInfo`) object. -#### Call Signature +#### Call Signature {#call-signature} ```ts bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; @@ -212,9 +212,9 @@ Creates a Bearer auth handler (Express middleware) that verifies the access toke In the `'jwt'` mode, the handler will create a JWT verification function using the JWK Set from the authorization server's JWKS URI. -##### Parameters +##### Parameters {#parameters} -###### mode +###### mode {#mode} `"jwt"` @@ -224,7 +224,7 @@ The mode of verification for the access token. Currently, only 'jwt' is supporte [VerifyAccessTokenMode](/references/js/type-aliases/VerifyAccessTokenMode.md) for the available modes. -###### config? +###### config? {#config} `Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` @@ -238,26 +238,26 @@ verification. - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) for the available configuration options (excluding `verifyAccessToken` and `issuer`). -##### Returns +##### Returns {#returns} `RequestHandler` An Express middleware function that verifies the access token and adds the verification result to the request object (`req.auth`). -##### See +##### See {#see} [handleBearerAuth](/references/js/functions/handleBearerAuth.md) for the implementation details and the extended types of the `req.auth` (`AuthInfo`) object. -##### Throws +##### Throws {#throws} if the JWKS URI is not provided in the server metadata when using the `'jwt'` mode. *** -### ~~delegatedRouter()~~ +### ~~delegatedRouter()~~ {#delegatedrouter} ```ts delegatedRouter(): Router; @@ -266,18 +266,18 @@ delegatedRouter(): Router; 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. -#### Returns +#### Returns {#returns} `Router` A router that serves the OAuth 2.0 Authorization Server Metadata endpoint with the metadata provided to the instance. -#### Deprecated +#### Deprecated {#deprecated} Use [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter) instead. -#### Example +#### Example {#example} ```ts import express from 'express'; @@ -288,13 +288,13 @@ const mcpAuth: MCPAuth; // Assume this is initialized app.use(mcpAuth.delegatedRouter()); ``` -#### Throws +#### Throws {#throws} If called in `resource server` mode. *** -### protectedResourceMetadataRouter() +### protectedResourceMetadataRouter() {#protectedresourcemetadatarouter} ```ts protectedResourceMetadataRouter(): Router; @@ -306,17 +306,17 @@ for all configured resources. This router automatically creates the correct `.well-known` endpoints for each resource identifier provided in your configuration. -#### Returns +#### Returns {#returns} `Router` A router that serves the OAuth 2.0 Protected Resource Metadata endpoint. -#### Throws +#### Throws {#throws} If called in `authorization server` mode. -#### Example +#### Example {#example} ```ts import express from 'express'; diff --git a/docs/references/js/classes/MCPAuthAuthServerError.md b/docs/references/js/classes/MCPAuthAuthServerError.md index cc3f26b..4b9c556 100644 --- a/docs/references/js/classes/MCPAuthAuthServerError.md +++ b/docs/references/js/classes/MCPAuthAuthServerError.md @@ -6,51 +6,51 @@ sidebar_label: MCPAuthAuthServerError Error thrown when there is an issue with the remote authorization server. -## 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 +58,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,43 +108,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() {#tojson} ```ts toJson(showCause: boolean): Record; @@ -152,26 +152,26 @@ toJson(showCause: boolean): Record; Converts the error to a HTTP response friendly JSON format. -#### Parameters +#### Parameters {#parameters} -##### showCause +##### showCause {#showcause} `boolean` = `false` Whether to include the cause of the error in the JSON response. Defaults to `false`. -#### Returns +#### Returns {#returns} `Record`\<`string`, `unknown`\> -#### Inherited from +#### 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 +179,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 index 871e300..7990bdc 100644 --- a/docs/references/js/classes/MCPAuthBearerAuthError.md +++ b/docs/references/js/classes/MCPAuthBearerAuthError.md @@ -6,51 +6,51 @@ sidebar_label: MCPAuthBearerAuthError Error thrown when there is an issue when authenticating with Bearer tokens. -## Extends +## Extends {#extends} - [`MCPAuthError`](/references/js/classes/MCPAuthError.md) -## Constructors +## Constructors {#constructors} -### Constructor +### Constructor {#constructor} ```ts new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthErrorDetails): MCPAuthBearerAuthError; ``` -#### Parameters +#### Parameters {#parameters} -##### code +##### code {#code} [`BearerAuthErrorCode`](/references/js/type-aliases/BearerAuthErrorCode.md) -##### cause? +##### cause? {#cause} [`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) -#### Returns +#### Returns {#returns} `MCPAuthBearerAuthError` -#### 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: MCPAuthBearerAuthErrorDetails; ``` -#### 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: BearerAuthErrorCode; @@ -58,49 +58,49 @@ readonly code: BearerAuthErrorCode; 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 = 'MCPAuthBearerAuthError'; ``` -#### 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,43 +108,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() {#tojson} ```ts toJson(showCause: boolean): Record; @@ -152,26 +152,26 @@ toJson(showCause: boolean): Record; Converts the error to a HTTP response friendly JSON format. -#### Parameters +#### Parameters {#parameters} -##### showCause +##### showCause {#showcause} `boolean` = `false` Whether to include the cause of the error in the JSON response. Defaults to `false`. -#### Returns +#### Returns {#returns} `Record`\<`string`, `unknown`\> -#### Overrides +#### Overrides {#overrides} [`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 +179,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/MCPAuthConfigError.md b/docs/references/js/classes/MCPAuthConfigError.md index bc6f5b1..8047fdd 100644 --- a/docs/references/js/classes/MCPAuthConfigError.md +++ b/docs/references/js/classes/MCPAuthConfigError.md @@ -6,55 +6,55 @@ sidebar_label: MCPAuthConfigError Error thrown when there is a configuration issue with mcp-auth. -## 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 +62,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,43 +112,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() {#tojson} ```ts toJson(showCause: boolean): Record; @@ -156,26 +156,26 @@ toJson(showCause: boolean): Record; Converts the error to a HTTP response friendly JSON format. -#### Parameters +#### Parameters {#parameters} -##### showCause +##### showCause {#showcause} `boolean` = `false` Whether to include the cause of the error in the JSON response. Defaults to `false`. -#### Returns +#### Returns {#returns} `Record`\<`string`, `unknown`\> -#### Inherited from +#### 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 +183,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 3b634b3..6bffab7 100644 --- a/docs/references/js/classes/MCPAuthError.md +++ b/docs/references/js/classes/MCPAuthError.md @@ -8,58 +8,58 @@ Base class for all mcp-auth errors. It provides a standardized way to handle errors related to MCP authentication and authorization. -## 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 +67,7 @@ Error.cause *** -### code +### code {#code} ```ts readonly code: string; @@ -77,13 +77,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 +91,13 @@ Error.message *** -### name +### name {#name} ```ts name: string = 'MCPAuthError'; ``` -#### Overrides +#### Overrides {#overrides} ```ts Error.name @@ -105,13 +105,13 @@ Error.name *** -### stack? +### stack? {#stack} ```ts optional stack: string; ``` -#### Inherited from +#### Inherited from {#inherited-from} ```ts Error.stack @@ -119,7 +119,7 @@ Error.stack *** -### prepareStackTrace()? +### prepareStackTrace()? {#preparestacktrace} ```ts static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; @@ -127,25 +127,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,21 +153,21 @@ Error.prepareStackTrace *** -### stackTraceLimit +### stackTraceLimit {#stacktracelimit} ```ts static stackTraceLimit: number; ``` -#### Inherited from +#### Inherited from {#inherited-from} ```ts Error.stackTraceLimit ``` -## Methods +## Methods {#methods} -### toJson() +### toJson() {#tojson} ```ts toJson(showCause: boolean): Record; @@ -175,22 +175,22 @@ toJson(showCause: boolean): Record; Converts the error to a HTTP response friendly JSON format. -#### Parameters +#### Parameters {#parameters} -##### showCause +##### showCause {#showcause} `boolean` = `false` Whether to include the cause of the error in the JSON response. Defaults to `false`. -#### Returns +#### Returns {#returns} `Record`\<`string`, `unknown`\> *** -### captureStackTrace() +### captureStackTrace() {#capturestacktrace} ```ts static captureStackTrace(targetObject: object, constructorOpt?: Function): void; @@ -198,21 +198,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 index 0ff8407..78be151 100644 --- a/docs/references/js/classes/MCPAuthTokenVerificationError.md +++ b/docs/references/js/classes/MCPAuthTokenVerificationError.md @@ -6,51 +6,51 @@ sidebar_label: MCPAuthTokenVerificationError Error thrown when there is an issue when verifying tokens. -## Extends +## Extends {#extends} - [`MCPAuthError`](/references/js/classes/MCPAuthError.md) -## Constructors +## Constructors {#constructors} -### Constructor +### Constructor {#constructor} ```ts new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause?: unknown): MCPAuthTokenVerificationError; ``` -#### Parameters +#### Parameters {#parameters} -##### code +##### code {#code} [`MCPAuthTokenVerificationErrorCode`](/references/js/type-aliases/MCPAuthTokenVerificationErrorCode.md) -##### cause? +##### cause? {#cause} `unknown` -#### Returns +#### Returns {#returns} `MCPAuthTokenVerificationError` -#### 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: MCPAuthTokenVerificationErrorCode; @@ -58,49 +58,49 @@ readonly code: MCPAuthTokenVerificationErrorCode; 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 = 'MCPAuthTokenVerificationError'; ``` -#### 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,43 +108,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() {#tojson} ```ts toJson(showCause: boolean): Record; @@ -152,26 +152,26 @@ toJson(showCause: boolean): Record; Converts the error to a HTTP response friendly JSON format. -#### Parameters +#### Parameters {#parameters} -##### showCause +##### showCause {#showcause} `boolean` = `false` Whether to include the cause of the error in the JSON response. Defaults to `false`. -#### Returns +#### Returns {#returns} `Record`\<`string`, `unknown`\> -#### Inherited from +#### 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 +179,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/functions/createVerifyJwt.md b/docs/references/js/functions/createVerifyJwt.md index 1746416..c7126e8 100644 --- a/docs/references/js/functions/createVerifyJwt.md +++ b/docs/references/js/functions/createVerifyJwt.md @@ -11,9 +11,9 @@ function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): V Creates a function to verify JWT access tokens using the provided key retrieval function and options. -## Parameters +## Parameters {#parameters} -### getKey +### getKey {#getkey} `JWTVerifyGetKey` @@ -23,7 +23,7 @@ The function to retrieve the key used to verify the JWT. JWTVerifyGetKey for the type definition of the key retrieval function. -### options? +### options? {#options} `JWTVerifyOptions` @@ -33,7 +33,7 @@ Optional JWT verification options. JWTVerifyOptions for the type definition of the options. -## Returns +## Returns {#returns} [`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) @@ -42,6 +42,6 @@ the token is valid. It requires the JWT to contain the fields `iss`, `client_id` 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 {#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 58c8ce8..97175e5 100644 --- a/docs/references/js/functions/fetchServerConfig.md +++ b/docs/references/js/functions/fetchServerConfig.md @@ -13,27 +13,27 @@ Fetches the server configuration according to the issuer and authorization serve 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. -## Parameters +## Parameters {#parameters} -### issuer +### issuer {#issuer} `string` The issuer URL of the authorization server. -### config +### config {#config} `ServerMetadataConfig` 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. -## 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 @@ -41,7 +41,7 @@ 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'; @@ -54,11 +54,11 @@ const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { typ 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. diff --git a/docs/references/js/functions/fetchServerConfigByWellKnownUrl.md b/docs/references/js/functions/fetchServerConfigByWellKnownUrl.md index c02019b..ebc56b5 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` 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. -## 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/getIssuer.md b/docs/references/js/functions/getIssuer.md index 701c77b..0ce55ef 100644 --- a/docs/references/js/functions/getIssuer.md +++ b/docs/references/js/functions/getIssuer.md @@ -13,12 +13,12 @@ Get the issuer URL from an auth server config. - Resolved config: extracts from `metadata.issuer` - Discovery config: returns `issuer` directly -## Parameters +## Parameters {#parameters} -### config +### config {#config} [`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md) -## Returns +## Returns {#returns} `string` diff --git a/docs/references/js/functions/handleBearerAuth.md b/docs/references/js/functions/handleBearerAuth.md index 1b1e42c..ddb403e 100644 --- a/docs/references/js/functions/handleBearerAuth.md +++ b/docs/references/js/functions/handleBearerAuth.md @@ -23,20 +23,20 @@ if not, it responds with an appropriate error message. AuthInfo interface defined in the `@modelcontextprotocol/sdk` module. See the extended interface in this file for details. -## Parameters +## Parameters {#parameters} -### param0 +### param0 {#param0} [`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) Configuration for the Bearer auth handler. -## Returns +## Returns {#returns} `RequestHandler` A middleware function for Express that handles Bearer auth. -## See +## See {#see} [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) for the configuration options. diff --git a/docs/references/js/type-aliases/AuthServerConfigError.md b/docs/references/js/type-aliases/AuthServerConfigError.md index 926e985..05371c1 100644 --- a/docs/references/js/type-aliases/AuthServerConfigError.md +++ b/docs/references/js/type-aliases/AuthServerConfigError.md @@ -14,9 +14,9 @@ type AuthServerConfigError = { Represents an error that occurs during the validation of the authorization server metadata. -## Properties +## Properties {#properties} -### cause? +### cause? {#cause} ```ts optional cause: Error; @@ -26,7 +26,7 @@ An optional cause of the error, typically an instance of `Error` that provides m *** -### code +### code {#code} ```ts code: AuthServerConfigErrorCode; @@ -36,7 +36,7 @@ The code representing the specific validation error. *** -### description +### description {#description} ```ts description: string; diff --git a/docs/references/js/type-aliases/AuthServerConfigWarning.md b/docs/references/js/type-aliases/AuthServerConfigWarning.md index 42a33f7..f093e35 100644 --- a/docs/references/js/type-aliases/AuthServerConfigWarning.md +++ b/docs/references/js/type-aliases/AuthServerConfigWarning.md @@ -13,9 +13,9 @@ type AuthServerConfigWarning = { Represents a warning that occurs during the validation of the authorization server metadata. -## Properties +## Properties {#properties} -### code +### code {#code} ```ts code: AuthServerConfigWarningCode; @@ -25,7 +25,7 @@ The code representing the specific validation warning. *** -### description +### description {#description} ```ts description: string; diff --git a/docs/references/js/type-aliases/AuthServerDiscoveryConfig.md b/docs/references/js/type-aliases/AuthServerDiscoveryConfig.md index 2e99b93..108c4d0 100644 --- a/docs/references/js/type-aliases/AuthServerDiscoveryConfig.md +++ b/docs/references/js/type-aliases/AuthServerDiscoveryConfig.md @@ -17,7 +17,7 @@ Use this when you want the metadata to be fetched on-demand via discovery when f This is useful for edge runtimes like Cloudflare Workers where top-level async fetch is not allowed. -## Example +## Example {#example} ```typescript const mcpAuth = new MCPAuth({ @@ -33,9 +33,9 @@ const mcpAuth = new MCPAuth({ }); ``` -## Properties +## Properties {#properties} -### issuer +### issuer {#issuer} ```ts issuer: string; @@ -46,7 +46,7 @@ well-known endpoint derived from this issuer. *** -### type +### type {#type} ```ts type: AuthServerType; @@ -54,6 +54,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/AuthServerModeConfig.md b/docs/references/js/type-aliases/AuthServerModeConfig.md index 6cb5594..da4c827 100644 --- a/docs/references/js/type-aliases/AuthServerModeConfig.md +++ b/docs/references/js/type-aliases/AuthServerModeConfig.md @@ -12,13 +12,13 @@ type AuthServerModeConfig = { Configuration for the legacy, MCP server as authorization server mode. -## Deprecated +## Deprecated {#deprecated} Use `ResourceServerModeConfig` config instead. -## Properties +## Properties {#properties} -### ~~server~~ +### ~~server~~ {#server} ```ts server: AuthServerConfig; @@ -26,6 +26,6 @@ server: AuthServerConfig; The single authorization server configuration. -#### Deprecated +#### Deprecated {#deprecated} Use `protectedResources` config instead. diff --git a/docs/references/js/type-aliases/AuthorizationServerMetadata.md b/docs/references/js/type-aliases/AuthorizationServerMetadata.md index b903d81..055f293 100644 --- a/docs/references/js/type-aliases/AuthorizationServerMetadata.md +++ b/docs/references/js/type-aliases/AuthorizationServerMetadata.md @@ -10,6 +10,6 @@ type AuthorizationServerMetadata = z.infer diff --git a/docs/references/js/variables/authorizationServerMetadataSchema.md b/docs/references/js/variables/authorizationServerMetadataSchema.md index 813b8ba..64ec501 100644 --- a/docs/references/js/variables/authorizationServerMetadataSchema.md +++ b/docs/references/js/variables/authorizationServerMetadataSchema.md @@ -34,6 +34,6 @@ const authorizationServerMetadataSchema: ZodObject<{ Zod schema for OAuth 2.0 Authorization Server Metadata as defined in RFC 8414. -## See +## See {#see} https://datatracker.ietf.org/doc/html/rfc8414 diff --git a/docs/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md b/docs/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md index e4a9b33..b8c34d5 100644 --- a/docs/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md +++ b/docs/references/js/variables/camelCaseAuthorizationServerMetadataSchema.md @@ -34,6 +34,6 @@ const camelCaseAuthorizationServerMetadataSchema: ZodObject<{ The camelCase version of the OAuth 2.0 Authorization Server Metadata Zod schema. -## See +## 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 index 603a8e9..086f269 100644 --- a/docs/references/js/variables/camelCaseProtectedResourceMetadataSchema.md +++ b/docs/references/js/variables/camelCaseProtectedResourceMetadataSchema.md @@ -26,6 +26,6 @@ const camelCaseProtectedResourceMetadataSchema: ZodObject<{ The camelCase version of the OAuth 2.0 Protected Resource Metadata Zod schema. -## See +## See {#see} [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) for the original schema and field information. 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 index 7fca7ea..3818cfb 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/references/js/README.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/README.md @@ -21,6 +21,7 @@ sidebar_label: Node.js SDK - [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) @@ -33,6 +34,7 @@ sidebar_label: Node.js SDK - [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) @@ -56,4 +58,5 @@ sidebar_label: Node.js SDK - [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 index 9cfb817..0cd1581 100644 --- 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 @@ -4,7 +4,7 @@ sidebar_label: MCPAuth # Klasse: MCPAuth -Die Hauptklasse für die mcp-auth-Bibliothek. Sie fungiert als Factory und Registry zur Erstellung von Authentifizierungsrichtlinien für deine geschützten Ressourcen. +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. @@ -14,17 +14,44 @@ Sie wird mit deinen Serverkonfigurationen initialisiert und stellt eine `bearerA 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, fetchServerConfig } from 'mcp-auth'; +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` kann ein einzelnes Konfigurationsobjekt oder ein Array davon sein. protectedResources: [ { metadata: { @@ -35,7 +62,11 @@ const mcpAuth = new MCPAuth({ }, ], }); +``` + +#### Verwendung der Middleware {#using-the-middleware} +```ts // Router für Protected Resource Metadata einbinden app.use(mcpAuth.protectedResourceMetadataRouter()); @@ -44,7 +75,7 @@ app.get( '/notes', mcpAuth.bearerAuth('jwt', { resource: resourceIdentifier, // Gibt an, zu welcher Ressource dieser Endpunkt gehört - audience: resourceIdentifier, // Optional: Überprüfe den 'aud'-Anspruch + audience: resourceIdentifier, // Optional: das 'aud'-Claim validieren requiredScopes: ['read:notes'], }), (req, res) => { @@ -60,14 +91,12 @@ Dieser Ansatz wird aus Gründen der Abwärtskompatibilität unterstützt. ```ts import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; +import { MCPAuth } from 'mcp-auth'; const app = express(); const mcpAuth = new MCPAuth({ - server: await fetchServerConfig( - 'https://auth.logto.io/oidc', - { type: 'oidc' } - ), + // Discovery-Konfiguration – Metadaten werden bei Bedarf abgerufen + server: { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }, }); // Router für Legacy Authorization Server Metadata einbinden @@ -79,7 +108,7 @@ app.get( mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), (req, res) => { console.log('Auth info:', req.auth); - // Bearbeite hier die MCP-Anfrage + // Hier die MCP-Anfrage bearbeiten }, ); ``` @@ -153,7 +182,7 @@ Optionale Konfiguration für den Bearer-Auth-Handler. **Siehe** -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) für die verfügbaren Konfigurationsoptionen (außer +[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) für die verfügbaren Konfigurationsoptionen (ohne `verifyAccessToken` und `issuer`). ##### Rückgabewert {#returns} @@ -165,8 +194,8 @@ Eine Express-Middleware-Funktion, die das Zugangstoken (Access token) überprüf ##### Siehe {#see} -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) für Details zur Implementierung und die erweiterten Typen des -`req.auth` (`AuthInfo`)-Objekts. +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) für die Implementierungsdetails und die erweiterten Typen des +`req.auth` (`AuthInfo`) Objekts. #### Aufrufsignatur {#call-signature} @@ -178,7 +207,7 @@ Erstellt einen Bearer-Auth-Handler (Express-Middleware), der das Zugangstoken (A `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 Autorisierungsservers. +von der JWKS-URI des Authorization Servers. ##### Parameter {#parameters} @@ -186,7 +215,7 @@ von der JWKS-URI des Autorisierungsservers. `"jwt"` -Der Verifizierungsmodus für das Zugangstoken (Access token). Aktuell wird nur 'jwt' unterstützt. +Der Verifizierungsmodus für das Zugangstoken (Access token). Derzeit wird nur 'jwt' unterstützt. **Siehe** @@ -203,7 +232,7 @@ Remote-JWK-Set-Optionen. - 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 (außer + - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) für die verfügbaren Konfigurationsoptionen (ohne `verifyAccessToken` und `issuer`). ##### Rückgabewert {#returns} @@ -215,12 +244,12 @@ Eine Express-Middleware-Funktion, die das Zugangstoken (Access token) überprüf ##### Siehe {#see} -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) für Details zur Implementierung und die erweiterten Typen des -`req.auth` (`AuthInfo`)-Objekts. +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) für die Implementierungsdetails und die erweiterten Typen des +`req.auth` (`AuthInfo`) Objekts. -##### Fehler {#throws} +##### Wirft {#throws} -wenn die JWKS-URI nicht in den Server-Metadaten angegeben ist, wenn +wenn die JWKS-URI in den Server-Metadaten nicht angegeben ist, wenn der `'jwt'`-Modus verwendet wird. *** @@ -231,15 +260,15 @@ der `'jwt'`-Modus verwendet wird. delegatedRouter(): Router; ``` -Erstellt einen Delegated Router zum Bereitstellen des veralteten OAuth 2.0 Authorization Server Metadata Endpunkts -(`/.well-known/oauth-authorization-server`) mit den der Instanz bereitgestellten Metadaten. +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 Endpunkt mit den -bereitgestellten Metadaten der Instanz bedient. +Ein Router, der den OAuth 2.0 Authorization Server Metadata Endpoint mit den +der Instanz bereitgestellten Metadaten bereitstellt. #### Veraltet {#deprecated} @@ -256,7 +285,7 @@ const mcpAuth: MCPAuth; // Angenommen, dies ist initialisiert app.use(mcpAuth.delegatedRouter()); ``` -#### Fehler {#throws} +#### Wirft {#throws} Wenn im `Resource Server`-Modus aufgerufen. @@ -268,7 +297,7 @@ Wenn im `Resource Server`-Modus aufgerufen. protectedResourceMetadataRouter(): Router; ``` -Erstellt einen Router, der den OAuth 2.0 Protected Resource Metadata Endpunkt +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 @@ -278,9 +307,9 @@ Ressourcenkennung, die in deiner Konfiguration angegeben ist. `Router` -Ein Router, der den OAuth 2.0 Protected Resource Metadata Endpunkt bereitstellt. +Ein Router, der den OAuth 2.0 Protected Resource Metadata Endpoint bereitstellt. -#### Fehler {#throws} +#### Wirft {#throws} Wenn im `Authorization Server`-Modus aufgerufen. 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 index 5ae6512..67fbe95 100644 --- 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 @@ -100,21 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -Die Eigenschaft `Error.stackTraceLimit` gibt die Anzahl der Stack-Frames an, -die von einem Stack-Trace gesammelt werden (egal ob durch `new Error().stack` oder -`Error.captureStackTrace(obj)` erzeugt). +Optionale Überschreibung zur Formatierung von Stacktraces + +#### Parameter {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -Der Standardwert ist `10`, kann aber auf jede gültige JavaScript-Zahl gesetzt werden. Änderungen -wirken sich auf jeden Stack-Trace aus, der _nachdem_ der Wert geändert wurde, erfasst wird. +`CallSite`[] -Wenn ein ungültiger Wert oder eine negative Zahl gesetzt wird, werden keine Stack-Frames -im Stack-Trace erfasst. +#### 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} @@ -155,49 +177,7 @@ Standardmäßig `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Erstellt eine `.stack`-Eigenschaft auf `targetObject`, die beim Zugriff -einen String zurückgibt, der den Ort im Code repräsentiert, an dem -`Error.captureStackTrace()` aufgerufen wurde. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Ähnlich wie `new Error().stack` -``` - -Die erste Zeile des Traces wird mit -`${myObject.name}: ${myObject.message}` vorangestellt. - -Das optionale Argument `constructorOpt` akzeptiert eine Funktion. Wenn angegeben, werden alle Frames -oberhalb von `constructorOpt`, einschließlich `constructorOpt`, aus dem -generierten Stack-Trace ausgelassen. - -Das Argument `constructorOpt` ist nützlich, um Implementierungsdetails -der Fehlererzeugung vor dem Benutzer zu verbergen. Zum Beispiel: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Erzeuge einen Fehler ohne Stack-Trace, um die Berechnung des Stack-Traces zweimal zu vermeiden. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Erfasse den Stack-Trace oberhalb der Funktion b - Error.captureStackTrace(error, b); // Weder Funktion c noch b sind im Stack-Trace enthalten - throw error; -} - -a(); -``` +Erstellt die .stack-Eigenschaft auf einem Zielobjekt #### Parameter {#parameters} @@ -216,33 +196,3 @@ a(); #### Geerbt von {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### 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) 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 index 8bcaa4e..c70f4af 100644 --- 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 @@ -6,7 +6,7 @@ sidebar_label: MCPAuthBearerAuthError Fehler, der ausgelöst wird, wenn es ein Problem bei der Authentifizierung mit Bearer-Tokens gibt. -## Erbt von {#extends} +## Erweitert {#extends} - [`MCPAuthError`](/references/js/classes/MCPAuthError.md) @@ -100,21 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -Die Eigenschaft `Error.stackTraceLimit` gibt die Anzahl der Stack-Frames an, -die von einem Stack-Trace gesammelt werden (egal ob durch `new Error().stack` oder -`Error.captureStackTrace(obj)` erzeugt). +Optionale Überschreibung zur Formatierung von Stacktraces + +#### Parameter {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -Der Standardwert ist `10`, kann aber auf jede gültige JavaScript-Zahl gesetzt werden. Änderungen -wirken sich auf jeden Stack-Trace aus, der _nachdem_ der Wert geändert wurde, erfasst wird. +`CallSite`[] -Wenn ein ungültiger Wert oder eine negative Zahl gesetzt wird, werden keine Stack-Frames -erfasst. +#### 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} @@ -137,7 +159,7 @@ Konvertiert den Fehler in ein HTTP-Response-freundliches JSON-Format. `boolean` = `false` Gibt an, ob die Ursache des Fehlers in der JSON-Antwort enthalten sein soll. -Standard ist `false`. +Standardmäßig `false`. #### Rückgabewert {#returns} @@ -155,49 +177,7 @@ Standard ist `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Erstellt eine `.stack`-Eigenschaft auf `targetObject`, die beim Zugriff -einen String zurückgibt, der den Ort im Code darstellt, an dem -`Error.captureStackTrace()` aufgerufen wurde. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Ähnlich wie `new Error().stack` -``` - -Die erste Zeile des Traces wird mit -`${myObject.name}: ${myObject.message}` vorangestellt. - -Das optionale Argument `constructorOpt` akzeptiert eine Funktion. Falls angegeben, werden alle Frames -oberhalb von `constructorOpt`, einschließlich `constructorOpt`, aus dem -generierten Stack-Trace ausgelassen. - -Das Argument `constructorOpt` ist nützlich, um Implementierungsdetails -der Fehlererzeugung vor dem Benutzer zu verbergen. Zum Beispiel: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Erzeuge einen Fehler ohne Stack-Trace, um die Berechnung des Stack-Traces zweimal zu vermeiden. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Erfasse den Stack-Trace oberhalb der Funktion b - Error.captureStackTrace(error, b); // Weder Funktion c noch b sind im Stack-Trace enthalten - throw error; -} - -a(); -``` +Erstellt die .stack-Eigenschaft auf einem Zielobjekt #### Parameter {#parameters} @@ -216,33 +196,3 @@ a(); #### Geerbt von {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### 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) 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 index 7a8480f..0103c4e 100644 --- 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 @@ -4,7 +4,7 @@ sidebar_label: MCPAuthConfigError # Klasse: MCPAuthConfigError -Fehler, der ausgelöst wird, wenn es ein Konfigurationsproblem mit mcp-auth gibt. +Fehler, der ausgelöst wird, wenn ein Konfigurationsproblem mit mcp-auth vorliegt. ## Erbt von {#extends} @@ -104,17 +104,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -Die Eigenschaft `Error.stackTraceLimit` gibt die Anzahl der Stack-Frames an, die von einem Stack-Trace gesammelt werden (egal ob durch `new Error().stack` oder `Error.captureStackTrace(obj)` erzeugt). +Optionale Überschreibung zur Formatierung von Stacktraces + +#### Parameter {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -Der Standardwert ist `10`, kann aber auf jede gültige JavaScript-Zahl gesetzt werden. Änderungen wirken sich auf alle Stack-Traces aus, die _nach_ der Änderung des Wertes erfasst werden. +`CallSite`[] -Wenn ein ungültiger Wert (kein Zahlwert) oder ein negativer Wert gesetzt wird, werden keine Stack-Frames erfasst. +#### 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} @@ -137,7 +163,7 @@ Konvertiert den Fehler in ein HTTP-Response-freundliches JSON-Format. `boolean` = `false` Ob die Ursache des Fehlers in der JSON-Antwort enthalten sein soll. -Standard ist `false`. +Standardmäßig `false`. #### Rückgabe {#returns} @@ -155,44 +181,7 @@ Standard ist `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Erstellt eine `.stack`-Eigenschaft auf `targetObject`, die beim Zugriff einen String zurückgibt, der den Ort im Code darstellt, an dem `Error.captureStackTrace()` aufgerufen wurde. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Ähnlich wie `new Error().stack` -``` - -Die erste Zeile des Traces wird mit -`${myObject.name}: ${myObject.message}` vorangestellt. - -Das optionale Argument `constructorOpt` akzeptiert eine Funktion. Wenn angegeben, werden alle Frames oberhalb von `constructorOpt`, einschließlich `constructorOpt`, aus dem generierten Stack-Trace ausgelassen. - -Das Argument `constructorOpt` ist nützlich, um Implementierungsdetails der Fehlererzeugung vor dem Benutzer zu verbergen. Zum Beispiel: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Erzeuge einen Fehler ohne Stack-Trace, um die Berechnung des Stack-Traces zweimal zu vermeiden. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Erfasse den Stack-Trace oberhalb der Funktion b - Error.captureStackTrace(error, b); // Weder Funktion c noch b sind im Stack-Trace enthalten - throw error; -} - -a(); -``` +Erstellt die .stack-Eigenschaft auf einem Zielobjekt #### Parameter {#parameters} @@ -211,33 +200,3 @@ a(); #### Geerbt von {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### 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) 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 index 4b64268..88dce09 100644 --- 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 @@ -119,21 +119,45 @@ Error.stack *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -Die Eigenschaft `Error.stackTraceLimit` gibt die Anzahl der Stack-Frames an, -die von einem Stack-Trace gesammelt werden (egal ob durch `new Error().stack` oder -`Error.captureStackTrace(obj)` erzeugt). +Optionale Überschreibung zur Formatierung von Stacktraces + +#### Parameter {#parameters} + +##### err {#err} -Der Standardwert ist `10`, kann aber auf jede gültige JavaScript-Zahl gesetzt werden. Änderungen -wirken sich auf alle Stack-Traces aus, die _nachdem_ der Wert geändert wurde, erfasst werden. +`Error` -Wenn auf einen Nicht-Zahlenwert oder auf eine negative Zahl gesetzt, werden keine Frames -im Stack-Trace erfasst. +##### 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} @@ -172,47 +196,7 @@ Standardmäßig `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Erstellt eine `.stack`-Eigenschaft auf `targetObject`, die beim Zugriff -einen String zurückgibt, der den Ort im Code repräsentiert, an dem -`Error.captureStackTrace()` aufgerufen wurde. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Ähnlich wie `new Error().stack` -``` - -Die erste Zeile des Traces wird mit -`${myObject.name}: ${myObject.message}` vorangestellt. - -Das optionale Argument `constructorOpt` akzeptiert eine Funktion. Falls angegeben, werden alle Frames -oberhalb von `constructorOpt`, einschließlich `constructorOpt`, aus dem generierten Stack-Trace entfernt. - -Das Argument `constructorOpt` ist nützlich, um Implementierungsdetails der Fehlererzeugung vor dem Benutzer zu verbergen. Zum Beispiel: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Erzeuge einen Fehler ohne Stack-Trace, um die Berechnung des Stack-Traces zweimal zu vermeiden. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Erfasse den Stack-Trace oberhalb der Funktion b - Error.captureStackTrace(error, b); // Weder Funktion c noch b sind im Stack-Trace enthalten - throw error; -} - -a(); -``` +Erstellt die .stack Eigenschaft auf einem Zielobjekt #### Parameter {#parameters} @@ -233,35 +217,3 @@ a(); ```ts Error.captureStackTrace ``` - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### 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 -``` 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 index c715dfd..ef70223 100644 --- 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 @@ -100,17 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -Die Eigenschaft `Error.stackTraceLimit` gibt die Anzahl der Stack-Frames an, die von einem Stack-Trace gesammelt werden (egal ob durch `new Error().stack` oder `Error.captureStackTrace(obj)` generiert). +Optionale Überschreibung zur Formatierung von Stacktraces + +#### Parameter {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -Der Standardwert ist `10`, kann aber auf jede gültige JavaScript-Zahl gesetzt werden. Änderungen wirken sich auf alle Stack-Traces aus, die _nachdem_ der Wert geändert wurde, erfasst werden. +`CallSite`[] -Wenn ein ungültiger Wert (kein Zahlwert oder negativ) gesetzt wird, werden keine Stack-Frames erfasst. +#### 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} @@ -124,7 +150,7 @@ Wenn ein ungültiger Wert (kein Zahlwert oder negativ) gesetzt wird, werden kein toJson(showCause: boolean): Record; ``` -Konvertiert den Fehler in ein HTTP-Response-freundliches JSON-Format. +Wandelt den Fehler in ein HTTP-Response-freundliches JSON-Format um. #### Parameter {#parameters} @@ -132,8 +158,8 @@ Konvertiert den Fehler in ein HTTP-Response-freundliches JSON-Format. `boolean` = `false` -Legt fest, ob die Ursache des Fehlers in der JSON-Antwort enthalten sein soll. -Standard ist `false`. +Gibt an, ob die Ursache des Fehlers in der JSON-Antwort enthalten sein soll. +Standardmäßig `false`. #### Rückgabewert {#returns} @@ -151,44 +177,7 @@ Standard ist `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Erstellt eine `.stack`-Eigenschaft auf `targetObject`, die beim Zugriff einen String zurückgibt, der den Ort im Code darstellt, an dem `Error.captureStackTrace()` aufgerufen wurde. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Ähnlich wie `new Error().stack` -``` - -Die erste Zeile des Traces wird mit -`${myObject.name}: ${myObject.message}` vorangestellt. - -Das optionale Argument `constructorOpt` akzeptiert eine Funktion. Falls angegeben, werden alle Frames oberhalb von `constructorOpt`, einschließlich `constructorOpt`, aus dem generierten Stack-Trace ausgelassen. - -Das Argument `constructorOpt` ist nützlich, um Implementierungsdetails der Fehlererzeugung vor dem Benutzer zu verbergen. Zum Beispiel: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Erzeuge einen Fehler ohne Stack-Trace, um die Berechnung des Stack-Traces doppelt zu vermeiden. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Erfasse den Stack-Trace oberhalb der Funktion b - Error.captureStackTrace(error, b); // Weder Funktion c noch b sind im Stack-Trace enthalten - throw error; -} - -a(); -``` +Erstellt die .stack-Eigenschaft auf einem Zielobjekt #### Parameter {#parameters} @@ -207,33 +196,3 @@ a(); #### Geerbt von {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### 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) 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 index c7c2e96..66ef89c 100644 --- 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 @@ -20,7 +20,7 @@ Die Funktion zum Abrufen des Schlüssels, der zur Überprüfung des JWT verwende **Siehe** -JWTVerifyGetKey für die Typdefinition der Schlüsselabruf-Funktion. +JWTVerifyGetKey für die Typdefinition der Schlüsselabruffunktion. ### options? {#options} @@ -36,7 +36,7 @@ JWTVerifyOptions für die Typdefinition der Optionen. [`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. Das JWT muss die Felder `iss`, `client_id` und `sub` im Payload enthalten und kann optional die Felder `scope` oder `scopes` enthalten. Die Funktion verwendet intern die `jose`-Bibliothek, um die JWT-Überprüfung durchzuführen. +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} 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 index aff6d93..ef52dcb 100644 --- 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 @@ -5,12 +5,12 @@ sidebar_label: fetchServerConfig # Funktion: fetchServerConfig() ```ts -function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; +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- und OpenID Connect-Server unterschiedliche Konventionen für ihre Metadatenendpunkte haben. +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} @@ -18,7 +18,7 @@ Diese Funktion bestimmt automatisch die Well-Known-URL basierend auf dem Servert `string` -Die Aussteller-URL (Issuer) des Autorisierungsservers. +Die Aussteller-URL (Issuer URL) des Autorisierungsservers. ### config {#config} @@ -28,25 +28,25 @@ Das Konfigurationsobjekt, das den Servertyp und eine optionale Transpilierungsfu ## Rückgabewert {#returns} -`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> +`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -Ein Promise, das mit der Serverkonfiguration aufgelöst wird. +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 Discovery 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-Serverkonfiguration +// 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-Serverkonfiguration +// 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' }); ``` @@ -57,4 +57,4 @@ wenn der Abrufvorgang fehlschlägt. ## Fehlerauslösung {#throws} -wenn die Servermetadaten ungültig sind oder nicht der MCP-Spezifikation entsprechen. +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 index 0191ecc..b6ffce8 100644 --- 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 @@ -5,18 +5,22 @@ sidebar_label: fetchServerConfigByWellKnownUrl # Funktion: fetchServerConfigByWellKnownUrl() ```ts -function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; +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. +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. +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. +Die Well-Known-URL, von der die Serverkonfiguration abgerufen werden soll. Dies kann ein +String oder ein URL-Objekt sein. `string` | `URL` @@ -24,13 +28,13 @@ Die Well-Known-URL, von der die Serverkonfiguration abgerufen werden soll. Dies `ServerMetadataConfig` -Das Konfigurationsobjekt, das den Servertyp und eine optionale Transpile-Funktion enthält. +Das Konfigurationsobjekt, das den Servertyp und optional eine Transpile-Funktion enthält. ## Rückgabewert {#returns} -`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> +`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -Ein Promise, das mit der Serverkonfiguration aufgelöst wird. +Ein Promise, das mit der statischen Serverkonfiguration und den abgerufenen Metadaten aufgelöst wird. ## Löst aus {#throws} @@ -38,4 +42,5 @@ wenn der Abrufvorgang fehlschlägt. ## Löst aus {#throws} -wenn die Server-Metadaten ungültig sind oder nicht der MCP-Spezifikation entsprechen. +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 new file mode 100644 index 0000000..ce75b9c --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md @@ -0,0 +1,24 @@ +--- +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 index c6cd79b..b8d551f 100644 --- 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 @@ -8,16 +8,16 @@ sidebar_label: handleBearerAuth function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; ``` -Erstellt eine Middleware-Funktion zur Behandlung von Bearer-Authentifizierung in einer Express-Anwendung. +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, werden die Authentifizierungsinformationen im Feld `request.auth` hinzugefügt; andernfalls wird mit einer entsprechenden Fehlermeldung geantwortet. +- 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 unerwartete Fehler während des Authentifizierungsprozesses auftreten, werden diese von der Middleware erneut ausgelöst. +- 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. +**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} @@ -31,7 +31,7 @@ Konfiguration für den Bearer-Authentifizierungs-Handler. `RequestHandler` -Eine Middleware-Funktion für Express, die Bearer-Authentifizierung behandelt. +Eine Middleware-Funktion für Express, die die Bearer-Authentifizierung behandelt. ## Siehe auch {#see} 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 index 50782b9..cc6092e 100644 --- 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 @@ -5,45 +5,13 @@ sidebar_label: AuthServerConfig # Typalias: AuthServerConfig ```ts -type AuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; - type: AuthServerType; -}; +type AuthServerConfig = + | ResolvedAuthServerConfig + | AuthServerDiscoveryConfig; ``` -Konfiguration für den entfernten Autorisierungsserver, der mit dem MCP-Server integriert ist. +Konfiguration für den entfernten Autorisierungsserver (Authorization server), der mit dem MCP-Server integriert ist. -## Eigenschaften {#properties} - -### metadata {#metadata} - -```ts -metadata: CamelCaseAuthorizationServerMetadata; -``` - -Die Metadaten des Autorisierungsservers (authorization server), die der MCP-Spezifikation entsprechen sollten -(basierend auf OAuth 2.0 Authorization Server Metadata). - -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, falls 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. \ No newline at end of file +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/AuthServerConfigWarning.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md index 4c7fa60..b803176 100644 --- 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 @@ -21,7 +21,7 @@ Stellt eine Warnung dar, die während der Validierung der Metadaten des Autorisi code: AuthServerConfigWarningCode; ``` -Der Code, der die spezifische Validierungswarnung repräsentiert. +Der Code, der die spezifische Validierungswarnung darstellt. *** @@ -31,4 +31,4 @@ Der Code, der die spezifische Validierungswarnung repräsentiert. description: string; ``` -Eine für Menschen lesbare Beschreibung der Warnung. \ No newline at end of file +Eine für Menschen lesbare Beschreibung der Warnung. 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 new file mode 100644 index 0000000..31a5505 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md @@ -0,0 +1,59 @@ +--- +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/AuthServerModeConfig.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md index 6950046..9352a7e 100644 --- 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 @@ -10,7 +10,7 @@ type AuthServerModeConfig = { }; ``` -Konfiguration für den veralteten MCP-Server im Autorisierungsserver-Modus. +Konfiguration für den veralteten, MCP-Server als Autorisierungsserver-Modus. ## Veraltet {#deprecated} 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 index 3d9694d..561617e 100644 --- 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 @@ -5,232 +5,11 @@ sidebar_label: AuthorizationServerMetadata # Typalias: AuthorizationServerMetadata ```ts -type AuthorizationServerMetadata = { - authorization_endpoint: string; - code_challenge_methods_supported?: string[]; - grant_types_supported?: string[]; - introspection_endpoint?: string; - introspection_endpoint_auth_methods_supported?: string[]; - introspection_endpoint_auth_signing_alg_values_supported?: string[]; - issuer: string; - jwks_uri?: string; - op_policy_uri?: string; - op_tos_uri?: string; - registration_endpoint?: string; - response_modes_supported?: string[]; - response_types_supported: string[]; - revocation_endpoint?: string; - revocation_endpoint_auth_methods_supported?: string[]; - revocation_endpoint_auth_signing_alg_values_supported?: string[]; - scopes_supported?: string[]; - service_documentation?: string; - token_endpoint: string; - token_endpoint_auth_methods_supported?: string[]; - token_endpoint_auth_signing_alg_values_supported?: string[]; - ui_locales_supported?: string[]; - userinfo_endpoint?: string; -}; +type AuthorizationServerMetadata = z.infer; ``` Schema für OAuth 2.0 Authorization Server Metadata wie in RFC 8414 definiert. -## Typdeklaration {#type-declaration} - -### authorization\_endpoint {#authorization-endpoint} - -```ts -authorization_endpoint: string; -``` - -URL des Authorization Servers für den Authorization Endpoint [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. -Dies ist ERFORDERLICH, es sei denn, es werden keine Grant Types unterstützt, die den Authorization Endpoint verwenden. - -#### Siehe {#see} - -https://rfc-editor.org/rfc/rfc6749#section-3.1 - -### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} - -```ts -optional code_challenge_methods_supported: string[]; -``` - -JSON-Array mit einer Liste der Proof Key for Code Exchange (PKCE) -[[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] Code-Challenge-Methoden, die von diesem Authorization Server unterstützt werden. - -### grant\_types\_supported? {#grant-types-supported} - -```ts -optional grant_types_supported: string[]; -``` - -JSON-Array mit einer Liste der OAuth 2.0 Grant Type-Werte, die dieser Authorization Server unterstützt. -Die Array-Werte entsprechen denen, die mit dem `grant_types`-Parameter verwendet werden, -wie im "OAuth 2.0 Dynamic Client Registration Protocol" [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)] definiert. -Wenn weggelassen, ist der Standardwert `["authorization_code", "implicit"]`. - -### introspection\_endpoint? {#introspection-endpoint} - -```ts -optional introspection_endpoint: string; -``` - -URL des OAuth 2.0 Introspection Endpoints des Authorization Servers -[[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]. - -### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} - -```ts -optional introspection_endpoint_auth_methods_supported: string[]; -``` - -### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} - -```ts -optional introspection_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### issuer {#issuer} - -```ts -issuer: string; -``` - -Der Issuer-Identifier (Aussteller) des Authorization Servers, eine URL, die das `https`-Schema verwendet und -keine Query- oder Fragment-Komponenten enthält. - -### jwks\_uri? {#jwks-uri} - -```ts -optional jwks_uri: string; -``` - -URL des JWK Set [[JWK](https://www.rfc-editor.org/rfc/rfc8414.html#ref-JWK)] -Dokuments des Authorization Servers. Das referenzierte Dokument enthält die Signaturschlüssel, die der Client verwendet, -um Signaturen des Authorization Servers zu validieren. Diese URL MUSS das `https`-Schema verwenden. - -### op\_policy\_uri? {#op-policy-uri} - -```ts -optional op_policy_uri: string; -``` - -### op\_tos\_uri? {#op-tos-uri} - -```ts -optional op_tos_uri: string; -``` - -### registration\_endpoint? {#registration-endpoint} - -```ts -optional registration_endpoint: string; -``` - -URL des OAuth 2.0 Dynamic Client Registration Endpoints des Authorization Servers -[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. - -### response\_modes\_supported? {#response-modes-supported} - -```ts -optional response_modes_supported: string[]; -``` - -JSON-Array mit einer Liste der OAuth 2.0 `response_mode`-Werte, die dieser Authorization Server unterstützt, -wie in "OAuth 2.0 Multiple Response Type Encoding Practices" spezifiziert -[[OAuth.Responses](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Responses)]. - -Wenn weggelassen, ist der Standardwert `["query", "fragment"]`. Der Response Mode-Wert `"form_post"` ist -ebenfalls in "OAuth 2.0 Form Post Response Mode" definiert -[[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)]. - -### response\_types\_supported {#response-types-supported} - -```ts -response_types_supported: string[]; -``` - -JSON-Array mit einer Liste der OAuth 2.0 `response_type`-Werte, die dieser Authorization Server unterstützt. -Die Array-Werte entsprechen denen, die mit dem `response_types`-Parameter verwendet werden, -wie im "OAuth 2.0 Dynamic Client Registration Protocol" -[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)] definiert. - -### revocation\_endpoint? {#revocation-endpoint} - -```ts -optional revocation_endpoint: string; -``` - -URL des OAuth 2.0 Revocation Endpoints des Authorization Servers -[[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]. - -### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} - -```ts -optional revocation_endpoint_auth_methods_supported: string[]; -``` - -### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} - -```ts -optional revocation_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### scopes\_supported? {#scopes-supported} - -```ts -optional scopes_supported: string[]; -``` - -JSON-Array mit einer Liste der OAuth 2.0 `scope`-Werte, die dieser Authorization Server unterstützt. -[[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] - -### service\_documentation? {#service-documentation} - -```ts -optional service_documentation: string; -``` - -### token\_endpoint {#token-endpoint} - -```ts -token_endpoint: string; -``` - -URL des Token Endpoints des Authorization Servers [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. -Dies ist ERFORDERLICH, es sei denn, nur der Implicit Grant Type wird unterstützt. - -#### Siehe {#see} - -https://rfc-editor.org/rfc/rfc6749#section-3.2 - -### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} - -```ts -optional token_endpoint_auth_methods_supported: string[]; -``` - -### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} - -```ts -optional token_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### ui\_locales\_supported? {#ui-locales-supported} - -```ts -optional ui_locales_supported: string[]; -``` - -### userinfo\_endpoint? {#userinfo-endpoint} - -```ts -optional userinfo_endpoint: string; -``` - -URL des OpenID Connect [userinfo endpoint](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo). -Dieser Endpoint wird verwendet, um Informationen über den authentifizierten Benutzer abzurufen. - ## 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 index be62305..0c38965 100644 --- 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 @@ -44,7 +44,7 @@ issuer: | ValidateIssuerFunction; ``` -Ein String, der einen gültigen Aussteller (Issuer) repräsentiert, oder eine Funktion zur Validierung des Ausstellers des Zugangstokens. +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. @@ -63,10 +63,10 @@ Wenn eine Funktion angegeben wird, sollte sie den Aussteller gemäß den Regeln optional requiredScopes: string[]; ``` -Ein Array der erforderlichen Berechtigungen (Berechtigungen (Scopes)), die das Zugangstoken haben muss. Wenn das Token nicht +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 entweder ein durch Leerzeichen getrennter String oder ein Array von Strings sein kann. Wenn der `scope`-Anspruch nicht vorhanden ist, prüft der Handler den `scopes`-Anspruch, +**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. *** @@ -89,9 +89,8 @@ Dies ist erforderlich, wenn der Handler mit einer `protectedResources`-Konfigura optional showErrorDetails: boolean; ``` -Ob detaillierte Fehlerinformationen in der Antwort angezeigt werden sollen. Dies ist während der Entwicklung nützlich -zum Debuggen, sollte aber in der Produktion deaktiviert werden, um das Leaken sensibler -Informationen zu vermeiden. +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} 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 index 1c68316..4c9cd1b 100644 --- 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 @@ -5,175 +5,11 @@ sidebar_label: CamelCaseAuthorizationServerMetadata # Typalias: CamelCaseAuthorizationServerMetadata ```ts -type CamelCaseAuthorizationServerMetadata = { - authorizationEndpoint: string; - codeChallengeMethodsSupported?: string[]; - grantTypesSupported?: string[]; - introspectionEndpoint?: string; - introspectionEndpointAuthMethodsSupported?: string[]; - introspectionEndpointAuthSigningAlgValuesSupported?: string[]; - issuer: string; - jwksUri?: string; - opPolicyUri?: string; - opTosUri?: string; - registrationEndpoint?: string; - responseModesSupported?: string[]; - responseTypesSupported: string[]; - revocationEndpoint?: string; - revocationEndpointAuthMethodsSupported?: string[]; - revocationEndpointAuthSigningAlgValuesSupported?: string[]; - scopesSupported?: string[]; - serviceDocumentation?: string; - tokenEndpoint: string; - tokenEndpointAuthMethodsSupported?: string[]; - tokenEndpointAuthSigningAlgValuesSupported?: string[]; - uiLocalesSupported?: string[]; - userinfoEndpoint?: string; -}; +type CamelCaseAuthorizationServerMetadata = z.infer; ``` Die camelCase-Version des OAuth 2.0 Authorization Server Metadata-Typs. -## Typdeklaration {#type-declaration} - -### authorizationEndpoint {#authorizationendpoint} - -```ts -authorizationEndpoint: string; -``` - -### codeChallengeMethodsSupported? {#codechallengemethodssupported} - -```ts -optional codeChallengeMethodsSupported: string[]; -``` - -### grantTypesSupported? {#granttypessupported} - -```ts -optional grantTypesSupported: string[]; -``` - -### introspectionEndpoint? {#introspectionendpoint} - -```ts -optional introspectionEndpoint: string; -``` - -### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} - -```ts -optional introspectionEndpointAuthMethodsSupported: string[]; -``` - -### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} - -```ts -optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### issuer {#issuer} - -```ts -issuer: string; -``` - -### jwksUri? {#jwksuri} - -```ts -optional jwksUri: string; -``` - -### opPolicyUri? {#oppolicyuri} - -```ts -optional opPolicyUri: string; -``` - -### opTosUri? {#optosuri} - -```ts -optional opTosUri: string; -``` - -### registrationEndpoint? {#registrationendpoint} - -```ts -optional registrationEndpoint: string; -``` - -### responseModesSupported? {#responsemodessupported} - -```ts -optional responseModesSupported: string[]; -``` - -### responseTypesSupported {#responsetypessupported} - -```ts -responseTypesSupported: string[]; -``` - -### revocationEndpoint? {#revocationendpoint} - -```ts -optional revocationEndpoint: string; -``` - -### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} - -```ts -optional revocationEndpointAuthMethodsSupported: string[]; -``` - -### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} - -```ts -optional revocationEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### scopesSupported? {#scopessupported} - -```ts -optional scopesSupported: string[]; -``` - -### serviceDocumentation? {#servicedocumentation} - -```ts -optional serviceDocumentation: string; -``` - -### tokenEndpoint {#tokenendpoint} - -```ts -tokenEndpoint: string; -``` - -### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} - -```ts -optional tokenEndpointAuthMethodsSupported: string[]; -``` - -### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} - -```ts -optional tokenEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### uiLocalesSupported? {#uilocalessupported} - -```ts -optional uiLocalesSupported: string[]; -``` - -### userinfoEndpoint? {#userinfoendpoint} - -```ts -optional userinfoEndpoint: string; -``` - ## 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 index dcb545b..0870841 100644 --- 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 @@ -5,119 +5,11 @@ sidebar_label: CamelCaseProtectedResourceMetadata # Typalias: CamelCaseProtectedResourceMetadata ```ts -type CamelCaseProtectedResourceMetadata = { - authorizationDetailsTypesSupported?: string[]; - authorizationServers?: string[]; - bearerMethodsSupported?: string[]; - dpopBoundAccessTokensRequired?: boolean; - dpopSigningAlgValuesSupported?: string[]; - jwksUri?: string; - resource: string; - resourceDocumentation?: string; - resourceName?: string; - resourcePolicyUri?: string; - resourceSigningAlgValuesSupported?: string[]; - resourceTosUri?: string; - scopesSupported?: string[]; - signedMetadata?: string; - tlsClientCertificateBoundAccessTokens?: boolean; -}; +type CamelCaseProtectedResourceMetadata = z.infer; ``` Die camelCase-Version des OAuth 2.0 Protected Resource Metadata-Typs. -## Typdeklaration {#type-declaration} - -### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} - -```ts -optional authorizationDetailsTypesSupported: string[]; -``` - -### authorizationServers? {#authorizationservers} - -```ts -optional authorizationServers: string[]; -``` - -### bearerMethodsSupported? {#bearermethodssupported} - -```ts -optional bearerMethodsSupported: string[]; -``` - -### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} - -```ts -optional dpopBoundAccessTokensRequired: boolean; -``` - -### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} - -```ts -optional dpopSigningAlgValuesSupported: string[]; -``` - -### jwksUri? {#jwksuri} - -```ts -optional jwksUri: string; -``` - -### resource {#resource} - -```ts -resource: string; -``` - -### resourceDocumentation? {#resourcedocumentation} - -```ts -optional resourceDocumentation: string; -``` - -### resourceName? {#resourcename} - -```ts -optional resourceName: string; -``` - -### resourcePolicyUri? {#resourcepolicyuri} - -```ts -optional resourcePolicyUri: string; -``` - -### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} - -```ts -optional resourceSigningAlgValuesSupported: string[]; -``` - -### resourceTosUri? {#resourcetosuri} - -```ts -optional resourceTosUri: string; -``` - -### scopesSupported? {#scopessupported} - -```ts -optional scopesSupported: string[]; -``` - -### signedMetadata? {#signedmetadata} - -```ts -optional signedMetadata: string; -``` - -### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} - -```ts -optional tlsClientCertificateBoundAccessTokens: boolean; -``` - ## 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/ProtectedResourceMetadata.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md index 5e90e15..be5d259 100644 --- 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 @@ -5,153 +5,7 @@ sidebar_label: ProtectedResourceMetadata # Typalias: ProtectedResourceMetadata ```ts -type ProtectedResourceMetadata = { - authorization_details_types_supported?: string[]; - authorization_servers?: string[]; - bearer_methods_supported?: string[]; - dpop_bound_access_tokens_required?: boolean; - dpop_signing_alg_values_supported?: string[]; - jwks_uri?: string; - resource: string; - resource_documentation?: string; - resource_name?: string; - resource_policy_uri?: string; - resource_signing_alg_values_supported?: string[]; - resource_tos_uri?: string; - scopes_supported?: string[]; - signed_metadata?: string; - tls_client_certificate_bound_access_tokens?: boolean; -}; +type ProtectedResourceMetadata = z.infer; ``` -Schema für OAuth 2.0 Geschützte Ressourcen-Metadaten. - -## Typdeklaration {#type-declaration} - -### authorization\_details\_types\_supported? {#authorization-details-types-supported} - -```ts -optional authorization_details_types_supported: string[]; -``` - -Unterstützte Werte für den Typ der Autorisierungsdetails, wenn der Parameter authorization_details in der Anfrage verwendet wird. - -### authorization\_servers? {#authorization-servers} - -```ts -optional authorization_servers: string[]; -``` - -Liste der OAuth-Autorisierungsserver-Ausstellerkennungen, die mit dieser geschützten Ressource verwendet werden können. - -### bearer\_methods\_supported? {#bearer-methods-supported} - -```ts -optional bearer_methods_supported: string[]; -``` - -Unterstützte Methoden zum Senden von OAuth 2.0 Bearer Tokens. Werte: ["header", "body", "query"]. - -### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} - -```ts -optional dpop_bound_access_tokens_required: boolean; -``` - -Ob die geschützte Ressource immer DPoP-gebundene Zugangstokens (Zugangstoken) erfordert. - -### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} - -```ts -optional dpop_signing_alg_values_supported: string[]; -``` - -Unterstützte JWS-Algorithmen zur Validierung von DPoP-Proof JWTs. - -### jwks\_uri? {#jwks-uri} - -```ts -optional jwks_uri: string; -``` - -URL des JSON Web Key (JWK) Set-Dokuments der geschützten Ressource. Dieses Dokument enthält die öffentlichen Schlüssel, -die zur Überprüfung digitaler Signaturen von Antworten oder Daten verwendet werden können, die von dieser geschützten Ressource zurückgegeben werden. -Dies unterscheidet sich von der jwks_uri des Autorisierungsservers, die für die Token-Validierung verwendet wird. Wenn die geschützte -Ressource ihre Antworten signiert, können Clients diese öffentlichen Schlüssel abrufen, um die Authentizität und Integrität -der empfangenen Daten zu überprüfen. - -### resource {#resource} - -```ts -resource: string; -``` - -Der Ressourcenbezeichner der geschützten Ressource. - -### resource\_documentation? {#resource-documentation} - -```ts -optional resource_documentation: string; -``` - -URL mit Entwicklerdokumentation zur Nutzung der geschützten Ressource. - -### resource\_name? {#resource-name} - -```ts -optional resource_name: string; -``` - -Für Endbenutzer lesbarer Name der geschützten Ressource zur Anzeige. - -### resource\_policy\_uri? {#resource-policy-uri} - -```ts -optional resource_policy_uri: string; -``` - -URL mit Informationen zu den Anforderungen an die Datennutzung der geschützten Ressource. - -### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} - -```ts -optional resource_signing_alg_values_supported: string[]; -``` - -Von der geschützten Ressource unterstützte JWS-Signaturalgorithmen zum Signieren von Ressourcenantworten. - -### resource\_tos\_uri? {#resource-tos-uri} - -```ts -optional resource_tos_uri: string; -``` - -URL mit den Nutzungsbedingungen der geschützten Ressource. - -### scopes\_supported? {#scopes-supported} - -```ts -optional scopes_supported: string[]; -``` - -Liste der Berechtigungswerte (Scopes), die in Autorisierungsanfragen zum Zugriff auf diese geschützte Ressource verwendet werden. - -### signed\_metadata? {#signed-metadata} - -```ts -optional signed_metadata: string; -``` - -Ein signiertes JWT, das Metadatenparameter als Ansprüche (Claims) enthält. Das JWT muss mit JWS signiert sein und einen 'iss'-Anspruch enthalten. -Dieses Feld bietet eine Möglichkeit, die Authentizität der Metadaten selbst kryptografisch zu überprüfen. -Die Signatur kann mit den öffentlichen Schlüsseln überprüft werden, die am `jwks_uri`-Endpunkt verfügbar sind. -Wenn vorhanden, haben die Werte in diesen signierten Metadaten Vorrang vor den entsprechenden einfachen -JSON-Werten in diesem Metadatendokument. Dies hilft, Manipulationen an den Ressourcenmetadaten zu verhindern. - -### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} - -```ts -optional tls_client_certificate_bound_access_tokens: boolean; -``` - -Ob die geschützte Ressource Mutual-TLS-Clientzertifikat-gebundene Zugangstokens unterstützt. +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 new file mode 100644 index 0000000..64ed252 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md @@ -0,0 +1,53 @@ +--- +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 index 5d39631..65b1a7b 100644 --- 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 @@ -20,4 +20,4 @@ Konfiguration für den MCP-Server im Resource-Server-Modus. protectedResources: ResourceServerConfig | ResourceServerConfig[]; ``` -Eine einzelne Resource-Server-Konfiguration oder ein Array davon. \ No newline at end of file +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 index 2acfee6..67e1339 100644 --- 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 @@ -14,7 +14,7 @@ Diese Funktion sollte einen [MCPAuthBearerAuthError](/references/js/classes/MCPA 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 (protected resource) aufgeführten Autorisierungsserver (Authorization servers) +2. Die in den Metadaten der geschützten Ressource aufgeführten Autorisierungsserver (Authorization servers) ## Parameter {#parameters} @@ -28,4 +28,4 @@ nicht gültig ist. Der Aussteller sollte anhand folgender Kriterien validiert we ## Ausnahmen {#throws} -Wenn der Aussteller nicht erkannt oder ungültig ist. \ No newline at end of file +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 index 5e0f94e..95f8cbb 100644 --- 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 @@ -29,7 +29,7 @@ Objekt zurückzugeben. `string` -Der zu überprüfende Zugangstoken-String (Access token). +Der zu überprüfende Zugangstoken-String (Access token string). ## Rückgabewert {#returns} 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 index 67260d1..9244274 100644 --- 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 @@ -5,10 +5,34 @@ sidebar_label: authorizationServerMetadataSchema # Variable: authorizationServerMetadataSchema ```ts -const authorizationServerMetadataSchema: ZodObject; +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 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} 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 index 7a13a9c..671bfea 100644 --- 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 @@ -5,7 +5,31 @@ sidebar_label: camelCaseAuthorizationServerMetadataSchema # Variable: camelCaseAuthorizationServerMetadataSchema ```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject; +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. 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 index d2e552c..c032784 100644 --- 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 @@ -5,11 +5,27 @@ sidebar_label: camelCaseProtectedResourceMetadataSchema # Variable: camelCaseProtectedResourceMetadataSchema ```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject; +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. \ No newline at end of file +[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/protectedResourceMetadataSchema.md b/i18n/de/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md index c304d0e..2e248f8 100644 --- 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 @@ -5,7 +5,23 @@ sidebar_label: protectedResourceMetadataSchema # Variable: protectedResourceMetadataSchema ```ts -const protectedResourceMetadataSchema: ZodObject; +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 (Protected Resource Metadata). \ No newline at end of file +Zod-Schema für OAuth 2.0 Geschützte Ressourcen-Metadaten (OAuth 2.0 Protected Resource Metadata). 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 index 68cf318..aead9d7 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/references/js/README.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/README.md @@ -21,6 +21,7 @@ sidebar_label: Node.js SDK - [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) @@ -33,6 +34,7 @@ sidebar_label: Node.js SDK - [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) @@ -56,4 +58,5 @@ sidebar_label: Node.js SDK - [createVerifyJwt](/references/js/functions/createVerifyJwt.md) - [fetchServerConfig](/references/js/functions/fetchServerConfig.md) - [fetchServerConfigByWellKnownUrl](/references/js/functions/fetchServerConfigByWellKnownUrl.md) -- [handleBearerAuth](/references/js/functions/handleBearerAuth.md) \ No newline at end of file +- [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 index b114e05..4635993 100644 --- 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 @@ -4,9 +4,9 @@ sidebar_label: MCPAuth # Clase: MCPAuth -La clase principal de la librería mcp-auth. Actúa como una fábrica y registro para crear políticas de autenticación para tus recursos protegidos. +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 la autenticación basada en tokens. +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} @@ -14,17 +14,44 @@ Se inicializa con las configuraciones de tu servidor y proporciona un método `b 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, fetchServerConfig } from 'mcp-auth'; +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` puede ser un solo objeto de configuración o un arreglo de ellos. protectedResources: [ { metadata: { @@ -35,8 +62,12 @@ const mcpAuth = new MCPAuth({ }, ], }); +``` -// Monta el router para manejar Metadata de Recursos Protegidos +#### 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 @@ -60,17 +91,15 @@ Este enfoque se admite por compatibilidad con versiones anteriores. ```ts import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; +import { MCPAuth } from 'mcp-auth'; const app = express(); const mcpAuth = new MCPAuth({ - server: await fetchServerConfig( - 'https://auth.logto.io/oidc', - { type: 'oidc' } - ), + // Configuración de descubrimiento - los metadatos se obtienen bajo demanda + server: { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }, }); -// Monta el router para manejar Metadata heredada del Servidor de Autorización +// 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 @@ -79,7 +108,7 @@ app.get( mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), (req, res) => { console.log('Auth info:', req.auth); - // Maneja aquí la solicitud MCP + // Maneja la solicitud MCP aquí }, ); ``` @@ -93,7 +122,7 @@ new MCPAuth(config: MCPAuthConfig): MCPAuth; ``` Crea una instancia de MCPAuth. -Valida toda la configuración de antemano para fallar rápidamente en caso de errores. +Valida toda la configuración por adelantado para fallar rápido en caso de errores. #### Parámetros {#parameters} @@ -103,7 +132,7 @@ Valida toda la configuración de antemano para fallar rápidamente en caso de er La configuración de autenticación. -#### Devuelve {#returns} +#### Retorna {#returns} `MCPAuth` @@ -136,9 +165,7 @@ Crea un manejador Bearer auth (middleware de Express) que verifica el token de a [`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. +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** @@ -156,17 +183,16 @@ Configuración opcional para el manejador Bearer auth. [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) para las opciones de configuración disponibles (excluyendo `verifyAccessToken` y `issuer`). -##### Devuelve {#returns} +##### 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`). +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`). +[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} @@ -174,11 +200,11 @@ objeto `req.auth` (`AuthInfo`). 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. +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 JWKS URI del servidor de autorización. +del URI JWKS del servidor de autorización. ##### Parámetros {#parameters} @@ -196,8 +222,7 @@ El modo de verificación para el token de acceso. Actualmente, solo se admite 'j `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. +Configuración opcional para el manejador Bearer auth, incluyendo opciones de verificación JWT y opciones remotas de JWK set. **Ver** @@ -205,21 +230,20 @@ opciones remotas de JWK set. - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) para las opciones de configuración disponibles (excluyendo `verifyAccessToken` y `issuer`). -##### Devuelve {#returns} +##### 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`). +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`). +[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 JWKS URI no se proporciona en los metadatos del servidor al +si el URI JWKS no se proporciona en los metadatos del servidor al usar el modo `'jwt'`. *** @@ -230,14 +254,14 @@ usar el modo `'jwt'`. delegatedRouter(): Router; ``` -Crea un router delegado para servir el endpoint heredado de Metadata del Servidor de Autorización OAuth 2.0 +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. -#### Devuelve {#returns} +#### Retorna {#returns} `Router` -Un router que sirve el endpoint de Metadata del Servidor de Autorización OAuth 2.0 con los +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} @@ -251,7 +275,7 @@ import express from 'express'; import { MCPAuth } from 'mcp-auth'; const app = express(); -const mcpAuth: MCPAuth; // Supón que esto está inicializado +const mcpAuth: MCPAuth; // Se asume que está inicializado app.use(mcpAuth.delegatedRouter()); ``` @@ -267,17 +291,17 @@ Si se llama en modo `servidor de recursos`. protectedResourceMetadataRouter(): Router; ``` -Crea un router que sirve el endpoint de Metadata de Recursos Protegidos OAuth 2.0 +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. -#### Devuelve {#returns} +#### Retorna {#returns} `Router` -Un router que sirve el endpoint de Metadata de Recursos Protegidos OAuth 2.0. +Un router que sirve el endpoint de metadatos de recursos protegidos OAuth 2.0. #### Lanza {#throws} @@ -293,7 +317,7 @@ import { MCPAuth } from 'mcp-auth'; const mcpAuth: MCPAuth; const app = express(); -// Esto servirá metadata en `/.well-known/oauth-protected-resource/...` +// 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 index 25f261e..6042bc9 100644 --- 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 @@ -100,21 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -La propiedad `Error.stackTraceLimit` especifica el número de marcos de pila -recopilados por un seguimiento de pila (ya sea generado por `new Error().stack` o -`Error.captureStackTrace(obj)`). +Sobrescritura opcional para formatear los stack traces + +#### Parámetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Devuelve {#returns} + +`any` + +#### Ver {#see} -El valor predeterminado es `10`, pero se puede establecer en cualquier número válido de JavaScript. Los cambios -afectarán a cualquier seguimiento de pila capturado _después_ de que se haya cambiado el valor. +https://v8.dev/docs/stack-trace-api#customizing-stack-traces -Si se establece en un valor que no es un número, o en un número negativo, los seguimientos de pila -no capturarán ningún marco. +#### 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} @@ -155,49 +177,7 @@ Por defecto es `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Crea una propiedad `.stack` en `targetObject`, que al accederse devuelve -una cadena que representa la ubicación en el código en la que -se llamó a `Error.captureStackTrace()`. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Similar a `new Error().stack` -``` - -La primera línea del seguimiento estará precedida por -`${myObject.name}: ${myObject.message}`. - -El argumento opcional `constructorOpt` acepta una función. Si se proporciona, todos los marcos -por encima de `constructorOpt`, incluido `constructorOpt`, se omitirán del -seguimiento de pila generado. - -El argumento `constructorOpt` es útil para ocultar detalles de implementación -de la generación de errores al usuario. Por ejemplo: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Crear un error sin seguimiento de pila para evitar calcular el seguimiento dos veces. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Captura el seguimiento de pila por encima de la función b - Error.captureStackTrace(error, b); // Ni la función c ni b se incluyen en el seguimiento de pila - throw error; -} - -a(); -``` +Crea la propiedad .stack en un objeto objetivo #### Parámetros {#parameters} @@ -215,34 +195,4 @@ a(); #### Heredado de {#inherited-from} -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### 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) \ No newline at end of file +[`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 index aab8847..3bb856f 100644 --- 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 @@ -100,21 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -La propiedad `Error.stackTraceLimit` especifica el número de marcos de pila -recopilados por un seguimiento de pila (ya sea generado por `new Error().stack` o -`Error.captureStackTrace(obj)`). +Sobrescritura opcional para formatear los stack traces + +#### Parámetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Devuelve {#returns} + +`any` + +#### Ver {#see} -El valor predeterminado es `10`, pero se puede establecer en cualquier número válido de JavaScript. Los cambios -afectarán a cualquier seguimiento de pila capturado _después_ de que el valor haya sido cambiado. +https://v8.dev/docs/stack-trace-api#customizing-stack-traces -Si se establece en un valor que no es un número, o en un número negativo, los seguimientos de pila -no capturarán ningún marco. +#### 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} @@ -155,48 +177,7 @@ Por defecto es `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Crea una propiedad `.stack` en `targetObject`, que al accederse devuelve -una cadena que representa la ubicación en el código en la que -se llamó a `Error.captureStackTrace()`. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Similar a `new Error().stack` -``` - -La primera línea del seguimiento estará precedida por -`${myObject.name}: ${myObject.message}`. - -El argumento opcional `constructorOpt` acepta una función. Si se proporciona, todos los marcos -por encima de `constructorOpt`, incluido `constructorOpt`, se omitirán del seguimiento de pila generado. - -El argumento `constructorOpt` es útil para ocultar detalles de implementación -de la generación de errores al usuario. Por ejemplo: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Crear un error sin seguimiento de pila para evitar calcular el seguimiento dos veces. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Capturar el seguimiento de pila por encima de la función b - Error.captureStackTrace(error, b); // Ni la función c ni b se incluyen en el seguimiento de pila - throw error; -} - -a(); -``` +Crea la propiedad .stack en un objeto objetivo #### Parámetros {#parameters} @@ -214,34 +195,4 @@ a(); #### Heredado de {#inherited-from} -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### 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) \ No newline at end of file +[`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 index 4104aba..08177c8 100644 --- 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 @@ -104,21 +104,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -La propiedad `Error.stackTraceLimit` especifica el número de marcos de pila -recopilados por un seguimiento de pila (ya sea generado por `new Error().stack` o -`Error.captureStackTrace(obj)`). +Sobrescritura opcional para formatear los stack traces + +#### Parámetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Devuelve {#returns} + +`any` + +#### Ver {#see} -El valor predeterminado es `10`, pero se puede establecer en cualquier número válido de JavaScript. Los cambios -afectarán cualquier seguimiento de pila capturado _después_ de que el valor haya sido cambiado. +https://v8.dev/docs/stack-trace-api#customizing-stack-traces -Si se establece en un valor que no es un número, o en un número negativo, los seguimientos de pila -no capturarán ningún marco. +#### 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} @@ -159,48 +181,7 @@ Por defecto es `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Crea una propiedad `.stack` en `targetObject`, que al accederse devuelve -una cadena que representa la ubicación en el código en la que -se llamó a `Error.captureStackTrace()`. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Similar a `new Error().stack` -``` - -La primera línea del seguimiento estará precedida por -`${myObject.name}: ${myObject.message}`. - -El argumento opcional `constructorOpt` acepta una función. Si se proporciona, todos los marcos -por encima de `constructorOpt`, incluido `constructorOpt`, se omitirán del seguimiento de pila generado. - -El argumento `constructorOpt` es útil para ocultar detalles de implementación -de la generación del error al usuario. Por ejemplo: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Crear un error sin seguimiento de pila para evitar calcular el seguimiento dos veces. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Captura el seguimiento de pila por encima de la función b - Error.captureStackTrace(error, b); // Ni la función c ni b se incluyen en el seguimiento de pila - throw error; -} - -a(); -``` +Crea la propiedad .stack en un objeto objetivo #### Parámetros {#parameters} @@ -218,34 +199,4 @@ a(); #### Heredado de {#inherited-from} -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### 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) \ No newline at end of file +[`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 index 549ca11..4304c19 100644 --- 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 @@ -6,7 +6,7 @@ sidebar_label: 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. +Proporciona una forma estandarizada de manejar errores relacionados con la autenticación (Authentication) y autorización (Authorization) de MCP. ## Hereda de {#extends} @@ -119,21 +119,45 @@ Error.stack *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +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 ``` -La propiedad `Error.stackTraceLimit` especifica el número de marcos de pila -recopilados por un seguimiento de pila (ya sea generado por `new Error().stack` o -`Error.captureStackTrace(obj)`). +*** -El valor predeterminado es `10`, pero puede establecerse en cualquier número válido de JavaScript. Los cambios -afectarán a cualquier seguimiento de pila capturado _después_ de que se haya cambiado el valor. +### stackTraceLimit {#stacktracelimit} -Si se establece en un valor que no es un número, o en un número negativo, los seguimientos de pila -no capturarán ningún marco. +```ts +static stackTraceLimit: number; +``` #### Heredado de {#inherited-from} @@ -149,7 +173,7 @@ Error.stackTraceLimit toJson(showCause: boolean): Record; ``` -Convierte el error a un formato JSON amigable para respuestas HTTP. +Convierte el error a un formato JSON apto para respuestas HTTP. #### Parámetros {#parameters} @@ -172,49 +196,7 @@ Por defecto es `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Crea una propiedad `.stack` en `targetObject`, que al accederse devuelve -una cadena que representa la ubicación en el código en la que -se llamó a `Error.captureStackTrace()`. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Similar a `new Error().stack` -``` - -La primera línea del seguimiento estará precedida por -`${myObject.name}: ${myObject.message}`. - -El argumento opcional `constructorOpt` acepta una función. Si se proporciona, todos los marcos -por encima de `constructorOpt`, incluido `constructorOpt`, se omitirán del -seguimiento de pila generado. - -El argumento `constructorOpt` es útil para ocultar detalles de implementación -de la generación de errores al usuario. Por ejemplo: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Crear un error sin seguimiento de pila para evitar calcular el seguimiento dos veces. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Capturar el seguimiento de pila por encima de la función b - Error.captureStackTrace(error, b); // Ni la función c ni b se incluyen en el seguimiento de pila - throw error; -} - -a(); -``` +Crea la propiedad .stack en un objeto objetivo #### Parámetros {#parameters} @@ -235,35 +217,3 @@ a(); ```ts Error.captureStackTrace ``` - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### 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 -``` \ No newline at end of file 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 index ba500ee..db3ef51 100644 --- 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 @@ -100,21 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -La propiedad `Error.stackTraceLimit` especifica el número de marcos de pila -recopilados por un seguimiento de pila (ya sea generado por `new Error().stack` o -`Error.captureStackTrace(obj)`). +Sobrescritura opcional para formatear los stack traces + +#### Parámetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### Devuelve {#returns} + +`any` + +#### Ver {#see} -El valor predeterminado es `10`, pero se puede establecer en cualquier número válido de JavaScript. Los cambios -afectarán cualquier seguimiento de pila capturado _después_ de que se haya cambiado el valor. +https://v8.dev/docs/stack-trace-api#customizing-stack-traces -Si se establece en un valor que no es un número, o en un número negativo, los seguimientos de pila -no capturarán ningún marco. +#### 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} @@ -155,49 +177,7 @@ Por defecto es `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Crea una propiedad `.stack` en `targetObject`, que al accederse devuelve -una cadena que representa la ubicación en el código en la que -se llamó a `Error.captureStackTrace()`. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Similar a `new Error().stack` -``` - -La primera línea del seguimiento estará precedida por -`${myObject.name}: ${myObject.message}`. - -El argumento opcional `constructorOpt` acepta una función. Si se proporciona, todos los marcos -por encima de `constructorOpt`, incluido `constructorOpt`, se omitirán del -seguimiento de pila generado. - -El argumento `constructorOpt` es útil para ocultar detalles de implementación -de la generación de errores al usuario. Por ejemplo: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Crear un error sin seguimiento de pila para evitar calcular el seguimiento dos veces. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Captura el seguimiento de pila por encima de la función b - Error.captureStackTrace(error, b); // Ni la función c ni b se incluyen en el seguimiento de pila - throw error; -} - -a(); -``` +Crea la propiedad .stack en un objeto objetivo #### Parámetros {#parameters} @@ -215,34 +195,4 @@ a(); #### Heredado de {#inherited-from} -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### 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) \ No newline at end of file +[`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 index 717cdeb..6e455a2 100644 --- 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 @@ -8,7 +8,7 @@ sidebar_label: createVerifyJwt function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; ``` -Crea una función para verificar tokens de acceso JWT utilizando la función de recuperación de clave proporcionada y opciones. +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} @@ -32,12 +32,12 @@ Opciones opcionales de verificación de JWT. JWTVerifyOptions para la definición de tipo de las opciones. -## Devuelve {#returns} +## Retorna {#returns} [`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) -Una función que verifica tokens de acceso JWT (Access tokens) y devuelve 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. +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 devuelta. \ No newline at end of file +[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 index 5a3e174..51cc618 100644 --- 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 @@ -5,7 +5,7 @@ sidebar_label: fetchServerConfig # Función: fetchServerConfig() ```ts -function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; +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). @@ -28,9 +28,9 @@ El objeto de configuración que contiene el tipo de servidor y una función de t ## Devuelve {#returns} -`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> +`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -Una promesa que se resuelve con la configuración del servidor. +Una promesa que se resuelve con la configuración estática del servidor y los metadatos obtenidos. ## Ver también {#see} @@ -42,11 +42,11 @@ Una promesa que se resuelve con la configuración del servidor. ```ts import { fetchServerConfig } from 'mcp-auth'; -// Obteniendo la configuración del servidor OAuth +// 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' }); -// Obteniendo la configuración del servidor OpenID Connect +// 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' }); ``` 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 index 856985f..507ecd3 100644 --- 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 @@ -5,7 +5,7 @@ sidebar_label: fetchServerConfigByWellKnownUrl # Función: fetchServerConfigByWellKnownUrl() ```ts -function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; +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. @@ -16,7 +16,7 @@ Si los metadatos del servidor no se ajustan al esquema esperado, pero estás seg ### wellKnownUrl {#wellknownurl} -La URL well-known desde la que obtener la configuración del servidor. Puede ser una cadena de texto o un objeto URL. +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` @@ -24,13 +24,13 @@ La URL well-known desde la que obtener la configuración del servidor. Puede ser `ServerMetadataConfig` -El objeto de configuración que contiene el tipo de servidor y una función opcional de transformación. +El objeto de configuración que contiene el tipo de servidor y una función opcional de transpile. ## Devuelve {#returns} -`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> +`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -Una promesa que se resuelve con la configuración del servidor. +Una promesa que se resuelve con la configuración estática del servidor junto con los metadatos obtenidos. ## Lanza {#throws} @@ -38,4 +38,4 @@ 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 +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 new file mode 100644 index 0000000..eaf9c00 --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md @@ -0,0 +1,24 @@ +--- +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 index 3b21e6a..29d778a 100644 --- 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 @@ -13,7 +13,7 @@ Crea una función middleware para manejar la autenticación Bearer en una aplica 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 atributo `request.auth`; +- 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. 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 index 4ff9f1b..4b6c772 100644 --- 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 @@ -5,44 +5,13 @@ sidebar_label: AuthServerConfig # Alias de tipo: AuthServerConfig ```ts -type AuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; - type: AuthServerType; -}; +type AuthServerConfig = + | ResolvedAuthServerConfig + | AuthServerDiscoveryConfig; ``` Configuración para el servidor de autorización remoto integrado con el servidor MCP. -## 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 o descubrimiento de OpenID Connect); también pueden proporcionarse directamente en la configuración si el servidor no admite dichos endpoints. - -**Nota:** Los metadatos deben estar en formato camelCase según lo prefiere la librería mcp-auth. - -#### Ver {#see} - - - [Metadatos del servidor de autorización OAuth 2.0](https://datatracker.ietf.org/doc/html/rfc8414) - - [Descubrimiento de OpenID Connect](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 +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/AuthServerDiscoveryConfig.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md new file mode 100644 index 0000000..555732b --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md @@ -0,0 +1,58 @@ +--- +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/AuthorizationServerMetadata.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md index 868428f..d31d596 100644 --- 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 @@ -5,231 +5,10 @@ sidebar_label: AuthorizationServerMetadata # Alias de tipo: AuthorizationServerMetadata ```ts -type AuthorizationServerMetadata = { - authorization_endpoint: string; - code_challenge_methods_supported?: string[]; - grant_types_supported?: string[]; - introspection_endpoint?: string; - introspection_endpoint_auth_methods_supported?: string[]; - introspection_endpoint_auth_signing_alg_values_supported?: string[]; - issuer: string; - jwks_uri?: string; - op_policy_uri?: string; - op_tos_uri?: string; - registration_endpoint?: string; - response_modes_supported?: string[]; - response_types_supported: string[]; - revocation_endpoint?: string; - revocation_endpoint_auth_methods_supported?: string[]; - revocation_endpoint_auth_signing_alg_values_supported?: string[]; - scopes_supported?: string[]; - service_documentation?: string; - token_endpoint: string; - token_endpoint_auth_methods_supported?: string[]; - token_endpoint_auth_signing_alg_values_supported?: string[]; - ui_locales_supported?: string[]; - userinfo_endpoint?: string; -}; +type AuthorizationServerMetadata = z.infer; ``` -Esquema para los metadatos del servidor de autorización OAuth 2.0 según lo definido en RFC 8414. - -## Declaración de tipo {#type-declaration} - -### authorization\_endpoint {#authorization-endpoint} - -```ts -authorization_endpoint: string; -``` - -URL del endpoint de autorización del servidor de autorización [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. -Esto es OBLIGATORIO a menos que no se admitan tipos de concesión que utilicen el endpoint de autorización. - -#### Ver {#see} - -https://rfc-editor.org/rfc/rfc6749#section-3.1 - -### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} - -```ts -optional code_challenge_methods_supported: string[]; -``` - -Arreglo JSON que contiene una lista de métodos de desafío de código Proof Key for Code Exchange (PKCE) -[[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] admitidos por este servidor de autorización. - -### grant\_types\_supported? {#grant-types-supported} - -```ts -optional grant_types_supported: string[]; -``` - -Arreglo JSON que contiene una lista de los valores de tipo de concesión OAuth 2.0 que este servidor de autorización -admite. Los valores del arreglo son los mismos que se usan con el parámetro `grant_types` -definido por el "Protocolo de Registro Dinámico de Clientes OAuth 2.0" [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. -Si se omite, el valor predeterminado es `["authorization_code", "implicit"]`. - -### introspection\_endpoint? {#introspection-endpoint} - -```ts -optional introspection_endpoint: string; -``` - -URL del endpoint de introspección OAuth 2.0 del servidor de autorización -[[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]. - -### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} - -```ts -optional introspection_endpoint_auth_methods_supported: string[]; -``` - -### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} - -```ts -optional introspection_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### issuer {#issuer} - -```ts -issuer: string; -``` - -El identificador de emisor (Issuer) del servidor de autorización, que es una URL que utiliza el esquema `https` y -no tiene componentes de consulta ni fragmentos. - -### jwks\_uri? {#jwks-uri} - -```ts -optional jwks_uri: string; -``` - -URL del documento JWK Set del servidor de autorización [[JWK](https://www.rfc-editor.org/rfc/rfc8414.html#ref-JWK)]. -El documento referenciado contiene la(s) clave(s) de firma que el cliente utiliza para validar -firmas del servidor de autorización. Esta URL DEBE usar el esquema `https`. - -### op\_policy\_uri? {#op-policy-uri} - -```ts -optional op_policy_uri: string; -``` - -### op\_tos\_uri? {#op-tos-uri} - -```ts -optional op_tos_uri: string; -``` - -### registration\_endpoint? {#registration-endpoint} - -```ts -optional registration_endpoint: string; -``` - -URL del endpoint de registro dinámico de clientes OAuth 2.0 del servidor de autorización -[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. - -### response\_modes\_supported? {#response-modes-supported} - -```ts -optional response_modes_supported: string[]; -``` - -Arreglo JSON que contiene una lista de los valores `response_mode` de OAuth 2.0 que este -servidor de autorización admite, según lo especificado en "Prácticas de codificación de tipo de respuesta múltiple de OAuth 2.0" -[[OAuth.Responses](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Responses)]. - -Si se omite, el valor predeterminado es `["query", "fragment"]`. El valor de modo de respuesta `"form_post"` también está definido en "OAuth 2.0 Form Post Response Mode" -[[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)]. - -### response\_types\_supported {#response-types-supported} - -```ts -response_types_supported: string[]; -``` - -Arreglo JSON que contiene una lista de los valores `response_type` de OAuth 2.0 que este servidor de autorización -admite. Los valores del arreglo son los mismos que se usan con el parámetro `response_types` -definido por el "Protocolo de Registro Dinámico de Clientes OAuth 2.0" -[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. - -### revocation\_endpoint? {#revocation-endpoint} - -```ts -optional revocation_endpoint: string; -``` - -URL del endpoint de revocación OAuth 2.0 del servidor de autorización -[[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]. - -### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} - -```ts -optional revocation_endpoint_auth_methods_supported: string[]; -``` - -### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} - -```ts -optional revocation_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### scopes\_supported? {#scopes-supported} - -```ts -optional scopes_supported: string[]; -``` - -Arreglo JSON que contiene una lista de los valores `scope` de OAuth 2.0 que este servidor de autorización -admite. -[[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] - -### service\_documentation? {#service-documentation} - -```ts -optional service_documentation: string; -``` - -### token\_endpoint {#token-endpoint} - -```ts -token_endpoint: string; -``` - -URL del endpoint de token del servidor de autorización [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. -Esto es OBLIGATORIO a menos que solo se admita el tipo de concesión implícita. - -#### Ver {#see} - -https://rfc-editor.org/rfc/rfc6749#section-3.2 - -### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} - -```ts -optional token_endpoint_auth_methods_supported: string[]; -``` - -### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} - -```ts -optional token_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### ui\_locales\_supported? {#ui-locales-supported} - -```ts -optional ui_locales_supported: string[]; -``` - -### userinfo\_endpoint? {#userinfo-endpoint} - -```ts -optional userinfo_endpoint: string; -``` - -URL del [endpoint userinfo](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) de OpenID Connect. -Este endpoint se utiliza para recuperar información sobre el usuario autenticado. +Esquema para los metadatos del servidor de Autorización (Authorization) OAuth 2.0 según lo definido en la RFC 8414. ## Ver {#see} 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 index ad587e9..346a556 100644 --- 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 @@ -24,11 +24,9 @@ type BearerAuthConfig = { 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 comprobación de audiencia. +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. +**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} @@ -63,12 +61,9 @@ Si se proporciona una función, debe validar el emisor según las reglas en optional requiredScopes: string[]; ``` -Un arreglo de alcances (scopes) requeridos que el token de acceso debe tener. Si el token no contiene -todos estos alcances, se lanzará un error. +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 comprobará 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 comprobará el reclamo `scopes` -si está disponible. +**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. *** @@ -78,9 +73,7 @@ si está disponible. 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`. +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`. *** @@ -90,10 +83,9 @@ Es obligatorio cuando se utiliza el manejador con una configuración de `protect 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. +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 por defecto {#default} +#### Valor predeterminado {#default} ```ts false @@ -109,8 +101,7 @@ 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. +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} 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 index 78e386e..80c3228 100644 --- 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 @@ -5,174 +5,10 @@ sidebar_label: CamelCaseAuthorizationServerMetadata # Alias de tipo: CamelCaseAuthorizationServerMetadata ```ts -type CamelCaseAuthorizationServerMetadata = { - authorizationEndpoint: string; - codeChallengeMethodsSupported?: string[]; - grantTypesSupported?: string[]; - introspectionEndpoint?: string; - introspectionEndpointAuthMethodsSupported?: string[]; - introspectionEndpointAuthSigningAlgValuesSupported?: string[]; - issuer: string; - jwksUri?: string; - opPolicyUri?: string; - opTosUri?: string; - registrationEndpoint?: string; - responseModesSupported?: string[]; - responseTypesSupported: string[]; - revocationEndpoint?: string; - revocationEndpointAuthMethodsSupported?: string[]; - revocationEndpointAuthSigningAlgValuesSupported?: string[]; - scopesSupported?: string[]; - serviceDocumentation?: string; - tokenEndpoint: string; - tokenEndpointAuthMethodsSupported?: string[]; - tokenEndpointAuthSigningAlgValuesSupported?: string[]; - uiLocalesSupported?: string[]; - userinfoEndpoint?: string; -}; +type CamelCaseAuthorizationServerMetadata = z.infer; ``` -La versión en camelCase del tipo de metadatos del Servidor de Autorización (Authorization Server) de OAuth 2.0. - -## Declaración de tipo {#type-declaration} - -### authorizationEndpoint {#authorizationendpoint} - -```ts -authorizationEndpoint: string; -``` - -### codeChallengeMethodsSupported? {#codechallengemethodssupported} - -```ts -optional codeChallengeMethodsSupported: string[]; -``` - -### grantTypesSupported? {#granttypessupported} - -```ts -optional grantTypesSupported: string[]; -``` - -### introspectionEndpoint? {#introspectionendpoint} - -```ts -optional introspectionEndpoint: string; -``` - -### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} - -```ts -optional introspectionEndpointAuthMethodsSupported: string[]; -``` - -### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} - -```ts -optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### issuer {#issuer} - -```ts -issuer: string; -``` - -### jwksUri? {#jwksuri} - -```ts -optional jwksUri: string; -``` - -### opPolicyUri? {#oppolicyuri} - -```ts -optional opPolicyUri: string; -``` - -### opTosUri? {#optosuri} - -```ts -optional opTosUri: string; -``` - -### registrationEndpoint? {#registrationendpoint} - -```ts -optional registrationEndpoint: string; -``` - -### responseModesSupported? {#responsemodessupported} - -```ts -optional responseModesSupported: string[]; -``` - -### responseTypesSupported {#responsetypessupported} - -```ts -responseTypesSupported: string[]; -``` - -### revocationEndpoint? {#revocationendpoint} - -```ts -optional revocationEndpoint: string; -``` - -### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} - -```ts -optional revocationEndpointAuthMethodsSupported: string[]; -``` - -### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} - -```ts -optional revocationEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### scopesSupported? {#scopessupported} - -```ts -optional scopesSupported: string[]; -``` - -### serviceDocumentation? {#servicedocumentation} - -```ts -optional serviceDocumentation: string; -``` - -### tokenEndpoint {#tokenendpoint} - -```ts -tokenEndpoint: string; -``` - -### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} - -```ts -optional tokenEndpointAuthMethodsSupported: string[]; -``` - -### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} - -```ts -optional tokenEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### uiLocalesSupported? {#uilocalessupported} - -```ts -optional uiLocalesSupported: string[]; -``` - -### userinfoEndpoint? {#userinfoendpoint} - -```ts -optional userinfoEndpoint: string; -``` +La versión en camelCase del tipo de metadatos del servidor de autorización OAuth 2.0. ## Ver también {#see} 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 index 2007597..aa10df1 100644 --- 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 @@ -5,119 +5,11 @@ sidebar_label: CamelCaseProtectedResourceMetadata # Alias de tipo: CamelCaseProtectedResourceMetadata ```ts -type CamelCaseProtectedResourceMetadata = { - authorizationDetailsTypesSupported?: string[]; - authorizationServers?: string[]; - bearerMethodsSupported?: string[]; - dpopBoundAccessTokensRequired?: boolean; - dpopSigningAlgValuesSupported?: string[]; - jwksUri?: string; - resource: string; - resourceDocumentation?: string; - resourceName?: string; - resourcePolicyUri?: string; - resourceSigningAlgValuesSupported?: string[]; - resourceTosUri?: string; - scopesSupported?: string[]; - signedMetadata?: string; - tlsClientCertificateBoundAccessTokens?: boolean; -}; +type CamelCaseProtectedResourceMetadata = z.infer; ``` La versión en camelCase del tipo de metadatos de recurso protegido de OAuth 2.0. -## Declaración de tipo {#type-declaration} - -### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} - -```ts -optional authorizationDetailsTypesSupported: string[]; -``` - -### authorizationServers? {#authorizationservers} - -```ts -optional authorizationServers: string[]; -``` - -### bearerMethodsSupported? {#bearermethodssupported} - -```ts -optional bearerMethodsSupported: string[]; -``` - -### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} - -```ts -optional dpopBoundAccessTokensRequired: boolean; -``` - -### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} - -```ts -optional dpopSigningAlgValuesSupported: string[]; -``` - -### jwksUri? {#jwksuri} - -```ts -optional jwksUri: string; -``` - -### resource {#resource} - -```ts -resource: string; -``` - -### resourceDocumentation? {#resourcedocumentation} - -```ts -optional resourceDocumentation: string; -``` - -### resourceName? {#resourcename} - -```ts -optional resourceName: string; -``` - -### resourcePolicyUri? {#resourcepolicyuri} - -```ts -optional resourcePolicyUri: string; -``` - -### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} - -```ts -optional resourceSigningAlgValuesSupported: string[]; -``` - -### resourceTosUri? {#resourcetosuri} - -```ts -optional resourceTosUri: string; -``` - -### scopesSupported? {#scopessupported} - -```ts -optional scopesSupported: string[]; -``` - -### signedMetadata? {#signedmetadata} - -```ts -optional signedMetadata: string; -``` - -### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} - -```ts -optional tlsClientCertificateBoundAccessTokens: boolean; -``` - ## 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/ProtectedResourceMetadata.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md index f1c015e..6f1ddec 100644 --- 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 @@ -5,153 +5,7 @@ sidebar_label: ProtectedResourceMetadata # Alias de tipo: ProtectedResourceMetadata ```ts -type ProtectedResourceMetadata = { - authorization_details_types_supported?: string[]; - authorization_servers?: string[]; - bearer_methods_supported?: string[]; - dpop_bound_access_tokens_required?: boolean; - dpop_signing_alg_values_supported?: string[]; - jwks_uri?: string; - resource: string; - resource_documentation?: string; - resource_name?: string; - resource_policy_uri?: string; - resource_signing_alg_values_supported?: string[]; - resource_tos_uri?: string; - scopes_supported?: string[]; - signed_metadata?: string; - tls_client_certificate_bound_access_tokens?: boolean; -}; +type ProtectedResourceMetadata = z.infer; ``` -Esquema para los metadatos de recursos protegidos de OAuth 2.0. - -## Declaración de tipo {#type-declaration} - -### authorization\_details\_types\_supported? {#authorization-details-types-supported} - -```ts -optional authorization_details_types_supported: string[]; -``` - -Valores de tipo de detalles de autorización admitidos al usar el parámetro de solicitud authorization_details. - -### authorization\_servers? {#authorization-servers} - -```ts -optional authorization_servers: string[]; -``` - -Lista de identificadores de emisor del servidor de autorización OAuth que se pueden usar con este recurso protegido. - -### bearer\_methods\_supported? {#bearer-methods-supported} - -```ts -optional bearer_methods_supported: string[]; -``` - -Métodos admitidos para enviar tokens de portador OAuth 2.0. Valores: ["header", "body", "query"]. - -### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} - -```ts -optional dpop_bound_access_tokens_required: boolean; -``` - -Indica si el recurso protegido siempre requiere tokens de acceso vinculados a DPoP. - -### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} - -```ts -optional dpop_signing_alg_values_supported: string[]; -``` - -Algoritmos JWS admitidos para validar JWTs de prueba DPoP. - -### jwks\_uri? {#jwks-uri} - -```ts -optional jwks_uri: string; -``` - -URL del documento JSON Web Key (JWK) Set del recurso protegido. Este documento contiene las claves públicas -que se pueden usar para verificar firmas digitales de respuestas o datos devueltos por este recurso protegido. -Esto difiere del jwks_uri del servidor de autorización, que se utiliza para la validación de tokens. Cuando el recurso protegido -firma sus respuestas, los clientes pueden obtener estas claves públicas para verificar la autenticidad e integridad -de los datos recibidos. - -### resource {#resource} - -```ts -resource: string; -``` - -El identificador de recurso del recurso protegido. - -### resource\_documentation? {#resource-documentation} - -```ts -optional resource_documentation: string; -``` - -URL que contiene la documentación para desarrolladores sobre el uso del recurso protegido. - -### resource\_name? {#resource-name} - -```ts -optional resource_name: string; -``` - -Nombre legible por humanos del recurso protegido para mostrar a los usuarios finales. - -### resource\_policy\_uri? {#resource-policy-uri} - -```ts -optional resource_policy_uri: string; -``` - -URL que contiene información sobre los requisitos de uso de datos del recurso protegido. - -### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} - -```ts -optional resource_signing_alg_values_supported: string[]; -``` - -Algoritmos de firma JWS admitidos por el recurso protegido para firmar respuestas del recurso. - -### resource\_tos\_uri? {#resource-tos-uri} - -```ts -optional resource_tos_uri: string; -``` - -URL que contiene los términos de servicio del recurso protegido. - -### scopes\_supported? {#scopes-supported} - -```ts -optional scopes_supported: string[]; -``` - -Lista de valores de alcance (scope) utilizados en solicitudes de autorización para acceder a este recurso protegido. - -### signed\_metadata? {#signed-metadata} - -```ts -optional signed_metadata: string; -``` - -Un JWT firmado que contiene parámetros de metadatos como reclamos. El JWT debe estar firmado usando JWS e incluir -un reclamo 'iss'. Este campo proporciona una forma de verificar criptográficamente la autenticidad de los metadatos -en sí. La firma se puede verificar usando las claves públicas disponibles en el endpoint `jwks_uri`. -Cuando está presente, los valores en estos metadatos firmados tienen prioridad sobre los valores JSON -simples correspondientes en este documento de metadatos. Esto ayuda a prevenir la manipulación de los metadatos del recurso. - -### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} - -```ts -optional tls_client_certificate_bound_access_tokens: boolean; -``` - -Indica si el recurso protegido admite tokens de acceso vinculados a certificados de cliente mutual-TLS. \ No newline at end of file +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 new file mode 100644 index 0000000..4be631b --- /dev/null +++ b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md @@ -0,0 +1,52 @@ +--- +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/VerifyAccessTokenFunction.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/type-aliases/VerifyAccessTokenFunction.md index 7145862..cbd21bd 100644 --- 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 @@ -13,8 +13,8 @@ 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`. +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: @@ -35,5 +35,5 @@ La cadena del token de acceso (Access token) a verificar. `MaybePromise`\<`AuthInfo`\> -Una promesa que se resuelve en un objeto AuthInfo o un valor sincrónico si el +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/variables/authorizationServerMetadataSchema.md b/i18n/es/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md index 6eba06b..b6ebc17 100644 --- 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 @@ -5,10 +5,34 @@ sidebar_label: authorizationServerMetadataSchema # Variable: authorizationServerMetadataSchema ```ts -const authorizationServerMetadataSchema: ZodObject; +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. +Esquema Zod para los metadatos del Servidor de Autorización OAuth 2.0 según lo definido en RFC 8414. ## Ver {#see} 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 index 55f0dde..d6f27f7 100644 --- 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 @@ -5,7 +5,31 @@ sidebar_label: camelCaseAuthorizationServerMetadataSchema # Variable: camelCaseAuthorizationServerMetadataSchema ```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject; +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. 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 index c575595..09b6e9d 100644 --- 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 @@ -5,10 +5,26 @@ sidebar_label: camelCaseProtectedResourceMetadataSchema # Variable: camelCaseProtectedResourceMetadataSchema ```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject; +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 Recurso Protegido de OAuth 2.0. +La versión en camelCase del esquema Zod de metadatos de recursos protegidos de OAuth 2.0. ## Ver {#see} 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 index c2f97f4..2baee5f 100644 --- 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 @@ -5,7 +5,23 @@ sidebar_label: protectedResourceMetadataSchema # Variable: protectedResourceMetadataSchema ```ts -const protectedResourceMetadataSchema: ZodObject; +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/fr/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/README.md index 8db5041..c8ed099 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/references/js/README.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/README.md @@ -21,6 +21,7 @@ sidebar_label: SDK Node.js - [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) @@ -33,6 +34,7 @@ sidebar_label: SDK Node.js - [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) @@ -56,4 +58,5 @@ sidebar_label: SDK Node.js - [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 index f26dd3f..8e70140 100644 --- 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 @@ -4,27 +4,54 @@ 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. +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 vos configurations serveur et fournit une méthode `bearerAuth` pour générer un middleware Express pour l’authentification basée sur les jetons. +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. +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, fetchServerConfig } from 'mcp-auth'; +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` peut être un seul objet de configuration ou un tableau de ceux-ci. protectedResources: [ { metadata: { @@ -35,20 +62,24 @@ const mcpAuth = new MCPAuth({ }, ], }); +``` + +#### Utilisation du middleware {#using-the-middleware} -// Monter le routeur pour gérer les métadonnées des ressources protégées +```ts +// Montez le routeur pour gérer les métadonnées des ressources protégées app.use(mcpAuth.protectedResourceMetadataRouter()); -// Protéger un point de terminaison API pour la ressource configurée +// Protégez un endpoint API pour la ressource configurée app.get( '/notes', mcpAuth.bearerAuth('jwt', { - resource: resourceIdentifier, // Spécifiez à quelle ressource ce point de terminaison appartient - audience: resourceIdentifier, // Facultatif, valider la revendication 'aud' + resource: resourceIdentifier, // Spécifiez à quelle ressource appartient ce endpoint + audience: resourceIdentifier, // Optionnellement, validez la revendication 'aud' requiredScopes: ['read:notes'], }), (req, res) => { - console.log('Infos Auth :', req.auth); + console.log('Auth info:', req.auth); res.json({ notes: [] }); }, ); @@ -60,26 +91,24 @@ Cette approche est prise en charge pour la rétrocompatibilité. ```ts import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; +import { MCPAuth } from 'mcp-auth'; const app = express(); const mcpAuth = new MCPAuth({ - server: await fetchServerConfig( - 'https://auth.logto.io/oidc', - { type: 'oidc' } - ), + // Configuration par découverte - métadonnées récupérées à la demande + server: { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }, }); -// Monter le routeur pour gérer les métadonnées héritées du serveur d’autorisation +// Montez le routeur pour gérer les métadonnées héritées du serveur d'autorisation app.use(mcpAuth.delegatedRouter()); -// Protéger un point de terminaison en utilisant la politique par défaut +// Protégez un endpoint en utilisant la politique par défaut app.get( '/mcp', mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), (req, res) => { - console.log('Infos Auth :', req.auth); - // Traiter la requête MCP ici + console.log('Auth info:', req.auth); + // Gérez ici la requête MCP }, ); ``` @@ -93,7 +122,7 @@ 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. +Elle valide toute la configuration en amont pour échouer rapidement en cas d'erreur. #### Paramètres {#parameters} @@ -101,7 +130,7 @@ Elle valide toute la configuration en amont pour échouer rapidement en cas d’ [`MCPAuthConfig`](/references/js/type-aliases/MCPAuthConfig.md) -La configuration d’authentification. +La configuration d'authentification. #### Retourne {#returns} @@ -115,20 +144,19 @@ La configuration d’authentification. readonly config: MCPAuthConfig; ``` -La configuration d’authentification. +La configuration d'authentification. ## Méthodes {#methods} ### bearerAuth() {#bearerauth} -#### Signature d’appel {#call-signature} +#### 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 dans l’en-tête -`Authorization` de la requête. +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} @@ -136,48 +164,41 @@ Crée un gestionnaire d’authentification Bearer (middleware Express) qui véri [`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) -Une fonction qui vérifie le jeton d’accès. Elle doit accepter le -jeton d’accès sous forme de chaîne et retourner une promesse (ou une valeur) qui se résout avec le résultat de la vérification. +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`. +[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. +Configuration optionnelle pour le gestionnaire d'authentification Bearer. **Voir** -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) pour les options de configuration disponibles (à l’exception de -`verifyAccessToken` et `issuer`). +[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 et ajoute le -résultat de la vérification à l’objet requête (`req.auth`). +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`). +[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} +#### 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 dans l’en-tête -`Authorization` de la requête en utilisant un mode de vérification prédéfini. +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 -depuis l’URI JWKS du serveur d’autorisation. +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} @@ -185,7 +206,7 @@ depuis l’URI JWKS du serveur d’autorisation. `"jwt"` -Le mode de vérification pour le jeton d’accès. Actuellement, seul 'jwt' est pris en charge. +Le mode de vérification pour le jeton d’accès (Access token). Actuellement, seul 'jwt' est pris en charge. **Voir** @@ -195,32 +216,26 @@ Le mode de vérification pour le jeton d’accès. Actuellement, seul 'jwt' est `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. +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’exception de -`verifyAccessToken` et `issuer`). + - 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 et ajoute le -résultat de la vérification à l’objet requête (`req.auth`). +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`). +[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'`. +si l'URI JWKS n'est pas fourni dans les métadonnées du serveur lors de l'utilisation du mode `'jwt'`. *** @@ -230,15 +245,13 @@ l’utilisation du mode `'jwt'`. delegatedRouter(): Router; ``` -Crée un routeur délégué pour servir le point de terminaison hérité OAuth 2.0 Authorization Server Metadata -(`/.well-known/oauth-authorization-server`) avec les métadonnées fournies à l’instance. +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 le point de terminaison OAuth 2.0 Authorization Server Metadata avec les -métadonnées fournies à l’instance. +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} @@ -267,17 +280,15 @@ Si appelé en mode `resource server`. protectedResourceMetadataRouter(): Router; ``` -Crée un routeur qui sert le point de terminaison OAuth 2.0 Protected Resource Metadata -pour toutes les ressources configurées. +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 points de terminaison `.well-known` pour chaque -identifiant de ressource fourni dans votre configuration. +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 le point de terminaison OAuth 2.0 Protected Resource Metadata. +Un routeur qui sert l'endpoint OAuth 2.0 des métadonnées des ressources protégées. #### Lève {#throws} @@ -293,7 +304,7 @@ import { MCPAuth } from 'mcp-auth'; const mcpAuth: MCPAuth; const app = express(); -// Cela servira les métadonnées à `/.well-known/oauth-protected-resource/...` -// selon vos identifiants de ressources. +// 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 index 4709191..d8c5193 100644 --- 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 @@ -4,7 +4,7 @@ sidebar_label: MCPAuthAuthServerError # Classe : MCPAuthAuthServerError -Erreur levée lorsqu'il y a un problème avec le serveur d'autorisation distant. +Erreur levée lorsqu'il y a un problème avec le serveur d’autorisation distant. ## Hérite de {#extends} @@ -56,7 +56,7 @@ readonly optional cause: unknown; readonly code: AuthServerErrorCode; ``` -Le code d'erreur au format snake_case. +Le code d’erreur au format snake_case. #### Hérité de {#inherited-from} @@ -100,21 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace() ? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -La propriété `Error.stackTraceLimit` spécifie le nombre de frames de pile -collectés par une trace de pile (qu'elle soit générée par `new Error().stack` ou -`Error.captureStackTrace(obj)`). +Surcharge optionnelle pour le formatage des traces de pile + +#### Paramètres {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -La valeur par défaut est `10` mais peut être définie sur n'importe quel nombre JavaScript valide. Les modifications -affecteront toute trace de pile capturée _après_ que la valeur ait été modifiée. +`CallSite`[] -Si elle est définie sur une valeur non numérique, ou sur un nombre négatif, les traces de pile -ne captureront aucune frame. +#### 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} @@ -128,7 +150,7 @@ ne captureront aucune frame. toJson(showCause: boolean): Record; ``` -Convertit l'erreur en un format JSON adapté à une réponse HTTP. +Convertit l’erreur au format JSON adapté à une réponse HTTP. #### Paramètres {#parameters} @@ -136,8 +158,8 @@ Convertit l'erreur en un format JSON adapté à une réponse HTTP. `boolean` = `false` -Indique s'il faut inclure la cause de l'erreur dans la réponse JSON. -La valeur par défaut est `false`. +Indique s’il faut inclure la cause de l’erreur dans la réponse JSON. +Par défaut à `false`. #### Retourne {#returns} @@ -155,49 +177,7 @@ La valeur par défaut est `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Crée une propriété `.stack` sur `targetObject`, qui, lorsqu'elle est accédée, retourne -une chaîne représentant l'emplacement dans le code où -`Error.captureStackTrace()` a été appelé. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Similaire à `new Error().stack` -``` - -La première ligne de la trace sera préfixée par -`${myObject.name}: ${myObject.message}`. - -L'argument optionnel `constructorOpt` accepte une fonction. Si fourni, toutes les frames -au-dessus de `constructorOpt`, y compris `constructorOpt`, seront omises de la -trace de pile générée. - -L'argument `constructorOpt` est utile pour masquer les détails d'implémentation -de la génération d'erreur à l'utilisateur. Par exemple : - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Créer une erreur sans trace de pile pour éviter de calculer la trace deux fois. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Capturer la trace de pile au-dessus de la fonction b - Error.captureStackTrace(error, b); // Ni la fonction c, ni b ne sont incluses dans la trace de pile - throw error; -} - -a(); -``` +Crée la propriété .stack sur un objet cible #### Paramètres {#parameters} @@ -216,33 +196,3 @@ a(); #### Hérité de {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### 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) 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 index 730893e..004d87a 100644 --- 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 @@ -100,21 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace() ? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -La propriété `Error.stackTraceLimit` spécifie le nombre de frames de pile -collectés par une trace de pile (qu'elle soit générée par `new Error().stack` ou -`Error.captureStackTrace(obj)`). +Surcharge optionnelle pour formater les traces de pile + +#### Paramètres {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -La valeur par défaut est `10` mais peut être définie sur n'importe quel nombre JavaScript valide. Les modifications -affecteront toute trace de pile capturée _après_ que la valeur ait été modifiée. +`CallSite`[] -Si elle est définie sur une valeur non numérique, ou sur un nombre négatif, les traces de pile -ne captureront aucune frame. +#### 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} @@ -137,7 +159,7 @@ Convertit l'erreur en un format JSON adapté à une réponse HTTP. `boolean` = `false` Indique s'il faut inclure la cause de l'erreur dans la réponse JSON. -La valeur par défaut est `false`. +Par défaut à `false`. #### Retourne {#returns} @@ -155,49 +177,7 @@ La valeur par défaut est `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Crée une propriété `.stack` sur `targetObject`, qui, lorsqu'elle est accédée, retourne -une chaîne représentant l'emplacement dans le code où -`Error.captureStackTrace()` a été appelé. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Similaire à `new Error().stack` -``` - -La première ligne de la trace sera préfixée par -`${myObject.name}: ${myObject.message}`. - -L'argument optionnel `constructorOpt` accepte une fonction. Si fourni, toutes les frames -au-dessus de `constructorOpt`, y compris `constructorOpt`, seront omises de la -trace de pile générée. - -L'argument `constructorOpt` est utile pour masquer les détails d'implémentation -de la génération d'erreur à l'utilisateur. Par exemple : - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Créer une erreur sans trace de pile pour éviter de calculer la trace deux fois. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Capturer la trace de pile au-dessus de la fonction b - Error.captureStackTrace(error, b); // Ni la fonction c, ni b ne sont incluses dans la trace de pile - throw error; -} - -a(); -``` +Crée la propriété .stack sur un objet cible #### Paramètres {#parameters} @@ -216,33 +196,3 @@ a(); #### Hérité de {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### 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) 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 index a71d86e..53ce46b 100644 --- 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 @@ -30,7 +30,7 @@ Le code d'erreur au format snake_case. `string` -Une description lisible de l'erreur. +Une description lisible par l'humain de l'erreur. #### Retourne {#returns} @@ -104,21 +104,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace() ? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -La propriété `Error.stackTraceLimit` spécifie le nombre de frames de pile -collectés par une trace de pile (qu'elle soit générée par `new Error().stack` ou -`Error.captureStackTrace(obj)`). +Surcharge optionnelle pour formater les traces de pile + +#### Paramètres {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -La valeur par défaut est `10` mais peut être définie sur n'importe quel nombre JavaScript valide. Les modifications -affecteront toute trace de pile capturée _après_ que la valeur ait été modifiée. +`CallSite`[] -Si elle est définie sur une valeur non numérique, ou sur un nombre négatif, les traces de pile -ne captureront aucune frame. +#### 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} @@ -159,49 +181,7 @@ Par défaut à `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Crée une propriété `.stack` sur `targetObject`, qui, lorsqu'elle est accédée, retourne -une chaîne représentant l'emplacement dans le code où -`Error.captureStackTrace()` a été appelé. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Similaire à `new Error().stack` -``` - -La première ligne de la trace sera préfixée par -`${myObject.name}: ${myObject.message}`. - -L'argument optionnel `constructorOpt` accepte une fonction. Si fourni, toutes les frames -au-dessus de `constructorOpt`, y compris `constructorOpt`, seront omises de la -trace de pile générée. - -L'argument `constructorOpt` est utile pour masquer les détails d'implémentation -de la génération d'erreur à l'utilisateur. Par exemple : - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Créer une erreur sans trace de pile pour éviter de calculer la trace deux fois. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Capturer la trace de pile au-dessus de la fonction b - Error.captureStackTrace(error, b); // Ni la fonction c, ni b ne sont incluses dans la trace de pile - throw error; -} - -a(); -``` +Crée la propriété .stack sur un objet cible #### Paramètres {#parameters} @@ -220,33 +200,3 @@ a(); #### Hérité de {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### 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) 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 index 9886482..2ffb784 100644 --- 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 @@ -119,21 +119,45 @@ Error.stack *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace() ? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -La propriété `Error.stackTraceLimit` spécifie le nombre de frames de pile -collectés par une trace de pile (qu’elle soit générée par `new Error().stack` ou -`Error.captureStackTrace(obj)`). +Surcharge optionnelle pour le formatage des traces de pile + +#### Paramètres {#parameters} + +##### err {#err} -La valeur par défaut est `10` mais peut être définie sur n’importe quel nombre JavaScript valide. Les modifications -affecteront toute trace de pile capturée _après_ le changement de valeur. +`Error` -Si elle est définie sur une valeur non numérique, ou sur un nombre négatif, les traces de pile -ne captureront aucune frame. +##### 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} @@ -172,49 +196,7 @@ Par défaut à `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Crée une propriété `.stack` sur `targetObject`, qui, lorsqu’elle est accédée, retourne -une chaîne représentant l’emplacement dans le code où -`Error.captureStackTrace()` a été appelé. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Similaire à `new Error().stack` -``` - -La première ligne de la trace sera préfixée par -`${myObject.name}: ${myObject.message}`. - -L’argument optionnel `constructorOpt` accepte une fonction. Si fourni, toutes les frames -au-dessus de `constructorOpt`, y compris `constructorOpt`, seront omises de la -trace de pile générée. - -L’argument `constructorOpt` est utile pour masquer les détails d’implémentation -de la génération d’erreur à l’utilisateur. Par exemple : - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Créer une erreur sans trace de pile pour éviter de calculer la trace deux fois. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Capturer la trace de pile au-dessus de la fonction b - Error.captureStackTrace(error, b); // Ni la fonction c, ni b ne sont incluses dans la trace de pile - throw error; -} - -a(); -``` +Crée la propriété .stack sur un objet cible #### Paramètres {#parameters} @@ -235,35 +217,3 @@ a(); ```ts Error.captureStackTrace ``` - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### 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 -``` 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 index ecd5125..15c4842 100644 --- 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 @@ -100,21 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace() ? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -La propriété `Error.stackTraceLimit` spécifie le nombre de frames de pile -collectés par une trace de pile (qu'elle soit générée par `new Error().stack` ou -`Error.captureStackTrace(obj)`). +Surcharge optionnelle pour le formatage des traces de pile + +#### Paramètres {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -La valeur par défaut est `10` mais peut être définie sur n'importe quel nombre JavaScript valide. Les modifications -affecteront toute trace de pile capturée _après_ que la valeur ait été modifiée. +`CallSite`[] -Si elle est définie sur une valeur non numérique, ou sur un nombre négatif, les traces de pile -ne captureront aucune frame. +#### 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} @@ -155,49 +177,7 @@ La valeur par défaut est `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Crée une propriété `.stack` sur `targetObject`, qui, lorsqu'elle est accédée, retourne -une chaîne représentant l'emplacement dans le code où -`Error.captureStackTrace()` a été appelé. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Similaire à `new Error().stack` -``` - -La première ligne de la trace sera préfixée par -`${myObject.name}: ${myObject.message}`. - -L'argument optionnel `constructorOpt` accepte une fonction. Si fourni, toutes les frames -au-dessus de `constructorOpt`, y compris `constructorOpt`, seront omises de la -trace de pile générée. - -L'argument `constructorOpt` est utile pour masquer les détails d'implémentation -de la génération d'erreur à l'utilisateur. Par exemple : - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Créer une erreur sans trace de pile pour éviter de calculer la trace deux fois. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Capturer la trace de pile au-dessus de la fonction b - Error.captureStackTrace(error, b); // Ni la fonction c, ni b ne sont incluses dans la trace de pile - throw error; -} - -a(); -``` +Crée la propriété .stack sur un objet cible #### Paramètres {#parameters} @@ -216,33 +196,3 @@ a(); #### Hérité de {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### 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) 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 index c5afbf4..1b01722 100644 --- 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 @@ -26,7 +26,7 @@ JWTVerifyGetKey pour la définition du type de la fonction de récupération de `JWTVerifyOptions` -Options de vérification JWT facultatives. +Options facultatives de vérification du JWT. **Voir** 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 index 138e73c..9021caa 100644 --- 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 @@ -5,7 +5,7 @@ sidebar_label: fetchServerConfig # Fonction : fetchServerConfig() ```ts -function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; +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). @@ -28,11 +28,11 @@ L’objet de configuration contenant le type de serveur et une fonction de trans ## Retourne {#returns} -`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> +`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -Une promesse qui se résout avec la configuration du serveur. +Une promesse qui se résout avec la configuration statique du serveur et les métadonnées récupérées. -## Voir {#see} +## 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. @@ -57,4 +57,4 @@ 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. +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 index 248e10a..7d534c0 100644 --- 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 @@ -5,10 +5,10 @@ sidebar_label: fetchServerConfigByWellKnownUrl # Fonction : fetchServerConfigByWellKnownUrl() ```ts -function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; +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 par rapport à la spécification MCP. +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. @@ -28,9 +28,9 @@ L’objet de configuration contenant le type de serveur et éventuellement la fo ## Retourne {#returns} -`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> +`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -Une promesse qui se résout avec la configuration du serveur. +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} @@ -38,4 +38,4 @@ 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. \ No newline at end of file +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 new file mode 100644 index 0000000..53bdd92 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md @@ -0,0 +1,24 @@ +--- +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 index 436c754..3348934 100644 --- 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 @@ -11,13 +11,13 @@ 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’Émetteur (Issuer), l’Audience (Audience) et les Portées (Scopes) requises. +`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 (Access token) échoue, il répond avec une erreur 401 Non autorisé. -- Si le jeton ne possède pas les Portées (Scopes) requises, il répond avec une erreur 403 Interdit. -- Si des erreurs inattendues surviennent lors du processus d’authentification, le middleware les relancera. +- 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. 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 index e6dbd10..2aca815 100644 --- 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 @@ -5,46 +5,13 @@ sidebar_label: AuthServerConfig # Alias de type : AuthServerConfig ```ts -type AuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; - type: AuthServerType; -}; +type AuthServerConfig = + | ResolvedAuthServerConfig + | AuthServerDiscoveryConfig; ``` -Configuration pour le serveur d'autorisation distant intégré avec le serveur MCP. +Configuration pour le serveur d’autorisation distant intégré au serveur MCP. -## 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 les métadonnées du serveur d'autorisation OAuth 2.0). - -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. +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 index 7e48430..3fa77a1 100644 --- 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 @@ -12,7 +12,7 @@ type AuthServerConfigError = { }; ``` -Représente une erreur qui se produit lors de la validation des métadonnées du serveur d’autorisation (authorization server). +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} 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 index df2408e..6677393 100644 --- 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 @@ -11,7 +11,7 @@ type AuthServerConfigWarning = { }; ``` -Représente un avertissement qui survient lors de la validation des métadonnées du serveur d’autorisation. +Représente un avertissement qui se produit lors de la validation des métadonnées du serveur d’autorisation. ## Propriétés {#properties} 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 new file mode 100644 index 0000000..8a3820d --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md @@ -0,0 +1,57 @@ +--- +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/AuthServerModeConfig.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md index 91659c0..e58a42c 100644 --- 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 @@ -10,7 +10,7 @@ type AuthServerModeConfig = { }; ``` -Configuration pour le mode serveur d'autorisation hérité, MCP. +Configuration pour l'ancien serveur MCP en mode serveur d’autorisation (authorization server). ## Obsolète {#deprecated} @@ -24,7 +24,7 @@ Utilisez la configuration `ResourceServerModeConfig` à la place. server: AuthServerConfig; ``` -La configuration du serveur d'autorisation unique. +La configuration du serveur d’autorisation (authorization server) unique. #### Obsolète {#deprecated} 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 index 9073e68..46d2e16 100644 --- 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 @@ -5,234 +5,11 @@ sidebar_label: AuthorizationServerMetadata # Alias de type : AuthorizationServerMetadata ```ts -type AuthorizationServerMetadata = { - authorization_endpoint: string; - code_challenge_methods_supported?: string[]; - grant_types_supported?: string[]; - introspection_endpoint?: string; - introspection_endpoint_auth_methods_supported?: string[]; - introspection_endpoint_auth_signing_alg_values_supported?: string[]; - issuer: string; - jwks_uri?: string; - op_policy_uri?: string; - op_tos_uri?: string; - registration_endpoint?: string; - response_modes_supported?: string[]; - response_types_supported: string[]; - revocation_endpoint?: string; - revocation_endpoint_auth_methods_supported?: string[]; - revocation_endpoint_auth_signing_alg_values_supported?: string[]; - scopes_supported?: string[]; - service_documentation?: string; - token_endpoint: string; - token_endpoint_auth_methods_supported?: string[]; - token_endpoint_auth_signing_alg_values_supported?: string[]; - ui_locales_supported?: string[]; - userinfo_endpoint?: string; -}; +type AuthorizationServerMetadata = z.infer; ``` -Schéma pour les métadonnées du serveur d’autorisation OAuth 2.0 tel que défini dans la RFC 8414. +Schéma pour les métadonnées du serveur d’autorisation OAuth 2.0 telles que définies dans la RFC 8414. -## Déclaration du type {#type-declaration} - -### authorization\_endpoint {#authorization-endpoint} - -```ts -authorization_endpoint: string; -``` - -URL du point de terminaison d’autorisation du serveur d’autorisation [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. -Ceci est OBLIGATOIRE sauf si aucun type d’octroi n’est pris en charge utilisant le point de terminaison d’autorisation. - -#### Voir {#see} - -https://rfc-editor.org/rfc/rfc6749#section-3.1 - -### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} - -```ts -optional code_challenge_methods_supported: string[]; -``` - -Tableau JSON contenant une liste des méthodes de challenge de code Proof Key for Code Exchange (PKCE) -[[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] prises en charge par ce serveur d’autorisation. - -### grant\_types\_supported? {#grant-types-supported} - -```ts -optional grant_types_supported: string[]; -``` - -Tableau JSON contenant une liste des valeurs de type d’octroi OAuth 2.0 que ce serveur d’autorisation -prend en charge. Les valeurs du tableau utilisées sont les mêmes que celles utilisées avec le paramètre `grant_types` -défini par le "Protocole d’enregistrement dynamique du client OAuth 2.0" [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. -Si omis, la valeur par défaut est `["authorization_code", "implicit"]`. - -### introspection\_endpoint? {#introspection-endpoint} - -```ts -optional introspection_endpoint: string; -``` - -URL du point de terminaison d’introspection OAuth 2.0 du serveur d’autorisation -[[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]. - -### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} - -```ts -optional introspection_endpoint_auth_methods_supported: string[]; -``` - -### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} - -```ts -optional introspection_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### issuer {#issuer} - -```ts -issuer: string; -``` - -Identifiant de l’émetteur (Issuer) du serveur d’autorisation, qui est une URL utilisant le schéma `https` et -ne comportant pas de composants de requête ou de fragment. - -### jwks\_uri? {#jwks-uri} - -```ts -optional jwks_uri: string; -``` - -URL du document JWK Set [[JWK](https://www.rfc-editor.org/rfc/rfc8414.html#ref-JWK)] -du serveur d’autorisation. Le document référencé contient la/les clé(s) de signature que le client utilise pour valider -les signatures du serveur d’autorisation. Cette URL DOIT utiliser le schéma `https`. - -### op\_policy\_uri? {#op-policy-uri} - -```ts -optional op_policy_uri: string; -``` - -### op\_tos\_uri? {#op-tos-uri} - -```ts -optional op_tos_uri: string; -``` - -### registration\_endpoint? {#registration-endpoint} - -```ts -optional registration_endpoint: string; -``` - -URL du point de terminaison d’enregistrement dynamique du client OAuth 2.0 du serveur d’autorisation -[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. - -### response\_modes\_supported? {#response-modes-supported} - -```ts -optional response_modes_supported: string[]; -``` - -Tableau JSON contenant une liste des valeurs `response_mode` OAuth 2.0 que ce -serveur d’autorisation prend en charge, comme spécifié dans "OAuth 2.0 Multiple Response -Type Encoding Practices" -[[OAuth.Responses](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Responses)]. - -Si omis, la valeur par défaut est `["query", "fragment"]`. La valeur de mode de réponse `"form_post"` est -également définie dans "OAuth 2.0 Form Post Response Mode" -[[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)]. - -### response\_types\_supported {#response-types-supported} - -```ts -response_types_supported: string[]; -``` - -Tableau JSON contenant une liste des valeurs `response_type` OAuth 2.0 que ce serveur d’autorisation -prend en charge. Les valeurs du tableau utilisées sont les mêmes que celles utilisées avec le paramètre `response_types` -défini par le "Protocole d’enregistrement dynamique du client OAuth 2.0" -[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. - -### revocation\_endpoint? {#revocation-endpoint} - -```ts -optional revocation_endpoint: string; -``` - -URL du point de terminaison de révocation OAuth 2.0 du serveur d’autorisation -[[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]. - -### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} - -```ts -optional revocation_endpoint_auth_methods_supported: string[]; -``` - -### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} - -```ts -optional revocation_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### scopes\_supported? {#scopes-supported} - -```ts -optional scopes_supported: string[]; -``` - -Tableau JSON contenant une liste des valeurs `scope` OAuth 2.0 que ce serveur d’autorisation -prend en charge. -[[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] - -### service\_documentation? {#service-documentation} - -```ts -optional service_documentation: string; -``` - -### token\_endpoint {#token-endpoint} - -```ts -token_endpoint: string; -``` - -URL du point de terminaison de jeton du serveur d’autorisation [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. -Ceci est OBLIGATOIRE sauf si seul le type d’octroi implicite est pris en charge. - -#### Voir {#see} - -https://rfc-editor.org/rfc/rfc6749#section-3.2 - -### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} - -```ts -optional token_endpoint_auth_methods_supported: string[]; -``` - -### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} - -```ts -optional token_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### ui\_locales\_supported? {#ui-locales-supported} - -```ts -optional ui_locales_supported: string[]; -``` - -### userinfo\_endpoint? {#userinfo-endpoint} - -```ts -optional userinfo_endpoint: string; -``` - -URL du [point de terminaison userinfo](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) OpenID Connect. -Ce point de terminaison est utilisé pour récupérer les informations sur l’utilisateur authentifié. - -## Voir {#see} +## 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 index 67c16ca..d17bfdc 100644 --- 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 @@ -24,7 +24,7 @@ type BearerAuthConfig = { 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) pour lequel le jeton est destiné. Si non fourni, la vérification de l’audience sera ignorée. +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. @@ -63,7 +63,7 @@ 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. +**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. *** @@ -73,7 +73,7 @@ Un tableau des portées (Portées (Scopes)) requises que le jeton d’accès (Je optional resource: string; ``` -L’identifiant de la ressource protégée. Lorsqu’il est fourni, le gestionnaire utilisera les serveurs d’autorisation configurés pour cette ressource afin de valider le jeton reçu. +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`. *** @@ -84,7 +84,7 @@ Ce champ est requis lors de l’utilisation du gestionnaire avec une configurati optional showErrorDetails: boolean; ``` -Indique s’il faut afficher des informations d’erreur détaillées dans la réponse. Ceci est utile pour le débogage pendant le développement, mais doit être désactivé en production pour éviter de divulguer des informations sensibles. +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} 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 index 7f7bd49..e134ac3 100644 --- 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 @@ -5,174 +5,10 @@ sidebar_label: CamelCaseAuthorizationServerMetadata # Alias de type : CamelCaseAuthorizationServerMetadata ```ts -type CamelCaseAuthorizationServerMetadata = { - authorizationEndpoint: string; - codeChallengeMethodsSupported?: string[]; - grantTypesSupported?: string[]; - introspectionEndpoint?: string; - introspectionEndpointAuthMethodsSupported?: string[]; - introspectionEndpointAuthSigningAlgValuesSupported?: string[]; - issuer: string; - jwksUri?: string; - opPolicyUri?: string; - opTosUri?: string; - registrationEndpoint?: string; - responseModesSupported?: string[]; - responseTypesSupported: string[]; - revocationEndpoint?: string; - revocationEndpointAuthMethodsSupported?: string[]; - revocationEndpointAuthSigningAlgValuesSupported?: string[]; - scopesSupported?: string[]; - serviceDocumentation?: string; - tokenEndpoint: string; - tokenEndpointAuthMethodsSupported?: string[]; - tokenEndpointAuthSigningAlgValuesSupported?: string[]; - uiLocalesSupported?: string[]; - userinfoEndpoint?: string; -}; +type CamelCaseAuthorizationServerMetadata = z.infer; ``` -La version camelCase du type Metadata du serveur d’Autorisation (Authorization Server Metadata) OAuth 2.0. - -## Déclaration du type {#type-declaration} - -### authorizationEndpoint {#authorizationendpoint} - -```ts -authorizationEndpoint: string; -``` - -### codeChallengeMethodsSupported? {#codechallengemethodssupported} - -```ts -optional codeChallengeMethodsSupported: string[]; -``` - -### grantTypesSupported? {#granttypessupported} - -```ts -optional grantTypesSupported: string[]; -``` - -### introspectionEndpoint? {#introspectionendpoint} - -```ts -optional introspectionEndpoint: string; -``` - -### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} - -```ts -optional introspectionEndpointAuthMethodsSupported: string[]; -``` - -### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} - -```ts -optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### issuer {#issuer} - -```ts -issuer: string; -``` - -### jwksUri? {#jwksuri} - -```ts -optional jwksUri: string; -``` - -### opPolicyUri? {#oppolicyuri} - -```ts -optional opPolicyUri: string; -``` - -### opTosUri? {#optosuri} - -```ts -optional opTosUri: string; -``` - -### registrationEndpoint? {#registrationendpoint} - -```ts -optional registrationEndpoint: string; -``` - -### responseModesSupported? {#responsemodessupported} - -```ts -optional responseModesSupported: string[]; -``` - -### responseTypesSupported {#responsetypessupported} - -```ts -responseTypesSupported: string[]; -``` - -### revocationEndpoint? {#revocationendpoint} - -```ts -optional revocationEndpoint: string; -``` - -### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} - -```ts -optional revocationEndpointAuthMethodsSupported: string[]; -``` - -### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} - -```ts -optional revocationEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### scopesSupported? {#scopessupported} - -```ts -optional scopesSupported: string[]; -``` - -### serviceDocumentation? {#servicedocumentation} - -```ts -optional serviceDocumentation: string; -``` - -### tokenEndpoint {#tokenendpoint} - -```ts -tokenEndpoint: string; -``` - -### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} - -```ts -optional tokenEndpointAuthMethodsSupported: string[]; -``` - -### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} - -```ts -optional tokenEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### uiLocalesSupported? {#uilocalessupported} - -```ts -optional uiLocalesSupported: string[]; -``` - -### userinfoEndpoint? {#userinfoendpoint} - -```ts -optional userinfoEndpoint: string; -``` +La version camelCase du type de métadonnées du serveur d’autorisation OAuth 2.0. ## Voir aussi {#see} 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 index 7c15ece..7474b83 100644 --- 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 @@ -5,118 +5,10 @@ sidebar_label: CamelCaseProtectedResourceMetadata # Alias de type : CamelCaseProtectedResourceMetadata ```ts -type CamelCaseProtectedResourceMetadata = { - authorizationDetailsTypesSupported?: string[]; - authorizationServers?: string[]; - bearerMethodsSupported?: string[]; - dpopBoundAccessTokensRequired?: boolean; - dpopSigningAlgValuesSupported?: string[]; - jwksUri?: string; - resource: string; - resourceDocumentation?: string; - resourceName?: string; - resourcePolicyUri?: string; - resourceSigningAlgValuesSupported?: string[]; - resourceTosUri?: string; - scopesSupported?: string[]; - signedMetadata?: string; - tlsClientCertificateBoundAccessTokens?: boolean; -}; +type CamelCaseProtectedResourceMetadata = z.infer; ``` -La version camelCase du type OAuth 2.0 Protected Resource Metadata. - -## Déclaration du type {#type-declaration} - -### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} - -```ts -optional authorizationDetailsTypesSupported: string[]; -``` - -### authorizationServers? {#authorizationservers} - -```ts -optional authorizationServers: string[]; -``` - -### bearerMethodsSupported? {#bearermethodssupported} - -```ts -optional bearerMethodsSupported: string[]; -``` - -### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} - -```ts -optional dpopBoundAccessTokensRequired: boolean; -``` - -### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} - -```ts -optional dpopSigningAlgValuesSupported: string[]; -``` - -### jwksUri? {#jwksuri} - -```ts -optional jwksUri: string; -``` - -### resource {#resource} - -```ts -resource: string; -``` - -### resourceDocumentation? {#resourcedocumentation} - -```ts -optional resourceDocumentation: string; -``` - -### resourceName? {#resourcename} - -```ts -optional resourceName: string; -``` - -### resourcePolicyUri? {#resourcepolicyuri} - -```ts -optional resourcePolicyUri: string; -``` - -### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} - -```ts -optional resourceSigningAlgValuesSupported: string[]; -``` - -### resourceTosUri? {#resourcetosuri} - -```ts -optional resourceTosUri: string; -``` - -### scopesSupported? {#scopessupported} - -```ts -optional scopesSupported: string[]; -``` - -### signedMetadata? {#signedmetadata} - -```ts -optional signedMetadata: string; -``` - -### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} - -```ts -optional tlsClientCertificateBoundAccessTokens: boolean; -``` +La version camelCase du type de métadonnées de ressource protégée OAuth 2.0. ## Voir aussi {#see} 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 index cf5bc88..f3879cb 100644 --- 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 @@ -5,153 +5,7 @@ sidebar_label: ProtectedResourceMetadata # Alias de type : ProtectedResourceMetadata ```ts -type ProtectedResourceMetadata = { - authorization_details_types_supported?: string[]; - authorization_servers?: string[]; - bearer_methods_supported?: string[]; - dpop_bound_access_tokens_required?: boolean; - dpop_signing_alg_values_supported?: string[]; - jwks_uri?: string; - resource: string; - resource_documentation?: string; - resource_name?: string; - resource_policy_uri?: string; - resource_signing_alg_values_supported?: string[]; - resource_tos_uri?: string; - scopes_supported?: string[]; - signed_metadata?: string; - tls_client_certificate_bound_access_tokens?: boolean; -}; +type ProtectedResourceMetadata = z.infer; ``` -Schéma pour les métadonnées de ressource protégée OAuth 2.0. - -## Déclaration du type {#type-declaration} - -### authorization\_details\_types\_supported? {#authorization-details-types-supported} - -```ts -optional authorization_details_types_supported: string[]; -``` - -Types de détails d'autorisation pris en charge lors de l'utilisation du paramètre de requête authorization_details. - -### authorization\_servers? {#authorization-servers} - -```ts -optional authorization_servers: string[]; -``` - -Liste des identifiants d'émetteur du serveur d'autorisation OAuth pouvant être utilisés avec cette ressource protégée. - -### bearer\_methods\_supported? {#bearer-methods-supported} - -```ts -optional bearer_methods_supported: string[]; -``` - -Méthodes prises en charge pour l'envoi de jetons porteurs OAuth 2.0. Valeurs : ["header", "body", "query"]. - -### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} - -```ts -optional dpop_bound_access_tokens_required: boolean; -``` - -Indique si la ressource protégée exige toujours des jetons d’accès liés à DPoP. - -### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} - -```ts -optional dpop_signing_alg_values_supported: string[]; -``` - -Algorithmes JWS pris en charge pour la validation des preuves JWT DPoP. - -### jwks\_uri? {#jwks-uri} - -```ts -optional jwks_uri: string; -``` - -URL du document JSON Web Key (JWK) Set de la ressource protégée. Ce document contient les clés publiques -qui peuvent être utilisées pour vérifier les signatures numériques des réponses ou des données renvoyées par cette ressource protégée. -Ceci diffère du jwks_uri du serveur d'autorisation qui est utilisé pour la validation des jetons. Lorsque la ressource protégée -signe ses réponses, les clients peuvent récupérer ces clés publiques pour vérifier l'authenticité et l'intégrité -des données reçues. - -### resource {#resource} - -```ts -resource: string; -``` - -Identifiant de la ressource protégée. - -### resource\_documentation? {#resource-documentation} - -```ts -optional resource_documentation: string; -``` - -URL contenant la documentation développeur pour l'utilisation de la ressource protégée. - -### resource\_name? {#resource-name} - -```ts -optional resource_name: string; -``` - -Nom lisible par l'utilisateur de la ressource protégée pour l'affichage aux utilisateurs finaux. - -### resource\_policy\_uri? {#resource-policy-uri} - -```ts -optional resource_policy_uri: string; -``` - -URL contenant des informations sur les exigences d'utilisation des données de la ressource protégée. - -### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} - -```ts -optional resource_signing_alg_values_supported: string[]; -``` - -Algorithmes de signature JWS pris en charge par la ressource protégée pour la signature des réponses de ressource. - -### resource\_tos\_uri? {#resource-tos-uri} - -```ts -optional resource_tos_uri: string; -``` - -URL contenant les conditions d'utilisation de la ressource protégée. - -### scopes\_supported? {#scopes-supported} - -```ts -optional scopes_supported: string[]; -``` - -Liste des valeurs de portée utilisées dans les requêtes d'autorisation pour accéder à cette ressource protégée. - -### signed\_metadata? {#signed-metadata} - -```ts -optional signed_metadata: string; -``` - -Un JWT signé contenant les paramètres de métadonnées en tant que revendications (claims). Le JWT doit être signé à l'aide de JWS et inclure -une revendication 'iss'. Ce champ fournit un moyen de vérifier cryptographiquement l'authenticité des métadonnées -elles-mêmes. La signature peut être vérifiée à l'aide des clés publiques disponibles à l'endpoint `jwks_uri`. -Lorsqu'il est présent, les valeurs de ces métadonnées signées prévalent sur les valeurs JSON simples -correspondantes dans ce document de métadonnées. Cela aide à prévenir la falsification des métadonnées de la ressource. - -### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} - -```ts -optional tls_client_certificate_bound_access_tokens: boolean; -``` - -Indique si la ressource protégée prend en charge les jetons d’accès liés à un certificat client mutual-TLS. +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 new file mode 100644 index 0000000..dc37e49 --- /dev/null +++ b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md @@ -0,0 +1,53 @@ +--- +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/ValidateIssuerFunction.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md index 7e80675..f914b90 100644 --- 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 @@ -10,10 +10,9 @@ 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 à : +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 MCP-Auth +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} @@ -26,6 +25,6 @@ n’est pas valide. L’émetteur doit être validé par rapport à : `void` -## Lève une exception {#throws} +## 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/variables/authorizationServerMetadataSchema.md b/i18n/fr/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md index 5d2c0e8..807e091 100644 --- 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 @@ -5,7 +5,31 @@ sidebar_label: authorizationServerMetadataSchema # Variable : authorizationServerMetadataSchema ```ts -const authorizationServerMetadataSchema: ZodObject; +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. 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 index 12b6f3f..7646f52 100644 --- 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 @@ -5,7 +5,31 @@ sidebar_label: camelCaseAuthorizationServerMetadataSchema # Variable : camelCaseAuthorizationServerMetadataSchema ```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject; +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. 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 index 35740e9..532f586 100644 --- 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 @@ -5,10 +5,26 @@ sidebar_label: camelCaseProtectedResourceMetadataSchema # Variable : camelCaseProtectedResourceMetadataSchema ```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject; +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 des métadonnées de ressource protégée OAuth 2.0. +La version camelCase du schéma Zod OAuth 2.0 Protected Resource Metadata. ## Voir aussi {#see} 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 index afdc590..9e70d72 100644 --- 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 @@ -5,7 +5,23 @@ sidebar_label: protectedResourceMetadataSchema # Variable : protectedResourceMetadataSchema ```ts -const protectedResourceMetadataSchema: ZodObject; +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/ja/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/README.md index 2051515..faca9e5 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/references/js/README.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/README.md @@ -21,6 +21,7 @@ sidebar_label: Node.js SDK - [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) @@ -33,6 +34,7 @@ sidebar_label: Node.js SDK - [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) @@ -56,4 +58,5 @@ sidebar_label: Node.js SDK - [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 index 91b2eb4..a2d24bf 100644 --- 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 @@ -6,7 +6,7 @@ sidebar_label: MCPAuth mcp-auth ライブラリのメインクラスです。保護されたリソースのための認証 (Authentication) ポリシーを作成するためのファクトリーおよびレジストリとして機能します。 -サーバー構成で初期化され、トークンベースの認証 (Authentication) 用の Express ミドルウェアを生成する `bearerAuth` メソッドを提供します。 +サーバー構成で初期化され、トークンベースの認証 (Authentication) 用 Express ミドルウェアを生成する `bearerAuth` メソッドを提供します。 ## 例 {#example} @@ -14,17 +14,44 @@ mcp-auth ライブラリのメインクラスです。保護されたリソー 新しいアプリケーションにはこの方法が推奨されます。 +#### オプション 1: Discovery 設定(エッジランタイム推奨) {#option-1-discovery-config-recommended-for-edge-runtimes} + +メタデータをオンデマンドで取得したい場合に使用します。特に Cloudflare Workers のようなエッジランタイムでトップレベルの async fetch が許可されていない場合に便利です。 + ```ts import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; +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` は単一の構成オブジェクトまたはその配列を指定できます。 protectedResources: [ { metadata: { @@ -35,16 +62,20 @@ const mcpAuth = new MCPAuth({ }, ], }); +``` + +#### ミドルウェアの利用 {#using-the-middleware} -// 保護されたリソースメタデータを処理するルーターをマウント +```ts +// Protected Resource Metadata を処理するルーターをマウント app.use(mcpAuth.protectedResourceMetadataRouter()); -// 設定したリソース用の API エンドポイントを保護 +// 設定済みリソースの API エンドポイントを保護 app.get( '/notes', mcpAuth.bearerAuth('jwt', { resource: resourceIdentifier, // このエンドポイントが属するリソースを指定 - audience: resourceIdentifier, // 任意で 'aud' クレームを検証 + audience: resourceIdentifier, // 必要に応じて 'aud' クレームを検証 requiredScopes: ['read:notes'], }), (req, res) => { @@ -54,23 +85,21 @@ app.get( ); ``` -### `authorization server` モードでのレガシー利用例(非推奨) {#legacy-usage-in-authorization-server-mode-deprecated} +### レガシーな `authorization server` モードでの利用(非推奨) {#legacy-usage-in-authorization-server-mode-deprecated} 後方互換性のためにサポートされています。 ```ts import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; +import { MCPAuth } from 'mcp-auth'; const app = express(); const mcpAuth = new MCPAuth({ - server: await fetchServerConfig( - 'https://auth.logto.io/oidc', - { type: 'oidc' } - ), + // Discovery 設定 - メタデータはオンデマンド取得 + server: { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }, }); -// レガシー認可サーバーメタデータを処理するルーターをマウント +// レガシーな Authorization Server Metadata を処理するルーターをマウント app.use(mcpAuth.delegatedRouter()); // デフォルトポリシーでエンドポイントを保護 @@ -93,7 +122,7 @@ new MCPAuth(config: MCPAuthConfig): MCPAuth; ``` MCPAuth のインスタンスを作成します。 -エラー時にすぐ失敗するよう、全体の構成を事前に検証します。 +エラー時にすぐ失敗できるよう、構成全体を事前に検証します。 #### パラメーター {#parameters} @@ -135,31 +164,31 @@ bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit -Bearer 認証 (Authentication) ハンドラーのためのオプション構成。 +Bearer 認証 (Authentication) ハンドラーのためのオプション設定。 **参照** -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) で利用可能な構成オプション(`verifyAccessToken` と `issuer` を除く)を確認できます。 +[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) — 利用可能な設定オプション(`verifyAccessToken` と `issuer` を除く)。 ##### 戻り値 {#returns} `RequestHandler` -アクセス トークン (Access token) を検証し、検証結果をリクエストオブジェクト(`req.auth`)に追加する Express ミドルウェア関数。 +アクセス トークン (Access token) を検証し、その検証結果をリクエストオブジェクト(`req.auth`)に追加する Express ミドルウェア関数。 ##### 参照 {#see} -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) で実装詳細および `req.auth`(`AuthInfo`)オブジェクトの拡張型を確認できます。 +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) — 実装詳細および `req.auth`(`AuthInfo`)オブジェクトの拡張型。 #### 呼び出しシグネチャ {#call-signature} @@ -167,7 +196,7 @@ Bearer 認証 (Authentication) ハンドラーのためのオプション構成 bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; ``` -事前定義された検証モードを使用して、リクエストの `Authorization` ヘッダー内の アクセス トークン (Access token) を検証する Bearer 認証 (Authentication) ハンドラー(Express ミドルウェア)を作成します。 +リクエストの `Authorization` ヘッダー内の アクセス トークン (Access token) を、事前定義された検証モードで検証する Bearer 認証 (Authentication) ハンドラー(Express ミドルウェア)を作成します。 `'jwt'` モードでは、認可サーバーの JWKS URI から JWK Set を使って JWT 検証関数を作成します。 @@ -177,36 +206,36 @@ bearerAuth(mode: "jwt", config?: Omit & `VerifyJwtConfig` -JWT 検証オプションやリモート JWK Set オプションを含む、Bearer 認証 (Authentication) ハンドラーのためのオプション構成。 +JWT 検証オプションやリモート JWK set オプションを含む、Bearer 認証 (Authentication) ハンドラーのためのオプション設定。 **参照** - - VerifyJwtConfig で JWT 検証のための構成オプションを確認できます。 - - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) で利用可能な構成オプション(`verifyAccessToken` と `issuer` を除く)を確認できます。 + - VerifyJwtConfig — JWT 検証のための利用可能な設定オプション。 + - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) — 利用可能な設定オプション(`verifyAccessToken` と `issuer` を除く)。 ##### 戻り値 {#returns} `RequestHandler` -アクセス トークン (Access token) を検証し、検証結果をリクエストオブジェクト(`req.auth`)に追加する Express ミドルウェア関数。 +アクセス トークン (Access token) を検証し、その検証結果をリクエストオブジェクト(`req.auth`)に追加する Express ミドルウェア関数。 ##### 参照 {#see} -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) で実装詳細および `req.auth`(`AuthInfo`)オブジェクトの拡張型を確認できます。 +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) — 実装詳細および `req.auth`(`AuthInfo`)オブジェクトの拡張型。 ##### 例外 {#throws} -`'jwt'` モード使用時にサーバーメタデータに JWKS URI が指定されていない場合にスローされます。 +`'jwt'` モード利用時にサーバーメタデータに JWKS URI が指定されていない場合。 *** @@ -216,8 +245,8 @@ JWT 検証オプションやリモート JWK Set オプションを含む、Bear delegatedRouter(): Router; ``` -インスタンスに提供されたメタデータで、レガシー OAuth 2.0 認可サーバーメタデータエンドポイント -(`/.well-known/oauth-authorization-server`)を提供するための委譲ルーターを作成します。 +レガシー OAuth 2.0 認可サーバーメタデータエンドポイント +(`/.well-known/oauth-authorization-server`)をインスタンスに提供されたメタデータで提供するためのデリゲートルーターを作成します。 #### 戻り値 {#returns} @@ -242,7 +271,7 @@ app.use(mcpAuth.delegatedRouter()); #### 例外 {#throws} -`resource server` モードで呼び出された場合にスローされます。 +`resource server` モードで呼び出された場合。 *** @@ -252,19 +281,19 @@ app.use(mcpAuth.delegatedRouter()); protectedResourceMetadataRouter(): Router; ``` -設定されたすべてのリソースに対して OAuth 2.0 保護リソースメタデータエンドポイントを提供するルーターを作成します。 +設定されたすべてのリソースに対して OAuth 2.0 Protected Resource Metadata エンドポイントを提供するルーターを作成します。 -このルーターは、構成で指定された各リソース識別子に対して正しい `.well-known` エンドポイントを自動的に作成します。 +このルーターは、構成で指定した各リソース識別子に基づいて、正しい `.well-known` エンドポイントを自動的に作成します。 #### 戻り値 {#returns} `Router` -OAuth 2.0 保護リソースメタデータエンドポイントを提供するルーター。 +OAuth 2.0 Protected Resource Metadata エンドポイントを提供するルーター。 #### 例外 {#throws} -`authorization server` モードで呼び出された場合にスローされます。 +`authorization server` モードで呼び出された場合。 #### 例 {#example} @@ -272,7 +301,7 @@ OAuth 2.0 保護リソースメタデータエンドポイントを提供する import express from 'express'; import { MCPAuth } from 'mcp-auth'; -// mcpAuth が 1 つ以上の `protectedResources` 構成で初期化されていると仮定 +// mcpAuth が 1 つ以上の `protectedResources` 設定で初期化されていると仮定 const mcpAuth: MCPAuth; const app = express(); 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 index bef1792..015eb65 100644 --- 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 @@ -4,7 +4,7 @@ sidebar_label: MCPAuthAuthServerError # クラス: MCPAuthAuthServerError -リモート認可 (Authorization) サーバーに問題が発生した場合にスローされるエラーです。 +リモート認可 (Authorization) サーバーで問題が発生した場合にスローされるエラーです。 ## 継承 {#extends} @@ -100,17 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` プロパティは、スタックトレース(`new Error().stack` または `Error.captureStackTrace(obj)` で生成される)によって収集されるスタックフレームの数を指定します。 +スタックトレースのフォーマットをカスタマイズするためのオプションのオーバーライド + +#### パラメーター {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -デフォルト値は `10` ですが、有効な JavaScript の数値であれば任意に設定できます。値を変更した後にキャプチャされたすべてのスタックトレースに影響します。 +`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} @@ -132,7 +158,8 @@ toJson(showCause: boolean): Record; `boolean` = `false` -エラーの原因を JSON レスポンスに含めるかどうか。デフォルトは `false` です。 +JSON レスポンスにエラーの原因を含めるかどうかを指定します。 +デフォルトは `false` です。 #### 戻り値 {#returns} @@ -150,44 +177,7 @@ toJson(showCause: boolean): Record; static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -`targetObject` に `.stack` プロパティを作成し、アクセス時に -`Error.captureStackTrace()` が呼び出されたコード位置を表す文字列を返します。 - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // `new Error().stack` と同様 -``` - -トレースの最初の行は `${myObject.name}: ${myObject.message}` で始まります。 - -オプションの `constructorOpt` 引数には関数を指定できます。指定した場合、`constructorOpt` より上のすべてのフレーム(`constructorOpt` を含む)は生成されたスタックトレースから省略されます。 - -`constructorOpt` 引数は、エラー生成の実装詳細をユーザーから隠すのに便利です。例: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // スタックトレースを二重に計算しないよう、スタックトレースなしでエラーを作成 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 関数 b より上のスタックトレースをキャプチャ - Error.captureStackTrace(error, b); // 関数 c と b はスタックトレースに含まれません - throw error; -} - -a(); -``` +ターゲットオブジェクトに .stack プロパティを作成します #### パラメーター {#parameters} @@ -206,33 +196,3 @@ a(); #### 継承元 {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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) 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 index 10ac7f6..4c805d7 100644 --- 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 @@ -56,7 +56,7 @@ readonly optional cause: MCPAuthBearerAuthErrorDetails; readonly code: BearerAuthErrorCode; ``` -エラーコードは snake_case 形式です。 +スネークケース形式のエラーコードです。 #### 継承元 {#inherited-from} @@ -100,17 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` プロパティは、スタックトレース(`new Error().stack` または `Error.captureStackTrace(obj)` で生成される)の際に収集されるスタックフレーム数を指定します。 +スタックトレースのフォーマットをカスタマイズするためのオプションのオーバーライド + +#### パラメーター {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 戻り値 {#returns} + +`any` + +#### 参照 {#see} -デフォルト値は `10` ですが、有効な JavaScript の数値であれば任意に設定できます。値を変更した後にキャプチャされたスタックトレースに影響します。 +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} @@ -132,7 +158,8 @@ toJson(showCause: boolean): Record; `boolean` = `false` -エラーの原因を JSON レスポンスに含めるかどうか。デフォルトは `false` です。 +JSON レスポンスにエラーの原因を含めるかどうか。 +デフォルトは `false` です。 #### 戻り値 {#returns} @@ -150,45 +177,7 @@ toJson(showCause: boolean): Record; static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -`targetObject` に `.stack` プロパティを作成し、アクセス時に -`Error.captureStackTrace()` が呼び出されたコード位置を表す文字列を返します。 - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // `new Error().stack` と同様 -``` - -トレースの最初の行は -`${myObject.name}: ${myObject.message}` で始まります。 - -オプションの `constructorOpt` 引数には関数を指定できます。指定した場合、`constructorOpt` より上のすべてのフレーム(`constructorOpt` を含む)は生成されたスタックトレースから省略されます。 - -`constructorOpt` 引数は、エラー生成の実装詳細をユーザーから隠すのに便利です。例: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // スタックトレースを二重に計算しないよう、スタックトレースなしでエラーを作成 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 関数 b より上のスタックトレースをキャプチャ - Error.captureStackTrace(error, b); // 関数 c と b はスタックトレースに含まれません - throw error; -} - -a(); -``` +ターゲットオブジェクトに .stack プロパティを作成します #### パラメーター {#parameters} @@ -207,33 +196,3 @@ a(); #### 継承元 {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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) 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 index 34e9be3..4b1f455 100644 --- 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 @@ -104,17 +104,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` プロパティは、スタックトレース(`new Error().stack` または `Error.captureStackTrace(obj)` で生成される)によって収集されるスタックフレームの数を指定します。 +スタックトレースのフォーマットをカスタマイズするためのオプションのオーバーライド + +#### パラメーター {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 戻り値 {#returns} + +`any` + +#### 参照 {#see} -デフォルト値は `10` ですが、有効な JavaScript の数値であれば任意に設定できます。値を変更した後にキャプチャされたすべてのスタックトレースに影響します。 +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} @@ -136,7 +162,8 @@ toJson(showCause: boolean): Record; `boolean` = `false` -JSON レスポンスにエラーの原因を含めるかどうか。デフォルトは `false` です。 +JSON レスポンスにエラーの原因を含めるかどうか。 +デフォルトは `false` です。 #### 戻り値 {#returns} @@ -154,43 +181,7 @@ JSON レスポンスにエラーの原因を含めるかどうか。デフォル static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -`targetObject` に `.stack` プロパティを作成します。このプロパティにアクセスすると、`Error.captureStackTrace()` が呼び出されたコード位置を表す文字列が返されます。 - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // `new Error().stack` と同様 -``` - -トレースの最初の行は `${myObject.name}: ${myObject.message}` で始まります。 - -オプションの `constructorOpt` 引数には関数を指定できます。指定した場合、`constructorOpt` より上のすべてのフレーム(`constructorOpt` を含む)は生成されたスタックトレースから省略されます。 - -`constructorOpt` 引数は、エラー生成の実装詳細をユーザーから隠すのに便利です。例えば: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // スタックトレースを二重に計算しないよう、スタックトレースなしでエラーを作成 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 関数 b より上のスタックトレースをキャプチャ - Error.captureStackTrace(error, b); // 関数 c と b はスタックトレースに含まれません - throw error; -} - -a(); -``` +ターゲットオブジェクトに .stack プロパティを作成します #### パラメーター {#parameters} @@ -209,33 +200,3 @@ a(); #### 継承元 {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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) 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 index 4d098d7..1bfd3af 100644 --- 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 @@ -12,7 +12,7 @@ MCP の認証 (Authentication) および認可 (Authorization) に関連する - `Error` -## このクラスを継承するクラス {#extended-by} +## 継承先 {#extended-by} - [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) - [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) @@ -45,7 +45,7 @@ new MCPAuthError(code: string, message: string): MCPAuthError; `MCPAuthError` -#### オーバーライド元 {#overrides} +#### オーバーライド {#overrides} ```ts Error.constructor @@ -97,7 +97,7 @@ Error.message name: string = 'MCPAuthError'; ``` -#### オーバーライド元 {#overrides} +#### オーバーライド {#overrides} ```ts Error.name @@ -119,17 +119,45 @@ Error.stack *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` プロパティは、スタックトレース(`new Error().stack` または `Error.captureStackTrace(obj)` で生成される)によって収集されるスタックフレームの数を指定します。 +スタックトレースのフォーマットをカスタマイズするためのオプションのオーバーライド + +#### パラメーター {#parameters} + +##### err {#err} -デフォルト値は `10` ですが、有効な JavaScript の数値であれば任意に設定できます。値を変更した後にキャプチャされるすべてのスタックトレースに影響します。 +`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} @@ -168,45 +196,7 @@ JSON レスポンスにエラーの原因を含めるかどうか。 static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -`targetObject` に `.stack` プロパティを作成し、アクセス時に -`Error.captureStackTrace()` が呼び出されたコード位置を表す文字列を返します。 - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // `new Error().stack` と同様 -``` - -トレースの最初の行は -`${myObject.name}: ${myObject.message}` で始まります。 - -オプションの `constructorOpt` 引数には関数を指定できます。指定した場合、`constructorOpt` より上のすべてのフレーム(`constructorOpt` を含む)は生成されたスタックトレースから省略されます。 - -`constructorOpt` 引数は、エラー生成の実装詳細をユーザーから隠すのに便利です。例: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // スタックトレースを二重に計算しないように、スタックトレースなしでエラーを作成 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 関数 b より上のスタックトレースをキャプチャ - Error.captureStackTrace(error, b); // c と b はスタックトレースに含まれません - throw error; -} - -a(); -``` +ターゲットオブジェクトに .stack プロパティを作成します #### パラメーター {#parameters} @@ -227,35 +217,3 @@ a(); ```ts Error.captureStackTrace ``` - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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 -``` 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 index 3a2cce8..59c2c89 100644 --- 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 @@ -100,17 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` プロパティは、スタックトレース(`new Error().stack` または `Error.captureStackTrace(obj)` で生成される)によって収集されるスタックフレームの数を指定します。 +スタックトレースのフォーマットをカスタマイズするためのオプションのオーバーライド + +#### パラメーター {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -デフォルト値は `10` ですが、有効な JavaScript の数値であれば任意に設定できます。値を変更した後にキャプチャされたスタックトレースに影響します。 +`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} @@ -132,7 +158,8 @@ toJson(showCause: boolean): Record; `boolean` = `false` -エラーの原因を JSON レスポンスに含めるかどうか。デフォルトは `false` です。 +JSON レスポンスにエラーの原因を含めるかどうかを指定します。 +デフォルトは `false` です。 #### 戻り値 {#returns} @@ -150,46 +177,7 @@ toJson(showCause: boolean): Record; static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -`targetObject` に `.stack` プロパティを作成し、アクセス時に -`Error.captureStackTrace()` が呼び出されたコード位置を表す文字列を返します。 - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // `new Error().stack` と同様 -``` - -トレースの最初の行は -`${myObject.name}: ${myObject.message}` で始まります。 - -オプションの `constructorOpt` 引数には関数を指定できます。指定した場合、`constructorOpt` を含むそれより上のすべてのフレームが -生成されたスタックトレースから省略されます。 - -`constructorOpt` 引数は、エラー生成の実装詳細をユーザーから隠すのに便利です。例: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // スタックトレースを二重に計算しないよう、スタックトレースなしでエラーを作成 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 関数 b より上のスタックトレースをキャプチャ - Error.captureStackTrace(error, b); // 関数 c と b はスタックトレースに含まれません - throw error; -} - -a(); -``` +ターゲットオブジェクトに .stack プロパティを作成します #### パラメーター {#parameters} @@ -208,33 +196,3 @@ a(); #### 継承元 {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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) 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 index 3e03ad3..3cf84d5 100644 --- 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 @@ -8,7 +8,7 @@ sidebar_label: createVerifyJwt function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; ``` -指定されたキー取得関数とオプションを使用して、JWT アクセス トークン (Access token) を検証する関数を作成します。 +指定されたキー取得関数およびオプションを使用して、JWT アクセス トークン (Access token) を検証する関数を作成します。 ## パラメーター {#parameters} @@ -16,7 +16,7 @@ function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): V `JWTVerifyGetKey` -JWT を検証するために使用するキーを取得する関数です。 +JWT を検証するために使用されるキーを取得する関数。 **参照** @@ -26,7 +26,7 @@ JWT を検証するために使用するキーを取得する関数です。 `JWTVerifyOptions` -オプションの JWT 検証オプションです。 +オプションの JWT 検証オプション。 **参照** 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 index 8b7d4e4..715e3a9 100644 --- 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 @@ -5,12 +5,12 @@ sidebar_label: fetchServerConfig # 関数: fetchServerConfig() ```ts -function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; +function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; ``` -発行者 (Issuer) と認可サーバーの種類に基づいてサーバー設定を取得します。 +発行者 (Issuer) と認可サーバーの種類に基づいてサーバー構成を取得します。 -この関数は、サーバーの種類に応じて自動的に well-known URL を判別します。OAuth および OpenID Connect サーバーは、メタデータエンドポイントの規約が異なります。 +この関数はサーバーの種類に応じて自動的に well-known URL を判別します。OAuth および OpenID Connect サーバーはメタデータエンドポイントの規約が異なります。 ## パラメーター {#parameters} @@ -24,13 +24,13 @@ function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promis `ServerMetadataConfig` -サーバーの種類およびオプションのトランスパイル関数を含む設定オブジェクト。 +サーバーの種類やオプションのトランスパイル関数を含む設定オブジェクト。 ## 戻り値 {#returns} -`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> +`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -サーバー設定を解決する Promise。 +取得したメタデータを含む静的なサーバー構成を解決する Promise。 ## 参照 {#see} @@ -42,18 +42,18 @@ function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promis ```ts import { fetchServerConfig } from 'mcp-auth'; -// OAuth サーバー設定の取得 +// OAuth サーバー構成の取得 // これは `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` からメタデータを取得します const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { type: 'oauth' }); -// OpenID Connect サーバー設定の取得 +// OpenID Connect サーバー構成の取得 // これは `https://auth.logto.io/oidc/.well-known/openid-configuration` からメタデータを取得します const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); ``` ## 例外 {#throws} -フェッチ操作が失敗した場合にスローされます。 +フェッチ操作に失敗した場合にスローされます。 ## 例外 {#throws} 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 index 4f66b26..66f5a27 100644 --- 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 @@ -5,10 +5,10 @@ sidebar_label: fetchServerConfigByWellKnownUrl # 関数: fetchServerConfigByWellKnownUrl() ```ts -function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; +function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; ``` -指定された well-known URL からサーバー構成を取得し、それを MCP 仕様に照らして検証します。 +指定された well-known URL からサーバー構成を取得し、それを MCP 仕様に対して検証します。 サーバーメタデータが期待されるスキーマに準拠していない場合でも、互換性があると確信している場合は、`transpileData` 関数を定義してメタデータを期待される形式に変換できます。 @@ -28,9 +28,9 @@ function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: Ser ## 戻り値 {#returns} -`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> +`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -サーバー構成を解決する Promise。 +取得したメタデータを含む静的サーバー構成に解決される Promise。 ## 例外 {#throws} @@ -38,4 +38,4 @@ function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: Ser ## 例外 {#throws} -サーバーメタデータが無効、または MCP 仕様に一致しない場合にスローされます。 +サーバーメタデータが無効、または 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 new file mode 100644 index 0000000..46c156c --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md @@ -0,0 +1,24 @@ +--- +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 index 6f2fae3..03812c3 100644 --- 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 @@ -8,16 +8,16 @@ sidebar_label: handleBearerAuth function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; ``` -Express アプリケーションで Bearer 認証 (Bearer auth) を処理するためのミドルウェア関数を作成します。 +Express アプリケーションで Bearer 認証を処理するためのミドルウェア関数を作成します。 -このミドルウェアは、`Authorization` ヘッダーから Bearer トークンを抽出し、指定された `verifyAccessToken` 関数を使用して検証し、発行者、オーディエンス、必要なスコープをチェックします。 +このミドルウェアは、`Authorization` ヘッダーから Bearer トークンを抽出し、指定された `verifyAccessToken` 関数を使って検証し、発行者 (Issuer)、オーディエンス (Audience)、および必要なスコープ (Scope) をチェックします。 - トークンが有効な場合、認証情報を `request.auth` プロパティに追加します。有効でない場合は、適切なエラーメッセージで応答します。 - アクセス トークン (Access token) の検証に失敗した場合、401 Unauthorized エラーで応答します。 - トークンに必要なスコープ (Scope) が含まれていない場合、403 Forbidden エラーで応答します。 - 認証 (Authentication) プロセス中に予期しないエラーが発生した場合、ミドルウェアはそれらを再スローします。 -**注意:** `request.auth` オブジェクトには、`@modelcontextprotocol/sdk` モジュールで定義されている標準の AuthInfo インターフェースと比較して拡張されたフィールドが含まれます。詳細はこのファイル内の拡張インターフェースを参照してください。 +**注意:** `request.auth` オブジェクトには、`@modelcontextprotocol/sdk` モジュールで定義されている標準の AuthInfo インターフェースよりも拡張されたフィールドが含まれます。詳細はこのファイル内の拡張インターフェースを参照してください。 ## パラメーター {#parameters} @@ -25,13 +25,13 @@ Express アプリケーションで Bearer 認証 (Bearer auth) を処理する [`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) -Bearer 認証 (Bearer auth) ハンドラーの設定。 +Bearer 認証 (Authentication) ハンドラーの設定。 ## 戻り値 {#returns} `RequestHandler` -Bearer 認証 (Bearer auth) を処理する Express 用ミドルウェア関数。 +Bearer 認証 (Authentication) を処理する Express 用のミドルウェア関数。 ## 参照 {#see} 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 index b69e6c7..f0dbc99 100644 --- 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 @@ -5,43 +5,13 @@ sidebar_label: AuthServerConfig # 型エイリアス: AuthServerConfig ```ts -type AuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; - type: AuthServerType; -}; +type AuthServerConfig = + | ResolvedAuthServerConfig + | AuthServerDiscoveryConfig; ``` -MCP サーバーと統合されたリモート認可サーバー (Authorization server) の設定です。 +MCP サーバーと統合されたリモート認可サーバー (Authorization server) の設定。 -## プロパティ {#properties} - -### metadata {#metadata} - -```ts -metadata: CamelCaseAuthorizationServerMetadata; -``` - -認可サーバー (Authorization server) のメタデータで、MCP 仕様(OAuth 2.0 認可サーバーメタデータ (Authorization Server Metadata) に基づく)に準拠している必要があります。 - -このメタデータは通常、サーバーの well-known エンドポイント(OAuth 2.0 認可サーバーメタデータ (Authorization Server Metadata) または OpenID Connect Discovery)から取得されます。サーバーがそのようなエンドポイントをサポートしていない場合は、設定内で直接指定することもできます。 - -**注意:** メタデータは mcp-auth ライブラリの推奨に従い、camelCase 形式である必要があります。 - -#### 参照 {#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} - -[AuthServerType](/references/js/type-aliases/AuthServerType.md) で利用可能な値を確認できます。 +次のいずれかになります: +- **解決済み (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/AuthServerConfigWarning.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md index 5a3c435..8142835 100644 --- 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 @@ -31,4 +31,4 @@ code: AuthServerConfigWarningCode; description: string; ``` -警告の人間が読める説明です。 +警告の人間が読める説明です。 \ 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 new file mode 100644 index 0000000..6c039e4 --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md @@ -0,0 +1,57 @@ +--- +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/AuthServerModeConfig.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerModeConfig.md index bc69700..8a4012e 100644 --- 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 @@ -10,7 +10,7 @@ type AuthServerModeConfig = { }; ``` -レガシーの MCP サーバーを認可サーバーモードとして使用するための設定。 +レガシーの MCP サーバーを認可サーバーモードとして使用するための設定です。 ## 非推奨 {#deprecated} @@ -24,7 +24,7 @@ type AuthServerModeConfig = { server: AuthServerConfig; ``` -単一の認可サーバー設定。 +単一の認可サーバー設定です。 #### 非推奨 {#deprecated} 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 index 3848338..62db32d 100644 --- 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 @@ -5,224 +5,11 @@ sidebar_label: AuthorizationServerMetadata # 型エイリアス: AuthorizationServerMetadata ```ts -type AuthorizationServerMetadata = { - authorization_endpoint: string; - code_challenge_methods_supported?: string[]; - grant_types_supported?: string[]; - introspection_endpoint?: string; - introspection_endpoint_auth_methods_supported?: string[]; - introspection_endpoint_auth_signing_alg_values_supported?: string[]; - issuer: string; - jwks_uri?: string; - op_policy_uri?: string; - op_tos_uri?: string; - registration_endpoint?: string; - response_modes_supported?: string[]; - response_types_supported: string[]; - revocation_endpoint?: string; - revocation_endpoint_auth_methods_supported?: string[]; - revocation_endpoint_auth_signing_alg_values_supported?: string[]; - scopes_supported?: string[]; - service_documentation?: string; - token_endpoint: string; - token_endpoint_auth_methods_supported?: string[]; - token_endpoint_auth_signing_alg_values_supported?: string[]; - ui_locales_supported?: string[]; - userinfo_endpoint?: string; -}; +type AuthorizationServerMetadata = z.infer; ``` RFC 8414 で定義されている OAuth 2.0 認可サーバーメタデータ (Authorization Server Metadata) のスキーマです。 -## 型定義 {#type-declaration} - -### authorization\_endpoint {#authorization-endpoint} - -```ts -authorization_endpoint: string; -``` - -認可サーバーの認可エンドポイントの URL [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]。 -認可エンドポイントを使用するグラントタイプがサポートされていない場合を除き、これは必須です。 - -#### 参照 {#see} - -https://rfc-editor.org/rfc/rfc6749#section-3.1 - -### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} - -```ts -optional code_challenge_methods_supported: string[]; -``` - -この認可サーバーがサポートする Proof Key for Code Exchange (PKCE) -[[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] のコードチャレンジ方式のリストを含む JSON 配列です。 - -### grant\_types\_supported? {#grant-types-supported} - -```ts -optional grant_types_supported: string[]; -``` - -この認可サーバーがサポートする OAuth 2.0 グラントタイプ値のリストを含む JSON 配列です。配列の値は、「OAuth 2.0 Dynamic Client Registration Protocol」[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)] で定義されている `grant_types` パラメーターで使用されるものと同じです。 -省略された場合、デフォルト値は `["authorization_code", "implicit"]` です。 - -### introspection\_endpoint? {#introspection-endpoint} - -```ts -optional introspection_endpoint: string; -``` - -認可サーバーの OAuth 2.0 インスペクションエンドポイントの URL -[[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]。 - -### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} - -```ts -optional introspection_endpoint_auth_methods_supported: string[]; -``` - -### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} - -```ts -optional introspection_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### issuer {#issuer} - -```ts -issuer: string; -``` - -認可サーバーの発行者 (Issuer) 識別子であり、`https` スキームを使用し、クエリやフラグメントコンポーネントを持たない URL です。 - -### jwks\_uri? {#jwks-uri} - -```ts -optional jwks_uri: string; -``` - -認可サーバーの JWK Set [[JWK](https://www.rfc-editor.org/rfc/rfc8414.html#ref-JWK)] -ドキュメントの URL。参照されるドキュメントには、クライアントが認可サーバーからの署名を検証するために使用する署名鍵が含まれています。この URL は `https` スキームを使用しなければなりません。 - -### op\_policy\_uri? {#op-policy-uri} - -```ts -optional op_policy_uri: string; -``` - -### op\_tos\_uri? {#op-tos-uri} - -```ts -optional op_tos_uri: string; -``` - -### registration\_endpoint? {#registration-endpoint} - -```ts -optional registration_endpoint: string; -``` - -認可サーバーの OAuth 2.0 ダイナミッククライアント登録エンドポイントの URL -[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]。 - -### response\_modes\_supported? {#response-modes-supported} - -```ts -optional response_modes_supported: string[]; -``` - -この認可サーバーがサポートする OAuth 2.0 の `response_mode` 値のリストを含む JSON 配列です。「OAuth 2.0 Multiple Response Type Encoding Practices」 -[[OAuth.Responses](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Responses)] で規定されています。 - -省略された場合、デフォルトは `["query", "fragment"]` です。レスポンスモード値 `"form_post"` も「OAuth 2.0 Form Post Response Mode」 -[[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)] で定義されています。 - -### response\_types\_supported {#response-types-supported} - -```ts -response_types_supported: string[]; -``` - -この認可サーバーがサポートする OAuth 2.0 の `response_type` 値のリストを含む JSON 配列です。配列の値は、「OAuth 2.0 Dynamic Client Registration Protocol」 -[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)] で定義されている `response_types` パラメーターで使用されるものと同じです。 - -### revocation\_endpoint? {#revocation-endpoint} - -```ts -optional revocation_endpoint: string; -``` - -認可サーバーの OAuth 2.0 取り消しエンドポイントの URL -[[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]。 - -### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} - -```ts -optional revocation_endpoint_auth_methods_supported: string[]; -``` - -### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} - -```ts -optional revocation_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### scopes\_supported? {#scopes-supported} - -```ts -optional scopes_supported: string[]; -``` - -この認可サーバーがサポートする OAuth 2.0 の `scope` 値のリストを含む JSON 配列です。 -[[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] - -### service\_documentation? {#service-documentation} - -```ts -optional service_documentation: string; -``` - -### token\_endpoint {#token-endpoint} - -```ts -token_endpoint: string; -``` - -認可サーバーのトークンエンドポイントの URL [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]。 -暗黙的グラントタイプのみがサポートされている場合を除き、これは必須です。 - -#### 参照 {#see} - -https://rfc-editor.org/rfc/rfc6749#section-3.2 - -### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} - -```ts -optional token_endpoint_auth_methods_supported: string[]; -``` - -### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} - -```ts -optional token_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### ui\_locales\_supported? {#ui-locales-supported} - -```ts -optional ui_locales_supported: string[]; -``` - -### userinfo\_endpoint? {#userinfo-endpoint} - -```ts -optional userinfo_endpoint: string; -``` - -OpenID Connect の [userinfo エンドポイント](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) の URL。 -このエンドポイントは、認証済みユーザーに関する情報を取得するために使用されます。 - ## 参照 {#see} -https://datatracker.ietf.org/doc/html/rfc8414 +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 index 119de07..61cb290 100644 --- 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 @@ -24,7 +24,7 @@ type BearerAuthConfig = { optional audience: string; ``` -アクセス トークン (アクセス トークン) の想定されるオーディエンス (`aud` クレーム)。これは通常、トークンが意図されているリソースサーバー (API) です。指定しない場合、オーディエンスのチェックはスキップされます。 +アクセス トークン (アクセス トークン) の期待されるオーディエンス (`aud` クレーム)。これは通常、トークンが意図されているリソースサーバー (API) です。指定しない場合、オーディエンスのチェックはスキップされます。 **注:** 認可サーバーがリソースインジケーター (RFC 8707) をサポートしていない場合、このフィールドは省略できます。なぜなら、オーディエンスが関連しない場合があるためです。 @@ -44,13 +44,13 @@ issuer: 有効な発行者 (Issuer) を表す文字列、またはアクセス トークンの発行者を検証するための関数。 -文字列が指定された場合は、直接比較のための想定される発行者値として使用されます。 +文字列が指定された場合、それが期待される発行者 (Issuer) の値として直接比較に使用されます。 -関数が指定された場合は、[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) のルールに従って発行者を検証する必要があります。 +関数が指定された場合は、[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) のルールに従って発行者 (Issuer) を検証する必要があります。 #### 参照 {#see} -検証関数の詳細については [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) を参照してください。 +[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) で検証関数の詳細を確認できます。 *** @@ -62,7 +62,7 @@ optional requiredScopes: string[]; アクセス トークンが持つべき必須スコープ (スコープ) の配列。トークンにこれらすべてのスコープが含まれていない場合、エラーがスローされます。 -**注:** ハンドラーはトークン内の `scope` クレームをチェックします。これは認可サーバーの実装によって、スペース区切りの文字列または文字列の配列である場合があります。`scope` クレームが存在しない場合、利用可能であれば `scopes` クレームをチェックします。 +**注:** ハンドラーはトークン内の `scope` クレームをチェックします。これは認可サーバーの実装によって、スペース区切りの文字列または文字列配列である場合があります。`scope` クレームが存在しない場合、`scopes` クレームがあればそちらをチェックします。 *** @@ -82,7 +82,7 @@ optional resource: string; optional showErrorDetails: boolean; ``` -レスポンスに詳細なエラー情報を表示するかどうか。これは開発中のデバッグに役立ちますが、本番環境では機密情報漏洩を防ぐために無効にする必要があります。 +レスポンスに詳細なエラー情報を表示するかどうか。これは開発中のデバッグに便利ですが、本番環境では機密情報漏洩を防ぐため無効にするべきです。 #### デフォルト {#default} @@ -104,4 +104,4 @@ verifyAccessToken: VerifyAccessTokenFunction; #### 参照 {#see} -詳細については [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) を参照してください。 +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) で詳細を確認できます。 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 index 22a0143..d8df81f 100644 --- 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 @@ -5,175 +5,11 @@ sidebar_label: CamelCaseAuthorizationServerMetadata # 型エイリアス: CamelCaseAuthorizationServerMetadata ```ts -type CamelCaseAuthorizationServerMetadata = { - authorizationEndpoint: string; - codeChallengeMethodsSupported?: string[]; - grantTypesSupported?: string[]; - introspectionEndpoint?: string; - introspectionEndpointAuthMethodsSupported?: string[]; - introspectionEndpointAuthSigningAlgValuesSupported?: string[]; - issuer: string; - jwksUri?: string; - opPolicyUri?: string; - opTosUri?: string; - registrationEndpoint?: string; - responseModesSupported?: string[]; - responseTypesSupported: string[]; - revocationEndpoint?: string; - revocationEndpointAuthMethodsSupported?: string[]; - revocationEndpointAuthSigningAlgValuesSupported?: string[]; - scopesSupported?: string[]; - serviceDocumentation?: string; - tokenEndpoint: string; - tokenEndpointAuthMethodsSupported?: string[]; - tokenEndpointAuthSigningAlgValuesSupported?: string[]; - uiLocalesSupported?: string[]; - userinfoEndpoint?: string; -}; +type CamelCaseAuthorizationServerMetadata = z.infer; ``` -OAuth 2.0 認可サーバーメタデータ (Authorization Server Metadata) 型の camelCase バージョンです。 - -## 型定義 {#type-declaration} - -### authorizationEndpoint {#authorizationendpoint} - -```ts -authorizationEndpoint: string; -``` - -### codeChallengeMethodsSupported? {#codechallengemethodssupported} - -```ts -optional codeChallengeMethodsSupported: string[]; -``` - -### grantTypesSupported? {#granttypessupported} - -```ts -optional grantTypesSupported: string[]; -``` - -### introspectionEndpoint? {#introspectionendpoint} - -```ts -optional introspectionEndpoint: string; -``` - -### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} - -```ts -optional introspectionEndpointAuthMethodsSupported: string[]; -``` - -### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} - -```ts -optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### issuer {#issuer} - -```ts -issuer: string; -``` - -### jwksUri? {#jwksuri} - -```ts -optional jwksUri: string; -``` - -### opPolicyUri? {#oppolicyuri} - -```ts -optional opPolicyUri: string; -``` - -### opTosUri? {#optosuri} - -```ts -optional opTosUri: string; -``` - -### registrationEndpoint? {#registrationendpoint} - -```ts -optional registrationEndpoint: string; -``` - -### responseModesSupported? {#responsemodessupported} - -```ts -optional responseModesSupported: string[]; -``` - -### responseTypesSupported {#responsetypessupported} - -```ts -responseTypesSupported: string[]; -``` - -### revocationEndpoint? {#revocationendpoint} - -```ts -optional revocationEndpoint: string; -``` - -### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} - -```ts -optional revocationEndpointAuthMethodsSupported: string[]; -``` - -### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} - -```ts -optional revocationEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### scopesSupported? {#scopessupported} - -```ts -optional scopesSupported: string[]; -``` - -### serviceDocumentation? {#servicedocumentation} - -```ts -optional serviceDocumentation: string; -``` - -### tokenEndpoint {#tokenendpoint} - -```ts -tokenEndpoint: string; -``` - -### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} - -```ts -optional tokenEndpointAuthMethodsSupported: string[]; -``` - -### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} - -```ts -optional tokenEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### uiLocalesSupported? {#uilocalessupported} - -```ts -optional uiLocalesSupported: string[]; -``` - -### userinfoEndpoint? {#userinfoendpoint} - -```ts -optional userinfoEndpoint: string; -``` +OAuth 2.0 認可サーバーメタデータ型の camelCase バージョンです。 ## 参照 {#see} -元の型およびフィールド情報については [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) を参照してください。 +[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 index c4a449e..c197dad 100644 --- 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 @@ -5,119 +5,11 @@ sidebar_label: CamelCaseProtectedResourceMetadata # 型エイリアス: CamelCaseProtectedResourceMetadata ```ts -type CamelCaseProtectedResourceMetadata = { - authorizationDetailsTypesSupported?: string[]; - authorizationServers?: string[]; - bearerMethodsSupported?: string[]; - dpopBoundAccessTokensRequired?: boolean; - dpopSigningAlgValuesSupported?: string[]; - jwksUri?: string; - resource: string; - resourceDocumentation?: string; - resourceName?: string; - resourcePolicyUri?: string; - resourceSigningAlgValuesSupported?: string[]; - resourceTosUri?: string; - scopesSupported?: string[]; - signedMetadata?: string; - tlsClientCertificateBoundAccessTokens?: boolean; -}; +type CamelCaseProtectedResourceMetadata = z.infer; ``` OAuth 2.0 Protected Resource Metadata 型の camelCase バージョンです。 -## 型定義 {#type-declaration} - -### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} - -```ts -optional authorizationDetailsTypesSupported: string[]; -``` - -### authorizationServers? {#authorizationservers} - -```ts -optional authorizationServers: string[]; -``` - -### bearerMethodsSupported? {#bearermethodssupported} - -```ts -optional bearerMethodsSupported: string[]; -``` - -### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} - -```ts -optional dpopBoundAccessTokensRequired: boolean; -``` - -### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} - -```ts -optional dpopSigningAlgValuesSupported: string[]; -``` - -### jwksUri? {#jwksuri} - -```ts -optional jwksUri: string; -``` - -### resource {#resource} - -```ts -resource: string; -``` - -### resourceDocumentation? {#resourcedocumentation} - -```ts -optional resourceDocumentation: string; -``` - -### resourceName? {#resourcename} - -```ts -optional resourceName: string; -``` - -### resourcePolicyUri? {#resourcepolicyuri} - -```ts -optional resourcePolicyUri: string; -``` - -### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} - -```ts -optional resourceSigningAlgValuesSupported: string[]; -``` - -### resourceTosUri? {#resourcetosuri} - -```ts -optional resourceTosUri: string; -``` - -### scopesSupported? {#scopessupported} - -```ts -optional scopesSupported: string[]; -``` - -### signedMetadata? {#signedmetadata} - -```ts -optional signedMetadata: string; -``` - -### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} - -```ts -optional tlsClientCertificateBoundAccessTokens: boolean; -``` - ## 参照 {#see} -元の型およびフィールド情報については、 [ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) を参照してください。 +元の型およびフィールド情報については、 [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/ProtectedResourceMetadata.md b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ProtectedResourceMetadata.md index 459d38d..fda97ab 100644 --- 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 @@ -5,147 +5,7 @@ sidebar_label: ProtectedResourceMetadata # 型エイリアス: ProtectedResourceMetadata ```ts -type ProtectedResourceMetadata = { - authorization_details_types_supported?: string[]; - authorization_servers?: string[]; - bearer_methods_supported?: string[]; - dpop_bound_access_tokens_required?: boolean; - dpop_signing_alg_values_supported?: string[]; - jwks_uri?: string; - resource: string; - resource_documentation?: string; - resource_name?: string; - resource_policy_uri?: string; - resource_signing_alg_values_supported?: string[]; - resource_tos_uri?: string; - scopes_supported?: string[]; - signed_metadata?: string; - tls_client_certificate_bound_access_tokens?: boolean; -}; +type ProtectedResourceMetadata = z.infer; ``` -OAuth 2.0 保護されたリソースメタデータのスキーマです。 - -## 型宣言 {#type-declaration} - -### authorization\_details\_types\_supported? {#authorization-details-types-supported} - -```ts -optional authorization_details_types_supported: string[]; -``` - -authorization_details リクエストパラメーターを使用する際にサポートされる認可詳細タイプの値。 - -### authorization\_servers? {#authorization-servers} - -```ts -optional authorization_servers: string[]; -``` - -この保護されたリソースで使用できる OAuth 認可サーバーの発行者識別子のリスト。 - -### bearer\_methods\_supported? {#bearer-methods-supported} - -```ts -optional bearer_methods_supported: string[]; -``` - -OAuth 2.0 ベアラートークンの送信にサポートされる方法。値: ["header", "body", "query"]。 - -### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} - -```ts -optional dpop_bound_access_tokens_required: boolean; -``` - -この保護されたリソースが常に DPoP バインド付きアクセス トークン (アクセス トークン) を必要とするかどうか。 - -### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} - -```ts -optional dpop_signing_alg_values_supported: string[]; -``` - -DPoP 証明 JWT の検証にサポートされる JWS アルゴリズム。 - -### jwks\_uri? {#jwks-uri} - -```ts -optional jwks_uri: string; -``` - -保護されたリソースの JSON Web Key (JWK) セットドキュメントの URL。このドキュメントには、この保護されたリソースから返されるレスポンスやデータのデジタル署名を検証するために使用できる公開鍵が含まれています。 -これはトークン検証に使用される認可サーバーの jwks_uri とは異なります。保護されたリソースがレスポンスに署名する場合、クライアントはこれらの公開鍵を取得して受信データの真正性と完全性を検証できます。 - -### resource {#resource} - -```ts -resource: string; -``` - -保護されたリソースのリソース識別子。 - -### resource\_documentation? {#resource-documentation} - -```ts -optional resource_documentation: string; -``` - -保護されたリソースの利用方法に関する開発者向けドキュメントの URL。 - -### resource\_name? {#resource-name} - -```ts -optional resource_name: string; -``` - -エンドユーザー向けに表示するための保護されたリソースの人間が読める名前。 - -### resource\_policy\_uri? {#resource-policy-uri} - -```ts -optional resource_policy_uri: string; -``` - -保護されたリソースのデータ利用要件に関する情報を含む URL。 - -### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} - -```ts -optional resource_signing_alg_values_supported: string[]; -``` - -リソースレスポンスの署名に保護されたリソースがサポートする JWS 署名アルゴリズム。 - -### resource\_tos\_uri? {#resource-tos-uri} - -```ts -optional resource_tos_uri: string; -``` - -保護されたリソースの利用規約を含む URL。 - -### scopes\_supported? {#scopes-supported} - -```ts -optional scopes_supported: string[]; -``` - -この保護されたリソースへアクセスするための認可リクエストで使用されるスコープ (スコープ) のリスト。 - -### signed\_metadata? {#signed-metadata} - -```ts -optional signed_metadata: string; -``` - -クレームとしてメタデータパラメーターを含む署名付き JWT。この JWT は JWS を使用して署名され、'iss' クレームを含める必要があります。このフィールドは、メタデータ自体の真正性を暗号学的に検証する方法を提供します。署名は `jwks_uri` エンドポイントで利用可能な公開鍵を使用して検証できます。 -存在する場合、この署名付きメタデータ内の値は、このメタデータドキュメント内の対応するプレーン JSON 値よりも優先されます。これにより、リソースメタデータの改ざんを防ぐことができます。 - -### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} - -```ts -optional tls_client_certificate_bound_access_tokens: boolean; -``` - -保護されたリソースが相互 TLS クライアント証明書バインド付きアクセス トークン (アクセス トークン) をサポートするかどうか。 \ No newline at end of file +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 new file mode 100644 index 0000000..3a921df --- /dev/null +++ b/i18n/ja/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md @@ -0,0 +1,49 @@ +--- +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 index ad853f7..b263b81 100644 --- 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 @@ -20,4 +20,4 @@ MCP サーバーをリソースサーバーモードとして構成するため 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 index 12b1a93..b67b52c 100644 --- 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 @@ -12,8 +12,8 @@ type ValidateIssuerFunction = (tokenIssuer: string) => void; この関数は、発行者 (Issuer) が有効でない場合、コード 'invalid_issuer' の [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md) をスローする必要があります。発行者 (Issuer) は以下に対して検証されるべきです: -1. MCP-Auth の認可サーバーメタデータで設定された認可サーバー (Authorization servers) -2. 保護されたリソースのメタデータに記載された認可サーバー (Authorization servers) +1. MCP-Auth の認可サーバーメタデータで設定された認可サーバー +2. 保護されたリソースのメタデータに記載されている認可サーバー ## パラメーター {#parameters} 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 index 9f3a787..6eea922 100644 --- 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 @@ -14,11 +14,11 @@ type VerifyAccessTokenFunction = (token: string) => MaybePromise; 例えば、JWT 検証関数がある場合、少なくともトークンの署名を確認し、有効期限を検証し、必要なクレーム (Claims) を抽出して `AuthInfo` オブジェクトを返す必要があります。 -**注意:** 次のフィールドについては、ハンドラー側で確認されるため、トークン内で検証する必要はありません: +**注意:** 次のフィールドはハンドラーによって検証されるため、トークン内で検証する必要はありません: -- `iss`(発行者 (Issuer)) -- `aud`(オーディエンス (Audience)) -- `scope`(スコープ (Scopes)) +- `iss` (発行者) +- `aud` (オーディエンス) +- `scope` (スコープ) ## パラメーター {#parameters} @@ -26,7 +26,7 @@ type VerifyAccessTokenFunction = (token: string) => MaybePromise; `string` -検証対象のアクセス トークン (Access token) 文字列。 +検証するアクセス トークン (Access token) の文字列。 ## 戻り値 {#returns} 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 index dfbc6ee..66a4f6b 100644 --- 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 @@ -5,11 +5,35 @@ sidebar_label: authorizationServerMetadataSchema # 変数: authorizationServerMetadataSchema ```ts -const authorizationServerMetadataSchema: ZodObject; +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 認可サーバーメタデータのための Zod スキーマです。 +RFC 8414 で定義されている OAuth 2.0 認可サーバーメタデータ (Authorization Server Metadata) 用の Zod スキーマです。 -## 参考 {#see} +## 参照 {#see} -https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file +https://datatracker.ietf.org/doc/html/rfc8414 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 index d1d5ad5..d00d981 100644 --- 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 @@ -5,11 +5,35 @@ sidebar_label: camelCaseAuthorizationServerMetadataSchema # 変数: camelCaseAuthorizationServerMetadataSchema ```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject; +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 スキーマの camelCase バージョンです。 +OAuth 2.0 認可サーバーメタデータ Zod スキーマの camelCase バージョンです。 ## 参照 {#see} -元のスキーマおよびフィールド情報については、 [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) を参照してください。 \ No newline at end of file +元のスキーマとフィールド情報については [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 index d5dfe27..8ead61e 100644 --- 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 @@ -5,7 +5,23 @@ sidebar_label: camelCaseProtectedResourceMetadataSchema # 変数: camelCaseProtectedResourceMetadataSchema ```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject; +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 バージョンです。 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 index e871e73..48765ef 100644 --- 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 @@ -5,7 +5,23 @@ sidebar_label: protectedResourceMetadataSchema # 変数: protectedResourceMetadataSchema ```ts -const protectedResourceMetadataSchema: ZodObject; +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/README.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/README.md index f7e3467..888b8d6 100644 --- a/i18n/ko/docusaurus-plugin-content-docs/current/references/js/README.md +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/README.md @@ -2,7 +2,7 @@ sidebar_label: Node.js SDK --- -# MCP Auth Node.js SDK 참고 +# MCP Auth Node.js SDK 참고서 ## 클래스 {#classes} @@ -21,6 +21,7 @@ sidebar_label: Node.js SDK - [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) @@ -33,6 +34,7 @@ sidebar_label: Node.js SDK - [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) @@ -56,4 +58,5 @@ sidebar_label: Node.js SDK - [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 index 233b0d2..642678f 100644 --- 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 @@ -10,21 +10,48 @@ mcp-auth 라이브러리의 주요 클래스입니다. 보호된 리소스에 ## 예시 {#example} -### `리소스 서버` 모드에서의 사용 {#usage-in-resource-server-mode} +### `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, fetchServerConfig } from 'mcp-auth'; +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`는 단일 구성 객체 또는 객체 배열이 될 수 있습니다. protectedResources: [ { metadata: { @@ -35,16 +62,20 @@ const mcpAuth = new MCPAuth({ }, ], }); +``` + +#### 미들웨어 사용하기 {#using-the-middleware} -// 보호된 리소스 메타데이터를 처리하는 라우터를 마운트합니다. +```ts +// 보호된 리소스 메타데이터를 처리하는 라우터를 마운트합니다 app.use(mcpAuth.protectedResourceMetadataRouter()); -// 구성된 리소스에 대한 API 엔드포인트를 보호합니다. +// 구성된 리소스에 대해 API 엔드포인트를 보호합니다 app.get( '/notes', mcpAuth.bearerAuth('jwt', { - resource: resourceIdentifier, // 이 엔드포인트가 속한 리소스를 지정합니다. - audience: resourceIdentifier, // 선택적으로 'aud' 클레임을 검증합니다. + resource: resourceIdentifier, // 이 엔드포인트가 속한 리소스를 지정 + audience: resourceIdentifier, // 선택적으로 'aud' 클레임을 검증 requiredScopes: ['read:notes'], }), (req, res) => { @@ -54,32 +85,30 @@ app.get( ); ``` -### `인가 (Authorization) 서버` 모드의 레거시 사용법 (더 이상 권장되지 않음) {#legacy-usage-in-authorization-server-mode-deprecated} +### `authorization server` 모드의 레거시 사용법 (더 이상 권장되지 않음) {#legacy-usage-in-authorization-server-mode-deprecated} 이 방식은 하위 호환성을 위해 지원됩니다. ```ts import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; +import { MCPAuth } from 'mcp-auth'; const app = express(); const mcpAuth = new MCPAuth({ - server: await fetchServerConfig( - 'https://auth.logto.io/oidc', - { type: 'oidc' } - ), + // Discovery config - 메타데이터를 필요할 때마다 가져옵니다 + server: { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }, }); -// 레거시 인가 (Authorization) 서버 메타데이터를 처리하는 라우터를 마운트합니다. +// 레거시 인가 (Authorization) 서버 메타데이터를 처리하는 라우터를 마운트합니다 app.use(mcpAuth.delegatedRouter()); -// 기본 정책을 사용하여 엔드포인트를 보호합니다. +// 기본 정책을 사용하여 엔드포인트를 보호합니다 app.get( '/mcp', mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), (req, res) => { console.log('Auth info:', req.auth); - // 여기서 MCP 요청을 처리합니다. + // 여기서 MCP 요청을 처리합니다 }, ); ``` @@ -135,7 +164,7 @@ bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit & VerifyJwtConfig): RequestHandler; ``` -사전 정의된 검증 모드를 사용하여 요청의 `Authorization` 헤더에 있는 액세스 토큰 (Access token)을 검증하는 Bearer 인증 (Authentication) 핸들러 (Express 미들웨어)를 생성합니다. +미리 정의된 검증 모드를 사용하여 요청의 `Authorization` 헤더에 있는 액세스 토큰 (Access token)을 검증하는 Bearer 인증 (Authentication) 핸들러 (Express 미들웨어)를 생성합니다. `'jwt'` 모드에서는 인가 (Authorization) 서버의 JWKS URI에서 JWK Set을 사용하여 JWT 검증 함수를 생성합니다. @@ -191,14 +220,14 @@ JWT 검증 옵션 및 원격 JWK set 옵션을 포함한 Bearer 인증 (Authenti **참고** - - JWT 검증을 위한 사용 가능한 구성 옵션은 VerifyJwtConfig에서 확인하세요. - - [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md)에서 사용 가능한 구성 옵션(단, `verifyAccessToken` 및 `issuer` 제외)을 확인하세요. + - JWT 검증을 위한 구성 옵션은 VerifyJwtConfig에서 확인하세요. + - 사용 가능한 구성 옵션은 [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md)에서 확인하세요 (`verifyAccessToken` 및 `issuer` 제외). ##### 반환값 {#returns} `RequestHandler` -액세스 토큰 (Access token)을 검증하고 검증 결과를 요청 객체 (`req.auth`)에 추가하는 Express 미들웨어 함수입니다. +액세스 토큰 (Access token)을 검증하고, 검증 결과를 요청 객체 (`req.auth`)에 추가하는 Express 미들웨어 함수입니다. ##### 참고 {#see} @@ -217,7 +246,7 @@ delegatedRouter(): Router; ``` 인스턴스에 제공된 메타데이터로 레거시 OAuth 2.0 인가 (Authorization) 서버 메타데이터 엔드포인트 -(`/.well-known/oauth-authorization-server`)를 제공하는 위임 라우터를 생성합니다. +(`/.well-known/oauth-authorization-server`)를 제공하는 delegated 라우터를 생성합니다. #### 반환값 {#returns} @@ -242,7 +271,7 @@ app.use(mcpAuth.delegatedRouter()); #### 예외 {#throws} -`리소스 서버` 모드에서 호출 시 예외가 발생합니다. +`resource server` 모드에서 호출 시 예외가 발생합니다. *** @@ -264,7 +293,7 @@ OAuth 2.0 보호된 리소스 메타데이터 엔드포인트를 제공하는 #### 예외 {#throws} -`인가 (Authorization) 서버` 모드에서 호출 시 예외가 발생합니다. +`authorization server` 모드에서 호출 시 예외가 발생합니다. #### 예시 {#example} 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 index cc9b2bf..f845631 100644 --- 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 @@ -100,18 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` 프로퍼티는 스택 트레이스가 수집하는 스택 프레임의 개수를 지정합니다 -(`new Error().stack` 또는 `Error.captureStackTrace(obj)`로 생성된 경우). +스택 트레이스 포맷팅을 위한 선택적 오버라이드 + +#### 매개변수 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -기본값은 `10`이지만, 유효한 JavaScript 숫자로 설정할 수 있습니다. 값이 변경된 _이후_에 캡처된 모든 스택 트레이스에 영향을 미칩니다. +`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} @@ -133,7 +158,7 @@ toJson(showCause: boolean): Record; `boolean` = `false` -오류의 원인(cause)을 JSON 응답에 포함할지 여부입니다. +JSON 응답에 오류의 원인을 포함할지 여부입니다. 기본값은 `false`입니다. #### 반환값 {#returns} @@ -152,46 +177,7 @@ toJson(showCause: boolean): Record; static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -`targetObject`에 `.stack` 프로퍼티를 생성하며, 접근 시 -`Error.captureStackTrace()`가 호출된 코드 위치를 나타내는 문자열을 반환합니다. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // `new Error().stack`과 유사 -``` - -트레이스의 첫 번째 줄은 -`${myObject.name}: ${myObject.message}`로 시작합니다. - -선택적 `constructorOpt` 인자는 함수입니다. 제공되면, `constructorOpt`를 포함하여 그 위의 모든 프레임이 -생성된 스택 트레이스에서 생략됩니다. - -`constructorOpt` 인자는 오류 생성의 구현 세부 정보를 사용자로부터 숨기고자 할 때 유용합니다. 예시: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // 스택 트레이스를 두 번 계산하지 않도록 스택 트레이스 없이 오류 생성 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 함수 b 위에서 스택 트레이스 캡처 - Error.captureStackTrace(error, b); // 함수 c와 b는 스택 트레이스에 포함되지 않음 - throw error; -} - -a(); -``` +대상 객체에 .stack 프로퍼티를 생성합니다 #### 매개변수 {#parameters} @@ -210,33 +196,3 @@ a(); #### 상속됨 {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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) 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 index 7a8c5ae..8f7e168 100644 --- 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 @@ -4,7 +4,7 @@ sidebar_label: MCPAuthBearerAuthError # 클래스: MCPAuthBearerAuthError -Bearer 토큰으로 인증 (Authentication)할 때 문제가 발생하면 발생하는 오류입니다. +Bearer 토큰으로 인증 (Authentication) 시 문제가 발생할 때 발생하는 오류입니다. ## 상속 {#extends} @@ -100,17 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` 프로퍼티는 스택 트레이스가 수집하는 스택 프레임의 개수를 지정합니다 (`new Error().stack` 또는 `Error.captureStackTrace(obj)`로 생성된 경우). +스택 트레이스 포맷팅을 위한 선택적 오버라이드 + +#### 매개변수 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -기본값은 `10`이지만, 유효한 JavaScript 숫자로 설정할 수 있습니다. 값이 변경된 이후에 캡처된 모든 스택 트레이스에 영향을 미칩니다. +`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} @@ -132,7 +158,8 @@ toJson(showCause: boolean): Record; `boolean` = `false` -JSON 응답에 오류의 원인(cause)을 포함할지 여부입니다. 기본값은 `false`입니다. +JSON 응답에 오류의 원인을 포함할지 여부입니다. +기본값은 `false`입니다. #### 반환값 {#returns} @@ -150,43 +177,7 @@ JSON 응답에 오류의 원인(cause)을 포함할지 여부입니다. 기본 static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -`targetObject`에 `.stack` 프로퍼티를 생성하며, 접근 시 `Error.captureStackTrace()`가 호출된 코드 위치를 나타내는 문자열을 반환합니다. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // `new Error().stack`과 유사 -``` - -트레이스의 첫 번째 줄은 `${myObject.name}: ${myObject.message}`로 시작합니다. - -선택적 `constructorOpt` 인자는 함수입니다. 제공되면, `constructorOpt`를 포함하여 그 위의 모든 프레임이 생성된 스택 트레이스에서 생략됩니다. - -`constructorOpt` 인자는 오류 생성의 구현 세부 정보를 사용자로부터 숨기는 데 유용합니다. 예시: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // 스택 트레이스를 두 번 계산하지 않도록 스택 트레이스 없는 오류 생성 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 함수 b 위에서 스택 트레이스 캡처 - Error.captureStackTrace(error, b); // 함수 c와 b는 스택 트레이스에 포함되지 않음 - throw error; -} - -a(); -``` +대상 객체에 .stack 프로퍼티를 생성합니다 #### 매개변수 {#parameters} @@ -205,33 +196,3 @@ a(); #### 상속됨 {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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) 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 index 3748904..8d529a0 100644 --- 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 @@ -104,19 +104,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` 프로퍼티는 스택 트레이스가 수집하는 스택 프레임의 개수를 지정합니다 -(`new Error().stack` 또는 `Error.captureStackTrace(obj)`로 생성된 경우). +스택 트레이스 형식을 지정하기 위한 선택적 오버라이드 + +#### 매개변수 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -기본값은 `10`이지만, 유효한 JavaScript 숫자로 설정할 수 있습니다. -값이 변경된 이후에 캡처된 모든 스택 트레이스에 영향을 미칩니다. +`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} @@ -138,7 +162,7 @@ toJson(showCause: boolean): Record; `boolean` = `false` -JSON 응답에 오류의 원인(cause)을 포함할지 여부입니다. +JSON 응답에 오류의 원인을 포함할지 여부입니다. 기본값은 `false`입니다. #### 반환값 {#returns} @@ -157,47 +181,7 @@ JSON 응답에 오류의 원인(cause)을 포함할지 여부입니다. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -`targetObject`에 `.stack` 프로퍼티를 생성하며, -접근 시 `Error.captureStackTrace()`가 호출된 코드 위치를 나타내는 문자열을 반환합니다. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // `new Error().stack`과 유사 -``` - -트레이스의 첫 번째 줄은 -`${myObject.name}: ${myObject.message}`로 시작합니다. - -선택적 `constructorOpt` 인자는 함수입니다. -제공되면, `constructorOpt`를 포함하여 그 위의 모든 프레임이 -생성된 스택 트레이스에서 생략됩니다. - -`constructorOpt` 인자는 오류 생성의 구현 세부 정보를 사용자로부터 숨길 때 유용합니다. 예시: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // 스택 트레이스를 두 번 계산하지 않도록 스택 트레이스 없이 오류 생성 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // b 함수 위에서 스택 트레이스 캡처 - Error.captureStackTrace(error, b); // c, b 함수 모두 스택 트레이스에 포함되지 않음 - throw error; -} - -a(); -``` +대상 객체에 .stack 프로퍼티를 생성합니다 #### 매개변수 {#parameters} @@ -216,33 +200,3 @@ a(); #### 상속됨 {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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) 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 index 371b332..8f4103e 100644 --- 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 @@ -6,7 +6,7 @@ sidebar_label: MCPAuthError 모든 mcp-auth 오류의 기본 클래스입니다. -MCP 인증 (Authentication) 및 인가 (Authorization)와 관련된 오류를 표준화된 방식으로 처리할 수 있도록 합니다. +MCP 인증 (Authentication) 및 인가 (Authorization)와 관련된 오류를 표준화된 방식으로 처리할 수 있도록 제공합니다. ## 상속 {#extends} @@ -33,7 +33,7 @@ new MCPAuthError(code: string, message: string): MCPAuthError; `string` -스네이크 케이스(snake_case) 형식의 오류 코드입니다. +스네이크 케이스 형식의 오류 코드입니다. ##### message {#message} @@ -51,7 +51,7 @@ new MCPAuthError(code: string, message: string): MCPAuthError; Error.constructor ``` -## 프로퍼티 {#properties} +## 속성 {#properties} ### cause? {#cause} @@ -73,7 +73,7 @@ Error.cause readonly code: string; ``` -스네이크 케이스(snake_case) 형식의 오류 코드입니다. +스네이크 케이스 형식의 오류 코드입니다. *** @@ -119,17 +119,45 @@ Error.stack *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` 프로퍼티는 스택 트레이스( `new Error().stack` 또는 `Error.captureStackTrace(obj)`로 생성됨 )에서 수집되는 스택 프레임의 개수를 지정합니다. +스택 트레이스 포맷팅을 위한 선택적 오버라이드 + +#### 매개변수 {#parameters} + +##### err {#err} -기본값은 `10`이지만, 유효한 JavaScript 숫자로 설정할 수 있습니다. 값이 변경된 이후에 캡처되는 모든 스택 트레이스에 영향을 미칩니다. +`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} @@ -168,45 +196,7 @@ JSON 응답에 오류의 원인(cause)을 포함할지 여부입니다. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -`targetObject`에 `.stack` 프로퍼티를 생성하며, 접근 시 -`Error.captureStackTrace()`가 호출된 코드 위치를 나타내는 문자열을 반환합니다. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // `new Error().stack`과 유사 -``` - -트레이스의 첫 번째 줄은 -`${myObject.name}: ${myObject.message}`로 시작합니다. - -선택적 `constructorOpt` 인자는 함수입니다. 제공되면, `constructorOpt`를 포함하여 그 위의 모든 프레임이 생성된 스택 트레이스에서 생략됩니다. - -`constructorOpt` 인자는 오류 생성의 구현 세부 정보를 사용자에게 숨기고 싶을 때 유용합니다. 예시: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // 스택 트레이스를 두 번 계산하지 않기 위해 스택 트레이스 없는 오류 생성 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 함수 b 위에서 스택 트레이스 캡처 - Error.captureStackTrace(error, b); // 함수 c와 b는 스택 트레이스에 포함되지 않음 - throw error; -} - -a(); -``` +대상 객체에 .stack 속성을 생성합니다 #### 매개변수 {#parameters} @@ -227,35 +217,3 @@ a(); ```ts Error.captureStackTrace ``` - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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 -``` 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 index 38e3730..a26a1af 100644 --- 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 @@ -100,17 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` 프로퍼티는 스택 트레이스( `new Error().stack` 또는 `Error.captureStackTrace(obj)`로 생성됨 )에서 수집되는 스택 프레임의 개수를 지정합니다. +스택 트레이스 포맷팅을 위한 선택적 오버라이드 + +#### 매개변수 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -기본값은 `10`이지만, 유효한 JavaScript 숫자로 설정할 수 있습니다. 값이 변경된 이후에 캡처된 모든 스택 트레이스에 영향을 미칩니다. +`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} @@ -132,7 +158,7 @@ toJson(showCause: boolean): Record; `boolean` = `false` -오류의 원인(cause)을 JSON 응답에 포함할지 여부입니다. +JSON 응답에 오류의 원인을 포함할지 여부입니다. 기본값은 `false`입니다. #### 반환값 {#returns} @@ -151,45 +177,7 @@ toJson(showCause: boolean): Record; static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -`targetObject`에 `.stack` 프로퍼티를 생성하며, 접근 시 -`Error.captureStackTrace()`가 호출된 코드 위치를 나타내는 문자열을 반환합니다. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // `new Error().stack`과 유사 -``` - -트레이스의 첫 번째 줄은 -`${myObject.name}: ${myObject.message}`로 시작합니다. - -선택적인 `constructorOpt` 인자는 함수입니다. 제공되면, `constructorOpt`를 포함하여 그 위의 모든 프레임이 생성된 스택 트레이스에서 생략됩니다. - -`constructorOpt` 인자는 오류 생성의 구현 세부 정보를 사용자로부터 숨길 때 유용합니다. 예시: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // 스택 트레이스를 두 번 계산하지 않기 위해 스택 트레이스 없는 오류 생성 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 함수 b 위에서 스택 트레이스 캡처 - Error.captureStackTrace(error, b); // 함수 c와 b는 스택 트레이스에 포함되지 않음 - throw error; -} - -a(); -``` +대상 객체에 .stack 프로퍼티를 생성합니다 #### 매개변수 {#parameters} @@ -208,33 +196,3 @@ a(); #### 상속됨 {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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) 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 index 0587849..3005a3f 100644 --- 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 @@ -8,7 +8,7 @@ sidebar_label: createVerifyJwt function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; ``` -제공된 키 조회 함수와 옵션을 사용하여 JWT 액세스 토큰 (Access token)을 검증하는 함수를 생성합니다. +제공된 키 검색 함수와 옵션을 사용하여 JWT 액세스 토큰 (Access token)을 검증하는 함수를 생성합니다. ## 매개변수 {#parameters} @@ -16,17 +16,17 @@ function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): V `JWTVerifyGetKey` -JWT를 검증하는 데 사용되는 키를 조회하는 함수입니다. +JWT를 검증하는 데 사용되는 키를 검색하는 함수입니다. **참고** -키 조회 함수의 타입 정의는 JWTVerifyGetKey를 참고하세요. +키 검색 함수의 타입 정의는 JWTVerifyGetKey를 참고하세요. ### options? {#options} `JWTVerifyOptions` -선택적으로 사용할 수 있는 JWT 검증 옵션입니다. +선택적 JWT 검증 옵션입니다. **참고** @@ -36,7 +36,7 @@ JWT를 검증하는 데 사용되는 키를 조회하는 함수입니다. [`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) -JWT 액세스 토큰 (Access token)을 검증하고, 토큰이 유효한 경우 AuthInfo 객체를 반환하는 함수입니다. 이 함수는 JWT의 페이로드에 `iss`, `client_id`, `sub` 필드가 반드시 포함되어야 하며, 선택적으로 `scope` 또는 `scopes` 필드를 포함할 수 있습니다. JWT 검증은 내부적으로 `jose` 라이브러리를 사용하여 수행됩니다. +JWT 액세스 토큰 (Access token)을 검증하고, 토큰이 유효할 경우 AuthInfo 객체를 반환하는 함수입니다. 이 함수는 JWT의 페이로드에 `iss`, `client_id`, `sub` 필드가 반드시 포함되어야 하며, 선택적으로 `scope` 또는 `scopes` 필드를 포함할 수 있습니다. JWT 검증은 내부적으로 `jose` 라이브러리를 사용하여 수행됩니다. ## 참고 {#see} 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 index 5196a42..702ec1c 100644 --- 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 @@ -5,7 +5,7 @@ sidebar_label: fetchServerConfig # 함수: fetchServerConfig() ```ts -function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; +function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; ``` 발급자 (Issuer)와 인가 서버 유형에 따라 서버 구성을 가져옵니다. @@ -24,37 +24,37 @@ function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promis `ServerMetadataConfig` -서버 유형 및 선택적 트랜스파일 함수가 포함된 구성 객체입니다. +서버 유형과 선택적 트랜스파일 함수가 포함된 구성 객체입니다. ## 반환값 {#returns} -`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> +`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) 를 참조하세요. + - 내부 구현에 대해서는 [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` 에서 메타데이터를 가져옵니다. +// 이는 `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` 에서 메타데이터를 가져옵니다. +// 이는 `https://auth.logto.io/oidc/.well-known/openid-configuration`에서 메타데이터를 가져옵니다. const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); ``` -## 예외 발생 {#throws} +## 예외 {#throws} 가져오기 작업이 실패할 경우 예외가 발생합니다. -## 예외 발생 {#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 index 5d27e6a..6cc3041 100644 --- 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 @@ -5,12 +5,12 @@ sidebar_label: fetchServerConfigByWellKnownUrl # 함수: fetchServerConfigByWellKnownUrl() ```ts -function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; +function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; ``` -제공된 well-known URL에서 서버 구성을 가져오고 MCP 명세에 따라 유효성을 검사합니다. +제공된 well-known URL에서 서버 구성을 가져오고 MCP 사양에 따라 유효성을 검사합니다. -서버 메타데이터가 예상된 스키마와 일치하지 않지만, 호환된다고 확신하는 경우, `transpileData` 함수를 정의하여 메타데이터를 예상 형식으로 변환할 수 있습니다. +서버 메타데이터가 예상된 스키마와 일치하지 않지만 호환된다고 확신하는 경우, `transpileData` 함수를 정의하여 메타데이터를 예상 형식으로 변환할 수 있습니다. ## 매개변수 {#parameters} @@ -28,14 +28,14 @@ function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: Ser ## 반환값 {#returns} -`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> +`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -서버 구성으로 resolve되는 promise입니다. +가져온 메타데이터와 함께 정적 서버 구성으로 해결되는 프로미스입니다. ## 예외 발생 {#throws} -가져오기(fetch) 작업이 실패할 경우 예외가 발생합니다. +가져오기 작업이 실패할 경우 예외가 발생합니다. ## 예외 발생 {#throws} -서버 메타데이터가 유효하지 않거나 MCP 명세와 일치하지 않을 경우 예외가 발생합니다. +서버 메타데이터가 유효하지 않거나 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 new file mode 100644 index 0000000..e0485f1 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md @@ -0,0 +1,24 @@ +--- +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 index f7a3b50..21f3e96 100644 --- 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 @@ -8,15 +8,15 @@ sidebar_label: handleBearerAuth function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; ``` -Express 애플리케이션에서 Bearer 인증 (Authentication)을 처리하기 위한 미들웨어 함수를 생성합니다. +Express 애플리케이션에서 Bearer 인증 (Authentication)을 처리하는 미들웨어 함수를 생성합니다. 이 미들웨어는 `Authorization` 헤더에서 Bearer 토큰을 추출하고, 제공된 `verifyAccessToken` 함수를 사용하여 토큰을 검증하며, 발급자 (Issuer), 대상 (Audience), 그리고 필요한 스코프 (Scope)를 확인합니다. -- 토큰이 유효하면 인증 (Authentication) 정보를 `request.auth` 속성에 추가합니다. - 유효하지 않은 경우 적절한 오류 메시지로 응답합니다. +- 토큰이 유효한 경우, 인증 (Authentication) 정보를 `request.auth` 속성에 추가합니다. + 유효하지 않은 경우, 적절한 오류 메시지로 응답합니다. - 액세스 토큰 (Access token) 검증에 실패하면 401 Unauthorized 오류로 응답합니다. - 토큰에 필요한 스코프 (Scope)가 없으면 403 Forbidden 오류로 응답합니다. -- 인증 (Authentication) 과정에서 예기치 않은 오류가 발생하면, 미들웨어가 해당 오류를 다시 throw 합니다. +- 인증 (Authentication) 과정 중 예기치 않은 오류가 발생하면, 미들웨어가 해당 오류를 다시 throw 합니다. **참고:** `request.auth` 객체는 `@modelcontextprotocol/sdk` 모듈에 정의된 표준 AuthInfo 인터페이스보다 확장된 필드를 포함합니다. 자세한 내용은 이 파일의 확장 인터페이스를 참고하세요. @@ -26,7 +26,7 @@ Express 애플리케이션에서 Bearer 인증 (Authentication)을 처리하기 [`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md) -Bearer 인증 (Authentication) 핸들러를 위한 구성입니다. +Bearer 인증 (Authentication) 핸들러를 위한 설정입니다. ## 반환값 {#returns} @@ -36,4 +36,4 @@ Bearer 인증 (Authentication)을 처리하는 Express용 미들웨어 함수입 ## 참고 {#see} -구성 옵션에 대해서는 [BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md)를 참고하세요. +설정 옵션에 대해서는 [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 index bf640e9..e449ca4 100644 --- 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 @@ -5,43 +5,13 @@ sidebar_label: AuthServerConfig # 타입 별칭: AuthServerConfig ```ts -type AuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; - type: AuthServerType; -}; +type AuthServerConfig = + | ResolvedAuthServerConfig + | AuthServerDiscoveryConfig; ``` -MCP 서버와 통합된 원격 인가 서버 (Authorization Server)에 대한 구성입니다. +MCP 서버와 통합된 원격 인가 서버 (Authorization server)의 구성입니다. -## 속성 {#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 인가 서버 메타데이터 (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 +다음 중 하나일 수 있습니다: +- **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/AuthServerConfigWarning.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md index 3870f76..49e9a0a 100644 --- 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 @@ -11,7 +11,7 @@ type AuthServerConfigWarning = { }; ``` -인가 서버 메타데이터 검증 중에 발생하는 경고를 나타냅니다. +인가 서버 메타데이터를 검증하는 동안 발생하는 경고를 나타냅니다. ## 속성 {#properties} 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 new file mode 100644 index 0000000..97bf4c9 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md @@ -0,0 +1,57 @@ +--- +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/AuthorizationServerMetadata.md b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md index d951130..4daf7c2 100644 --- 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 @@ -5,223 +5,10 @@ sidebar_label: AuthorizationServerMetadata # 타입 별칭: AuthorizationServerMetadata ```ts -type AuthorizationServerMetadata = { - authorization_endpoint: string; - code_challenge_methods_supported?: string[]; - grant_types_supported?: string[]; - introspection_endpoint?: string; - introspection_endpoint_auth_methods_supported?: string[]; - introspection_endpoint_auth_signing_alg_values_supported?: string[]; - issuer: string; - jwks_uri?: string; - op_policy_uri?: string; - op_tos_uri?: string; - registration_endpoint?: string; - response_modes_supported?: string[]; - response_types_supported: string[]; - revocation_endpoint?: string; - revocation_endpoint_auth_methods_supported?: string[]; - revocation_endpoint_auth_signing_alg_values_supported?: string[]; - scopes_supported?: string[]; - service_documentation?: string; - token_endpoint: string; - token_endpoint_auth_methods_supported?: string[]; - token_endpoint_auth_signing_alg_values_supported?: string[]; - ui_locales_supported?: string[]; - userinfo_endpoint?: string; -}; +type AuthorizationServerMetadata = z.infer; ``` -RFC 8414에서 정의된 OAuth 2.0 인가 서버 메타데이터 스키마입니다. - -## 타입 선언 {#type-declaration} - -### authorization\_endpoint {#authorization-endpoint} - -```ts -authorization_endpoint: string; -``` - -인가 서버의 인가 엔드포인트 URL [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. -인가 엔드포인트를 사용하는 grant type이 지원되지 않는 경우를 제외하고 필수입니다. - -#### 참고 {#see} - -https://rfc-editor.org/rfc/rfc6749#section-3.1 - -### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} - -```ts -optional code_challenge_methods_supported: string[]; -``` - -이 인가 서버가 지원하는 Proof Key for Code Exchange (PKCE) -[[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] 코드 챌린지 방식의 목록을 포함하는 JSON 배열입니다. - -### grant\_types\_supported? {#grant-types-supported} - -```ts -optional grant_types_supported: string[]; -``` - -이 인가 서버가 지원하는 OAuth 2.0 grant type 값의 목록을 포함하는 JSON 배열입니다. 배열 값은 "OAuth 2.0 Dynamic Client Registration Protocol" [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]에서 정의된 `grant_types` 파라미터와 동일하게 사용됩니다. -생략된 경우 기본값은 `["authorization_code", "implicit"]`입니다. - -### introspection\_endpoint? {#introspection-endpoint} - -```ts -optional introspection_endpoint: string; -``` - -인가 서버의 OAuth 2.0 인트로스펙션 엔드포인트 URL -[[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]. - -### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} - -```ts -optional introspection_endpoint_auth_methods_supported: string[]; -``` - -### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} - -```ts -optional introspection_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### issuer {#issuer} - -```ts -issuer: string; -``` - -인가 서버의 발급자 (Issuer) 식별자입니다. `https` 스킴을 사용하고 쿼리 또는 프래그먼트 컴포넌트가 없는 URL입니다. - -### jwks\_uri? {#jwks-uri} - -```ts -optional jwks_uri: string; -``` - -인가 서버의 JWK Set [[JWK](https://www.rfc-editor.org/rfc/rfc8414.html#ref-JWK)] -문서의 URL입니다. 참조된 문서는 인가 서버의 서명을 검증하기 위해 클라이언트가 사용하는 서명 키를 포함합니다. 이 URL은 반드시 `https` 스킴을 사용해야 합니다. - -### op\_policy\_uri? {#op-policy-uri} - -```ts -optional op_policy_uri: string; -``` - -### op\_tos\_uri? {#op-tos-uri} - -```ts -optional op_tos_uri: string; -``` - -### registration\_endpoint? {#registration-endpoint} - -```ts -optional registration_endpoint: string; -``` - -인가 서버의 OAuth 2.0 동적 클라이언트 등록 엔드포인트 URL -[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. - -### response\_modes\_supported? {#response-modes-supported} - -```ts -optional response_modes_supported: string[]; -``` - -이 인가 서버가 지원하는 OAuth 2.0 `response_mode` 값의 목록을 포함하는 JSON 배열입니다. "OAuth 2.0 Multiple Response Type Encoding Practices" -[[OAuth.Responses](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Responses)]에서 명시되어 있습니다. - -생략된 경우 기본값은 `["query", "fragment"]`입니다. `"form_post"` 응답 모드는 "OAuth 2.0 Form Post Response Mode" -[[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)]에서 정의되어 있습니다. - -### response\_types\_supported {#response-types-supported} - -```ts -response_types_supported: string[]; -``` - -이 인가 서버가 지원하는 OAuth 2.0 `response_type` 값의 목록을 포함하는 JSON 배열입니다. 배열 값은 "OAuth 2.0 Dynamic Client Registration Protocol" -[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]에서 정의된 `response_types` 파라미터와 동일하게 사용됩니다. - -### revocation\_endpoint? {#revocation-endpoint} - -```ts -optional revocation_endpoint: string; -``` - -인가 서버의 OAuth 2.0 토큰 폐기 엔드포인트 URL -[[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]. - -### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} - -```ts -optional revocation_endpoint_auth_methods_supported: string[]; -``` - -### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} - -```ts -optional revocation_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### scopes\_supported? {#scopes-supported} - -```ts -optional scopes_supported: string[]; -``` - -이 인가 서버가 지원하는 OAuth 2.0 `scope` 값의 목록을 포함하는 JSON 배열입니다. -[[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] - -### service\_documentation? {#service-documentation} - -```ts -optional service_documentation: string; -``` - -### token\_endpoint {#token-endpoint} - -```ts -token_endpoint: string; -``` - -인가 서버의 토큰 엔드포인트 URL [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. -암시적 grant type만 지원하는 경우를 제외하고 필수입니다. - -#### 참고 {#see} - -https://rfc-editor.org/rfc/rfc6749#section-3.2 - -### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} - -```ts -optional token_endpoint_auth_methods_supported: string[]; -``` - -### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} - -```ts -optional token_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### ui\_locales\_supported? {#ui-locales-supported} - -```ts -optional ui_locales_supported: string[]; -``` - -### userinfo\_endpoint? {#userinfo-endpoint} - -```ts -optional userinfo_endpoint: string; -``` - -OpenID Connect [userinfo endpoint](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) 의 URL입니다. -이 엔드포인트는 인증된 사용자에 대한 정보를 가져오는 데 사용됩니다. +RFC 8414에 정의된 OAuth 2.0 인가 서버 메타데이터 (Authorization Server Metadata) 스키마입니다. ## 참고 {#see} 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 index da25b16..5a247ab 100644 --- 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 @@ -24,11 +24,11 @@ type BearerAuthConfig = { optional audience: string; ``` -액세스 토큰 (Access token)의 예상 대상 (audience) (`aud` 클레임 (Claim)). 일반적으로 토큰이 의도된 리소스 서버 (API)를 의미합니다. 제공하지 않으면 대상 (Audience) 확인이 건너뜁니다. +액세스 토큰 (Access token)의 예상 대상 (Audience) (`aud` 클레임 (Claim)). 일반적으로 토큰이 의도된 리소스 서버 (API)입니다. 제공하지 않으면 대상 (Audience) 확인이 건너뜁니다. -**참고:** 인가 (Authorization) 서버가 리소스 지표 (Resource Indicators, RFC 8707)를 지원하지 않는 경우, 대상 (Audience)이 관련 없을 수 있으므로 이 필드는 생략할 수 있습니다. +**참고:** 인가 서버가 리소스 지표 (Resource Indicator) (RFC 8707)를 지원하지 않는 경우, 대상 (Audience)이 관련 없을 수 있으므로 이 필드를 생략할 수 있습니다. -#### 참고 {#see} +#### 참고(See) {#see} https://datatracker.ietf.org/doc/html/rfc8707 @@ -42,13 +42,13 @@ issuer: | ValidateIssuerFunction; ``` -유효한 발급자 (Issuer)를 나타내는 문자열 또는 액세스 토큰의 발급자를 검증하는 함수입니다. +유효한 발급자 (Issuer)를 나타내는 문자열 또는 액세스 토큰 (Access token)의 발급자 (Issuer)를 검증하는 함수. -문자열이 제공되면, 직접 비교를 위해 예상 발급자 (Issuer) 값으로 사용됩니다. +문자열이 제공되면, 예상 발급자 (Issuer) 값으로 직접 비교에 사용됩니다. 함수가 제공되면, [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md)의 규칙에 따라 발급자 (Issuer)를 검증해야 합니다. -#### 참고 {#see} +#### 참고(See) {#see} [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md)에서 검증 함수에 대한 자세한 내용을 확인하세요. @@ -60,9 +60,9 @@ issuer: optional requiredScopes: string[]; ``` -액세스 토큰 (Access token)이 반드시 가져야 하는 필수 스코프 (Scope) 배열입니다. 토큰에 이 모든 스코프 (Scope)가 포함되어 있지 않으면 오류가 발생합니다. +액세스 토큰 (Access token)이 반드시 가져야 하는 필수 스코프 (Scope)들의 배열. 토큰에 이 모든 스코프 (Scope)가 포함되어 있지 않으면 오류가 발생합니다. -**참고:** 핸들러는 토큰의 `scope` 클레임 (Claim)을 확인합니다. 이 값은 인가 (Authorization) 서버의 구현에 따라 공백으로 구분된 문자열이거나 문자열 배열일 수 있습니다. `scope` 클레임 (Claim)이 없으면, 핸들러는 `scopes` 클레임 (Claim)이 있는지 확인합니다. +**참고:** 핸들러는 토큰의 `scope` 클레임 (Claim)을 확인합니다. 이 값은 인가 서버의 구현에 따라 공백으로 구분된 문자열이거나 문자열 배열일 수 있습니다. `scope` 클레임 (Claim)이 없으면, 핸들러는 `scopes` 클레임 (Claim)이 있는지 확인합니다. *** @@ -72,7 +72,7 @@ optional requiredScopes: string[]; optional resource: string; ``` -보호된 리소스의 식별자입니다. 제공된 경우, 핸들러는 이 리소스에 대해 구성된 인가 (Authorization) 서버를 사용하여 받은 토큰을 검증합니다. `protectedResources` 구성과 함께 핸들러를 사용할 때 필수입니다. +보호된 리소스의 식별자. 제공된 경우, 핸들러는 이 리소스에 대해 구성된 인가 서버를 사용하여 받은 토큰을 검증합니다. `protectedResources` 구성과 함께 핸들러를 사용할 때 필수입니다. *** @@ -82,9 +82,9 @@ optional resource: string; optional showErrorDetails: boolean; ``` -응답에 상세 오류 정보를 표시할지 여부입니다. 개발 중 디버깅에 유용하지만, 민감한 정보 노출을 방지하기 위해 운영 환경에서는 비활성화해야 합니다. +응답에 상세 오류 정보를 표시할지 여부. 개발 중 디버깅에 유용하지만, 민감한 정보 노출을 방지하기 위해 운영 환경에서는 비활성화해야 합니다. -#### 기본값 {#default} +#### 기본값(Default) {#default} ```ts false @@ -98,10 +98,10 @@ false verifyAccessToken: VerifyAccessTokenFunction; ``` -액세스 토큰 (Access token)을 검증하는 함수 타입입니다. +액세스 토큰 (Access token) 검증을 위한 함수 타입. -이 함수는 토큰이 유효하지 않은 경우 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md)를 발생시키거나, 토큰이 유효한 경우 AuthInfo 객체를 반환해야 합니다. +이 함수는 토큰이 유효하지 않은 경우 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md)를 throw 하거나, 토큰이 유효한 경우 AuthInfo 객체를 반환해야 합니다. -#### 참고 {#see} +#### 참고(See) {#see} [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md)에서 자세한 내용을 확인하세요. 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 index 7af1255..880cb1a 100644 --- 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 @@ -5,175 +5,11 @@ sidebar_label: CamelCaseAuthorizationServerMetadata # 타입 별칭: CamelCaseAuthorizationServerMetadata ```ts -type CamelCaseAuthorizationServerMetadata = { - authorizationEndpoint: string; - codeChallengeMethodsSupported?: string[]; - grantTypesSupported?: string[]; - introspectionEndpoint?: string; - introspectionEndpointAuthMethodsSupported?: string[]; - introspectionEndpointAuthSigningAlgValuesSupported?: string[]; - issuer: string; - jwksUri?: string; - opPolicyUri?: string; - opTosUri?: string; - registrationEndpoint?: string; - responseModesSupported?: string[]; - responseTypesSupported: string[]; - revocationEndpoint?: string; - revocationEndpointAuthMethodsSupported?: string[]; - revocationEndpointAuthSigningAlgValuesSupported?: string[]; - scopesSupported?: string[]; - serviceDocumentation?: string; - tokenEndpoint: string; - tokenEndpointAuthMethodsSupported?: string[]; - tokenEndpointAuthSigningAlgValuesSupported?: string[]; - uiLocalesSupported?: string[]; - userinfoEndpoint?: string; -}; +type CamelCaseAuthorizationServerMetadata = z.infer; ``` -OAuth 2.0 인가 서버 메타데이터 타입의 camelCase 버전입니다. - -## 타입 선언 {#type-declaration} - -### authorizationEndpoint {#authorizationendpoint} - -```ts -authorizationEndpoint: string; -``` - -### codeChallengeMethodsSupported? {#codechallengemethodssupported} - -```ts -optional codeChallengeMethodsSupported: string[]; -``` - -### grantTypesSupported? {#granttypessupported} - -```ts -optional grantTypesSupported: string[]; -``` - -### introspectionEndpoint? {#introspectionendpoint} - -```ts -optional introspectionEndpoint: string; -``` - -### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} - -```ts -optional introspectionEndpointAuthMethodsSupported: string[]; -``` - -### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} - -```ts -optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### issuer {#issuer} - -```ts -issuer: string; -``` - -### jwksUri? {#jwksuri} - -```ts -optional jwksUri: string; -``` - -### opPolicyUri? {#oppolicyuri} - -```ts -optional opPolicyUri: string; -``` - -### opTosUri? {#optosuri} - -```ts -optional opTosUri: string; -``` - -### registrationEndpoint? {#registrationendpoint} - -```ts -optional registrationEndpoint: string; -``` - -### responseModesSupported? {#responsemodessupported} - -```ts -optional responseModesSupported: string[]; -``` - -### responseTypesSupported {#responsetypessupported} - -```ts -responseTypesSupported: string[]; -``` - -### revocationEndpoint? {#revocationendpoint} - -```ts -optional revocationEndpoint: string; -``` - -### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} - -```ts -optional revocationEndpointAuthMethodsSupported: string[]; -``` - -### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} - -```ts -optional revocationEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### scopesSupported? {#scopessupported} - -```ts -optional scopesSupported: string[]; -``` - -### serviceDocumentation? {#servicedocumentation} - -```ts -optional serviceDocumentation: string; -``` - -### tokenEndpoint {#tokenendpoint} - -```ts -tokenEndpoint: string; -``` - -### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} - -```ts -optional tokenEndpointAuthMethodsSupported: string[]; -``` - -### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} - -```ts -optional tokenEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### uiLocalesSupported? {#uilocalessupported} - -```ts -optional uiLocalesSupported: string[]; -``` - -### userinfoEndpoint? {#userinfoendpoint} - -```ts -optional userinfoEndpoint: string; -``` +OAuth 2.0 인가 서버 메타데이터 (Authorization Server Metadata) 타입의 camelCase 버전입니다. ## 참고 {#see} -원본 타입 및 필드 정보는 [AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) 를 참고하세요. +원본 타입 및 필드 정보는 [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 index e6929c8..23a94c8 100644 --- 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 @@ -5,118 +5,10 @@ sidebar_label: CamelCaseProtectedResourceMetadata # 타입 별칭: CamelCaseProtectedResourceMetadata ```ts -type CamelCaseProtectedResourceMetadata = { - authorizationDetailsTypesSupported?: string[]; - authorizationServers?: string[]; - bearerMethodsSupported?: string[]; - dpopBoundAccessTokensRequired?: boolean; - dpopSigningAlgValuesSupported?: string[]; - jwksUri?: string; - resource: string; - resourceDocumentation?: string; - resourceName?: string; - resourcePolicyUri?: string; - resourceSigningAlgValuesSupported?: string[]; - resourceTosUri?: string; - scopesSupported?: string[]; - signedMetadata?: string; - tlsClientCertificateBoundAccessTokens?: boolean; -}; +type CamelCaseProtectedResourceMetadata = z.infer; ``` -OAuth 2.0 불투명 토큰 (Opaque token) 보호 리소스 메타데이터 타입의 camelCase 버전입니다. - -## 타입 선언 {#type-declaration} - -### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} - -```ts -optional authorizationDetailsTypesSupported: string[]; -``` - -### authorizationServers? {#authorizationservers} - -```ts -optional authorizationServers: string[]; -``` - -### bearerMethodsSupported? {#bearermethodssupported} - -```ts -optional bearerMethodsSupported: string[]; -``` - -### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} - -```ts -optional dpopBoundAccessTokensRequired: boolean; -``` - -### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} - -```ts -optional dpopSigningAlgValuesSupported: string[]; -``` - -### jwksUri? {#jwksuri} - -```ts -optional jwksUri: string; -``` - -### resource {#resource} - -```ts -resource: string; -``` - -### resourceDocumentation? {#resourcedocumentation} - -```ts -optional resourceDocumentation: string; -``` - -### resourceName? {#resourcename} - -```ts -optional resourceName: string; -``` - -### resourcePolicyUri? {#resourcepolicyuri} - -```ts -optional resourcePolicyUri: string; -``` - -### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} - -```ts -optional resourceSigningAlgValuesSupported: string[]; -``` - -### resourceTosUri? {#resourcetosuri} - -```ts -optional resourceTosUri: string; -``` - -### scopesSupported? {#scopessupported} - -```ts -optional scopesSupported: string[]; -``` - -### signedMetadata? {#signedmetadata} - -```ts -optional signedMetadata: string; -``` - -### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} - -```ts -optional tlsClientCertificateBoundAccessTokens: boolean; -``` +OAuth 2.0 보호된 리소스 메타데이터(Protected Resource Metadata) 타입의 camelCase 버전입니다. ## 참고 {#see} 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 index a1407ff..7166e5b 100644 --- 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 @@ -2,7 +2,7 @@ sidebar_label: MCPAuthBearerAuthErrorDetails --- -# 타입 별칭: MCPAuthBearerAuthErrorDetails +# 타입 별칭: MCPAuthBearerAuthErrorDetails (Type Alias: MCPAuthBearerAuthErrorDetails) ```ts type MCPAuthBearerAuthErrorDetails = { @@ -14,7 +14,7 @@ type MCPAuthBearerAuthErrorDetails = { }; ``` -## 속성 {#properties} +## 속성(Properties) {#properties} ### actual? {#actual} 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 index e55c72a..afbb627 100644 --- 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 @@ -5,146 +5,7 @@ sidebar_label: ProtectedResourceMetadata # 타입 별칭: ProtectedResourceMetadata ```ts -type ProtectedResourceMetadata = { - authorization_details_types_supported?: string[]; - authorization_servers?: string[]; - bearer_methods_supported?: string[]; - dpop_bound_access_tokens_required?: boolean; - dpop_signing_alg_values_supported?: string[]; - jwks_uri?: string; - resource: string; - resource_documentation?: string; - resource_name?: string; - resource_policy_uri?: string; - resource_signing_alg_values_supported?: string[]; - resource_tos_uri?: string; - scopes_supported?: string[]; - signed_metadata?: string; - tls_client_certificate_bound_access_tokens?: boolean; -}; +type ProtectedResourceMetadata = z.infer; ``` -OAuth 2.0 보호된 리소스 메타데이터 스키마입니다. - -## 타입 선언 {#type-declaration} - -### authorization\_details\_types\_supported? {#authorization-details-types-supported} - -```ts -optional authorization_details_types_supported: string[]; -``` - -authorization_details 요청 파라미터를 사용할 때 지원되는 인가 세부 정보 타입 값입니다. - -### authorization\_servers? {#authorization-servers} - -```ts -optional authorization_servers: string[]; -``` - -이 보호된 리소스와 함께 사용할 수 있는 OAuth 인가 서버 발급자 식별자 목록입니다. - -### bearer\_methods\_supported? {#bearer-methods-supported} - -```ts -optional bearer_methods_supported: string[]; -``` - -OAuth 2.0 베어러 토큰을 전송할 때 지원되는 방법입니다. 값: ["header", "body", "query"]. - -### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} - -```ts -optional dpop_bound_access_tokens_required: boolean; -``` - -이 보호된 리소스가 항상 DPoP-바인딩 액세스 토큰 (액세스 토큰)을 요구하는지 여부입니다. - -### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} - -```ts -optional dpop_signing_alg_values_supported: string[]; -``` - -DPoP 증명 JWT (JWT)를 검증할 때 지원되는 JWS 알고리즘입니다. - -### jwks\_uri? {#jwks-uri} - -```ts -optional jwks_uri: string; -``` - -보호된 리소스의 JSON Web Key (JWK) 세트 문서의 URL입니다. 이 문서에는 이 보호된 리소스가 반환하는 응답 또는 데이터의 디지털 서명을 검증하는 데 사용할 수 있는 공개 키가 포함되어 있습니다. -이는 토큰 검증에 사용되는 인가 서버의 jwks_uri와 다릅니다. 보호된 리소스가 응답에 서명하는 경우, 클라이언트는 이 공개 키를 가져와 수신 데이터의 진위성과 무결성을 검증할 수 있습니다. - -### resource {#resource} - -```ts -resource: string; -``` - -보호된 리소스의 리소스 식별자입니다. - -### resource\_documentation? {#resource-documentation} - -```ts -optional resource_documentation: string; -``` - -보호된 리소스를 사용하는 방법에 대한 개발자 문서가 포함된 URL입니다. - -### resource\_name? {#resource-name} - -```ts -optional resource_name: string; -``` - -최종 사용자에게 표시할 보호된 리소스의 사람이 읽을 수 있는 이름입니다. - -### resource\_policy\_uri? {#resource-policy-uri} - -```ts -optional resource_policy_uri: string; -``` - -보호된 리소스의 데이터 사용 요구 사항에 대한 정보가 포함된 URL입니다. - -### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} - -```ts -optional resource_signing_alg_values_supported: string[]; -``` - -리소스 응답에 서명할 때 보호된 리소스가 지원하는 JWS 서명 알고리즘입니다. - -### resource\_tos\_uri? {#resource-tos-uri} - -```ts -optional resource_tos_uri: string; -``` - -보호된 리소스의 서비스 약관이 포함된 URL입니다. - -### scopes\_supported? {#scopes-supported} - -```ts -optional scopes_supported: string[]; -``` - -이 보호된 리소스에 접근하기 위한 인가 요청에서 사용되는 스코프 (Scope) 값 목록입니다. - -### signed\_metadata? {#signed-metadata} - -```ts -optional signed_metadata: string; -``` - -클레임으로 메타데이터 파라미터를 포함하는 서명된 JWT (JWT)입니다. JWT는 JWS를 사용하여 서명되어야 하며 'iss' 클레임을 포함해야 합니다. 이 필드는 메타데이터 자체의 진위성을 암호학적으로 검증할 수 있는 방법을 제공합니다. 서명은 jwks_uri 엔드포인트에서 제공되는 공개 키를 사용하여 검증할 수 있습니다. 이 값이 존재할 경우, 이 서명된 메타데이터의 값이 이 메타데이터 문서의 해당 일반 JSON 값보다 우선합니다. 이는 리소스 메타데이터의 변조를 방지하는 데 도움이 됩니다. - -### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} - -```ts -optional tls_client_certificate_bound_access_tokens: boolean; -``` - -보호된 리소스가 상호-TLS 클라이언트 인증서-바인딩 액세스 토큰 (액세스 토큰)을 지원하는지 여부입니다. +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 new file mode 100644 index 0000000..0ba2158 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md @@ -0,0 +1,49 @@ +--- +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 index f5765ea..44b38dd 100644 --- 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 @@ -20,4 +20,4 @@ MCP 서버를 리소스 서버 모드로 설정하는 구성입니다. protectedResources: ResourceServerConfig | ResourceServerConfig[]; ``` -단일 리소스 서버 구성 또는 그 배열입니다. \ No newline at end of file +단일 리소스 서버 구성 또는 그 배열입니다. 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 index 9eb9e2e..8d73885 100644 --- 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 @@ -10,7 +10,7 @@ type ValidateIssuerFunction = (tokenIssuer: string) => void; 액세스 토큰 (Access token)의 발급자 (Issuer)를 검증하는 함수 타입입니다. -이 함수는 발급자가 유효하지 않은 경우 코드가 'invalid_issuer'인 [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md)를 throw해야 합니다. 발급자는 다음을 기준으로 검증되어야 합니다: +이 함수는 발급자가 유효하지 않은 경우 코드가 'invalid_issuer'인 [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md)를 throw해야 합니다. 발급자는 다음을 기준으로 검증해야 합니다: 1. MCP-Auth의 인증 서버 메타데이터에 구성된 인가 서버 (Authorization server) 2. 보호된 리소스의 메타데이터에 나열된 인가 서버 (Authorization server) 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 index 1feef1b..aea5510 100644 --- 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 @@ -8,13 +8,13 @@ sidebar_label: VerifyAccessTokenFunction type VerifyAccessTokenFunction = (token: string) => MaybePromise; ``` -액세스 토큰 (Access token)을 검증하는 함수 타입입니다. +액세스 토큰 (Access token) 검증을 위한 함수 타입입니다. 이 함수는 토큰이 유효하지 않은 경우 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md)를 throw 해야 하며, 토큰이 유효한 경우 AuthInfo 객체를 반환해야 합니다. -예를 들어, JWT 검증 함수가 있다면 최소한 토큰의 서명, 만료 여부를 확인하고 필요한 클레임 (Claim)을 추출하여 `AuthInfo` -객체를 반환해야 합니다. +예를 들어, JWT 검증 함수가 있다면, 최소한 토큰의 서명을 확인하고, 만료를 검증하며, +필요한 클레임 (Claim)을 추출하여 `AuthInfo` 객체를 반환해야 합니다. **참고:** 다음 필드는 핸들러에서 확인하므로 토큰에서 별도로 검증할 필요가 없습니다: @@ -34,4 +34,4 @@ type VerifyAccessTokenFunction = (token: string) => MaybePromise; `MaybePromise`\<`AuthInfo`\> -토큰이 유효한 경우 AuthInfo 객체 또는 동기 값으로 resolve 되는 프로미스입니다. \ No newline at end of file +토큰이 유효한 경우 AuthInfo 객체 또는 동기 값으로 resolve 되는 promise 입니다. 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 index b9db02f..32a66c9 100644 --- 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 @@ -5,11 +5,35 @@ sidebar_label: authorizationServerMetadataSchema # 변수: authorizationServerMetadataSchema ```ts -const authorizationServerMetadataSchema: ZodObject; +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 스키마입니다. +RFC 8414에서 정의된 OAuth 2.0 인가 서버 메타데이터 (Authorization Server Metadata)를 위한 Zod 스키마입니다. ## 참고 {#see} -https://datatracker.ietf.org/doc/html/rfc8414 \ No newline at end of file +https://datatracker.ietf.org/doc/html/rfc8414 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 index 0cab425..4b2bf93 100644 --- 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 @@ -5,11 +5,35 @@ sidebar_label: camelCaseAuthorizationServerMetadataSchema # 변수: camelCaseAuthorizationServerMetadataSchema ```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject; +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)의 camelCase 버전 Zod 스키마입니다. +OAuth 2.0 인가 서버 메타데이터 Zod 스키마의 camelCase 버전입니다. ## 참고 {#see} -원본 스키마 및 필드 정보는 [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) 를 참조하세요. +원본 스키마 및 필드 정보는 [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 index 82414a5..d62cbd3 100644 --- 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 @@ -5,11 +5,27 @@ sidebar_label: camelCaseProtectedResourceMetadataSchema # 변수: camelCaseProtectedResourceMetadataSchema ```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject; +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 스키마의 camelCase 버전입니다. +OAuth 2.0 불투명 토큰 (Opaque token) 보호 리소스 메타데이터 Zod 스키마의 camelCase 버전입니다. ## 참고 {#see} -원본 스키마 및 필드 정보는 [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) 를 참조하세요. +원본 스키마 및 필드 정보는 [protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) 를 참고하세요. 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 index b230720..1f888df 100644 --- 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 @@ -5,7 +5,23 @@ sidebar_label: protectedResourceMetadataSchema # 변수: protectedResourceMetadataSchema ```ts -const protectedResourceMetadataSchema: ZodObject; +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/pt-BR/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/README.md index 164f971..2e9e8d7 100644 --- 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 @@ -21,6 +21,7 @@ sidebar_label: Node.js SDK - [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) @@ -33,6 +34,7 @@ sidebar_label: Node.js SDK - [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) @@ -56,4 +58,5 @@ sidebar_label: Node.js SDK - [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 index c9bfb0f..18a20d3 100644 --- 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 @@ -16,17 +16,45 @@ para gerar middleware Express para autenticação baseada em token. 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, fetchServerConfig } from 'mcp-auth'; +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` pode ser um único objeto de configuração ou um array deles. protectedResources: [ { metadata: { @@ -37,8 +65,12 @@ const mcpAuth = new MCPAuth({ }, ], }); +``` + +#### Usando o middleware {#using-the-middleware} -// Monta o router para lidar com o Metadata de Recurso Protegido +```ts +// Monta o router para lidar com Protected Resource Metadata app.use(mcpAuth.protectedResourceMetadataRouter()); // Protege um endpoint de API para o recurso configurado @@ -56,23 +88,21 @@ app.get( ); ``` -### Uso legado no modo `authorization server` (Obsoleto) {#legacy-usage-in-authorization-server-mode-deprecated} +### 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, fetchServerConfig } from 'mcp-auth'; +import { MCPAuth } from 'mcp-auth'; const app = express(); const mcpAuth = new MCPAuth({ - server: await fetchServerConfig( - 'https://auth.logto.io/oidc', - { type: 'oidc' } - ), + // Configuração de descoberta - metadados buscados sob demanda + server: { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }, }); -// Monta o router para lidar com o Metadata legado do Authorization Server +// Monta o router para lidar com metadados legados do Authorization Server app.use(mcpAuth.delegatedRouter()); // Protege um endpoint usando a política padrão @@ -129,7 +159,7 @@ A configuração de autenticação. bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; ``` -Cria um handler de autenticação Bearer (middleware Express) que verifica o token de acesso no +Cria um handler Bearer auth (middleware Express) que verifica o token de acesso no cabeçalho `Authorization` da requisição. ##### Parâmetros {#parameters} @@ -139,7 +169,7 @@ cabeçalho `Authorization` da requisição. [`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 um valor) que resolve para o +token de acesso como uma string e retornar uma promise (ou valor) que resolve para o resultado da verificação. **Veja também** @@ -151,7 +181,7 @@ resultado da verificação. `Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> -Configuração opcional para o handler de autenticação Bearer. +Configuração opcional para o handler Bearer auth. **Veja também** @@ -176,7 +206,7 @@ objeto `req.auth` (`AuthInfo`). bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; ``` -Cria um handler de autenticação Bearer (middleware Express) que verifica o token de acesso no +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 @@ -198,7 +228,7 @@ O modo de verificação para o token de acesso. Atualmente, apenas 'jwt' é supo `Omit`\<[`BearerAuthConfig`](/references/js/type-aliases/BearerAuthConfig.md), `"issuer"` \| `"verifyAccessToken"`\> & `VerifyJwtConfig` -Configuração opcional para o handler de autenticação Bearer, incluindo opções de verificação JWT e +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** @@ -232,17 +262,17 @@ usar o modo `'jwt'`. delegatedRouter(): Router; ``` -Cria um router delegado para servir o endpoint legado de Metadata do OAuth 2.0 Authorization Server -(`/.well-known/oauth-authorization-server`) com os metadados fornecidos para a instância. +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 de Metadata do OAuth 2.0 Authorization Server com os -metadados fornecidos para a instância. +Um router que serve o endpoint OAuth 2.0 Authorization Server Metadata com os +metadados fornecidos à instância. -#### Obsoleto {#deprecated} +#### Descontinuado {#deprecated} Use [protectedResourceMetadataRouter](/references/js/classes/MCPAuth.md#protectedresourcemetadatarouter) em vez disso. @@ -269,7 +299,7 @@ Se chamado no modo `resource server`. protectedResourceMetadataRouter(): Router; ``` -Cria um router que serve o endpoint de Metadata de Recurso Protegido OAuth 2.0 +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 @@ -279,7 +309,7 @@ identificador de recurso fornecido na sua configuração. `Router` -Um router que serve o endpoint de Metadata de Recurso Protegido OAuth 2.0. +Um router que serve o endpoint OAuth 2.0 Protected Resource Metadata. #### Lança exceção {#throws} @@ -291,11 +321,11 @@ Se chamado no modo `authorization server`. import express from 'express'; import { MCPAuth } from 'mcp-auth'; -// Supondo que mcpAuth está inicializado com uma ou mais configs `protectedResources` +// Supondo que mcpAuth foi inicializado com uma ou mais configs `protectedResources` const mcpAuth: MCPAuth; const app = express(); -// Isso servirá metadata em `/.well-known/oauth-protected-resource/...` -// com base nos seus identificadores de recurso. +// 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 index c85af2b..9c47118 100644 --- 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 @@ -56,7 +56,7 @@ readonly optional cause: unknown; readonly code: AuthServerErrorCode; ``` -O código do erro no formato snake_case. +O código de erro no formato snake_case. #### Herdado de {#inherited-from} @@ -100,21 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -A propriedade `Error.stackTraceLimit` especifica o número de frames de pilha -coletados por um stack trace (seja gerado por `new Error().stack` ou -`Error.captureStackTrace(obj)`). +Sobrescrita opcional para formatação de rastreamentos de pilha -O valor padrão é `10`, mas pode ser definido para qualquer número válido do JavaScript. Alterações -afetarão qualquer stack trace capturado _após_ a alteração do valor. +#### Parâmetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -Se definido para um valor não numérico ou negativo, os stack traces não -capturarão nenhum frame. +`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} @@ -155,49 +177,7 @@ O padrão é `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Cria uma propriedade `.stack` em `targetObject`, que ao ser acessada retorna -uma string representando a localização no código em que -`Error.captureStackTrace()` foi chamado. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Semelhante a `new Error().stack` -``` - -A primeira linha do trace será prefixada com -`${myObject.name}: ${myObject.message}`. - -O argumento opcional `constructorOpt` aceita uma função. Se fornecido, todos os frames -acima de `constructorOpt`, incluindo `constructorOpt`, serão omitidos do -stack trace gerado. - -O argumento `constructorOpt` é útil para ocultar detalhes de implementação -da geração do erro para o usuário. Por exemplo: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Cria um erro sem stack trace para evitar calcular o stack trace duas vezes. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Captura o stack trace acima da função b - Error.captureStackTrace(error, b); // Nem a função c, nem b são incluídas no stack trace - throw error; -} - -a(); -``` +Cria a propriedade .stack em um objeto alvo #### Parâmetros {#parameters} @@ -215,34 +195,4 @@ a(); #### Herdado de {#inherited-from} -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### Parâmetros {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Retorna {#returns} - -`any` - -#### Veja também {#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) \ No newline at end of file +[`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 index d7f4fcd..287dd1b 100644 --- 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 @@ -56,7 +56,7 @@ readonly optional cause: MCPAuthBearerAuthErrorDetails; readonly code: BearerAuthErrorCode; ``` -O código de erro no formato snake_case. +O código do erro no formato snake_case. #### Herdado de {#inherited-from} @@ -100,21 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -A propriedade `Error.stackTraceLimit` especifica o número de frames de pilha -coletados por um stack trace (seja gerado por `new Error().stack` ou -`Error.captureStackTrace(obj)`). +Sobrescrita opcional para formatação de stack traces -O valor padrão é `10`, mas pode ser definido para qualquer número válido em JavaScript. Alterações -afetarão qualquer stack trace capturado _após_ a alteração do valor. +#### Parâmetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -Se definido para um valor não numérico, ou para um número negativo, os stack traces -não capturarão nenhum frame. +`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} @@ -155,49 +177,7 @@ O padrão é `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Cria uma propriedade `.stack` em `targetObject`, que ao ser acessada retorna -uma string representando a localização no código em que -`Error.captureStackTrace()` foi chamado. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Semelhante a `new Error().stack` -``` - -A primeira linha do trace será prefixada com -`${myObject.name}: ${myObject.message}`. - -O argumento opcional `constructorOpt` aceita uma função. Se fornecido, todos os frames -acima de `constructorOpt`, incluindo `constructorOpt`, serão omitidos do -stack trace gerado. - -O argumento `constructorOpt` é útil para ocultar detalhes de implementação -da geração do erro para o usuário. Por exemplo: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Cria um erro sem stack trace para evitar calcular o stack trace duas vezes. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Captura o stack trace acima da função b - Error.captureStackTrace(error, b); // Nem a função c, nem b são incluídas no stack trace - throw error; -} - -a(); -``` +Cria a propriedade .stack em um objeto alvo #### Parâmetros {#parameters} @@ -215,34 +195,4 @@ a(); #### Herdado de {#inherited-from} -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### Parâmetros {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Retorna {#returns} - -`any` - -#### Veja também {#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) \ No newline at end of file +[`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 index 97a7fef..723509d 100644 --- 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 @@ -24,7 +24,7 @@ new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; `string` -O código do erro no formato snake_case. +O código de erro no formato snake_case. ##### message {#message} @@ -60,7 +60,7 @@ optional cause: unknown; readonly code: string; ``` -O código do erro no formato snake_case. +O código de erro no formato snake_case. #### Herdado de {#inherited-from} @@ -104,21 +104,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -A propriedade `Error.stackTraceLimit` especifica o número de frames de pilha -coletados por um stack trace (seja gerado por `new Error().stack` ou -`Error.captureStackTrace(obj)`). +Sobrescrita opcional para formatação de rastreamentos de pilha -O valor padrão é `10`, mas pode ser definido para qualquer número válido em JavaScript. Alterações -afetarão qualquer stack trace capturado _após_ a alteração do valor. +#### Parâmetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -Se definido para um valor não numérico, ou para um número negativo, os stack traces -não capturarão nenhum frame. +`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} @@ -159,49 +181,7 @@ O padrão é `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Cria uma propriedade `.stack` em `targetObject`, que ao ser acessada retorna -uma string representando a localização no código em que -`Error.captureStackTrace()` foi chamada. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Semelhante a `new Error().stack` -``` - -A primeira linha do trace será prefixada com -`${myObject.name}: ${myObject.message}`. - -O argumento opcional `constructorOpt` aceita uma função. Se fornecido, todos os frames -acima de `constructorOpt`, incluindo `constructorOpt`, serão omitidos do -stack trace gerado. - -O argumento `constructorOpt` é útil para ocultar detalhes de implementação -da geração do erro para o usuário. Por exemplo: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Cria um erro sem stack trace para evitar calcular o stack trace duas vezes. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Captura o stack trace acima da função b - Error.captureStackTrace(error, b); // Nem a função c, nem b são incluídas no stack trace - throw error; -} - -a(); -``` +Cria a propriedade .stack em um objeto alvo #### Parâmetros {#parameters} @@ -219,34 +199,4 @@ a(); #### Herdado de {#inherited-from} -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### Parâmetros {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Retorna {#returns} - -`any` - -#### Veja também {#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) \ No newline at end of file +[`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 index e868d80..57aec67 100644 --- 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 @@ -119,21 +119,45 @@ Error.stack *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -A propriedade `Error.stackTraceLimit` especifica o número de frames de pilha -coletados por um stack trace (seja gerado por `new Error().stack` ou -`Error.captureStackTrace(obj)`). +Sobrescrita opcional para formatação de stack traces + +#### Parâmetros {#parameters} + +##### err {#err} -O valor padrão é `10`, mas pode ser definido para qualquer número válido do JavaScript. Alterações -afetarão qualquer stack trace capturado _após_ a alteração do valor. +`Error` -Se definido para um valor não numérico, ou para um número negativo, os stack traces -não capturarão nenhum frame. +##### 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} @@ -158,7 +182,7 @@ Converte o erro para um formato JSON amigável para resposta HTTP. `boolean` = `false` Se deve incluir a causa do erro na resposta JSON. -O padrão é `false`. +Padrão é `false`. #### Retorna {#returns} @@ -172,48 +196,7 @@ O padrão é `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Cria uma propriedade `.stack` em `targetObject`, que ao ser acessada retorna -uma string representando a localização no código em que -`Error.captureStackTrace()` foi chamada. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Semelhante a `new Error().stack` -``` - -A primeira linha do trace será prefixada com -`${myObject.name}: ${myObject.message}`. - -O argumento opcional `constructorOpt` aceita uma função. Se fornecido, todos os frames -acima de `constructorOpt`, incluindo `constructorOpt`, serão omitidos do stack trace gerado. - -O argumento `constructorOpt` é útil para ocultar detalhes de implementação -da geração do erro para o usuário. Por exemplo: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Cria um erro sem stack trace para evitar calcular o stack trace duas vezes. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Captura o stack trace acima da função b - Error.captureStackTrace(error, b); // Nem a função c, nem b são incluídas no stack trace - throw error; -} - -a(); -``` +Cria a propriedade .stack em um objeto alvo #### Parâmetros {#parameters} @@ -233,36 +216,4 @@ a(); ```ts Error.captureStackTrace -``` - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### 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 ``` \ 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 index 47b2783..991eef4 100644 --- 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 @@ -100,21 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -A propriedade `Error.stackTraceLimit` especifica o número de frames de pilha -coletados por um stack trace (seja gerado por `new Error().stack` ou -`Error.captureStackTrace(obj)`). +Sobrescrita opcional para formatação de rastreamentos de pilha -O valor padrão é `10`, mas pode ser definido para qualquer número válido do JavaScript. Alterações -afetarão qualquer stack trace capturado _após_ a alteração do valor. +#### Parâmetros {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -Se definido para um valor não numérico, ou para um número negativo, os stack traces -não capturarão nenhum frame. +`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} @@ -155,49 +177,7 @@ O padrão é `false`. static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -Cria uma propriedade `.stack` em `targetObject`, que ao ser acessada retorna -uma string representando a localização no código em que -`Error.captureStackTrace()` foi chamado. - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // Semelhante a `new Error().stack` -``` - -A primeira linha do trace será prefixada com -`${myObject.name}: ${myObject.message}`. - -O argumento opcional `constructorOpt` aceita uma função. Se fornecido, todos os frames -acima de `constructorOpt`, incluindo `constructorOpt`, serão omitidos do -stack trace gerado. - -O argumento `constructorOpt` é útil para ocultar detalhes de implementação -da geração do erro para o usuário. Por exemplo: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // Cria um erro sem stack trace para evitar calcular o stack trace duas vezes. - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // Captura o stack trace acima da função b - Error.captureStackTrace(error, b); // Nem a função c, nem b são incluídas no stack trace - throw error; -} - -a(); -``` +Cria a propriedade .stack em um objeto alvo #### Parâmetros {#parameters} @@ -215,34 +195,4 @@ a(); #### Herdado de {#inherited-from} -[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static prepareStackTrace(err: Error, stackTraces: CallSite[]): any; -``` - -#### Parâmetros {#parameters} - -##### err {#err} - -`Error` - -##### stackTraces {#stacktraces} - -`CallSite`[] - -#### Retorna {#returns} - -`any` - -#### Veja também {#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) \ No newline at end of file +[`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/fetchServerConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/fetchServerConfig.md index d11b77d..f169f76 100644 --- 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 @@ -5,13 +5,12 @@ sidebar_label: fetchServerConfig # Função: fetchServerConfig() ```ts -function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; +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. +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} @@ -25,13 +24,13 @@ A URL do emissor (Issuer) do servidor de autorização. `ServerMetadataConfig` -O objeto de configuração contendo o tipo de servidor e uma função de transpilação opcional. +O objeto de configuração contendo o tipo de servidor e a função de transpilação opcional. -## Retorno {#returns} +## Retorna {#returns} -`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> +`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -Uma promise que resolve para a configuração do servidor. +Uma promise que resolve para a configuração estática do servidor com os metadados buscados. ## Veja também {#see} @@ -58,5 +57,4 @@ 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 +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 index 53f429c..4ca6bc2 100644 --- 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 @@ -5,7 +5,7 @@ sidebar_label: fetchServerConfigByWellKnownUrl # Função: fetchServerConfigByWellKnownUrl() ```ts -function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; +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. @@ -26,11 +26,11 @@ A well-known URL de onde buscar a configuração do servidor. Pode ser uma strin O objeto de configuração contendo o tipo do servidor e, opcionalmente, a função de transpile. -## Retorna {#returns} +## Retorno {#returns} -`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> +`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -Uma promise que resolve para a configuração do servidor. +Uma promise que resolve para a configuração estática do servidor com os metadados buscados. ## Lança exceção {#throws} 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 new file mode 100644 index 0000000..bd74823 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md @@ -0,0 +1,24 @@ +--- +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 index 3c9d1fa..aad396f 100644 --- 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 @@ -11,13 +11,13 @@ 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 (Issuer), público (Audience) e escopos (Scopes) necessários. +`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 (Access token) falhar, responde com um erro 401 Não autorizado. -- Se o token não possuir os escopos (Scopes) necessários, responde com um erro 403 Proibido. -- Se ocorrerem erros inesperados durante o processo de autenticação (Authentication), o middleware irá relançá-los. +- 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. 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 index 0651175..0a7ffc9 100644 --- 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 @@ -5,45 +5,13 @@ sidebar_label: AuthServerConfig # Alias de Tipo: AuthServerConfig ```ts -type AuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; - type: AuthServerType; -}; +type AuthServerConfig = + | ResolvedAuthServerConfig + | AuthServerDiscoveryConfig; ``` -Configuração para o servidor remoto de autorização integrado com o servidor MCP. +Configuração para o servidor de autorização remoto integrado com o servidor MCP. -## 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 normalmente são obtidos a partir 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} - - - [Metadados do Servidor de Autorização 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; -``` - -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 +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/AuthServerConfigWarning.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerConfigWarning.md index 102c7ce..047abd2 100644 --- 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 @@ -21,7 +21,7 @@ Representa um aviso que ocorre durante a validação dos metadados do servidor d code: AuthServerConfigWarningCode; ``` -O código que representa o aviso específico de validação. +O código que representa o aviso de validação específico. *** @@ -31,4 +31,4 @@ O código que representa o aviso específico de validação. description: string; ``` -Uma descrição legível por humanos do aviso. \ No newline at end of file +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/AuthServerDiscoveryConfig.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md new file mode 100644 index 0000000..37b00d6 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md @@ -0,0 +1,57 @@ +--- +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/AuthorizationServerMetadata.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md index 95c6719..d2b9621 100644 --- 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 @@ -5,233 +5,10 @@ sidebar_label: AuthorizationServerMetadata # Alias de Tipo: AuthorizationServerMetadata ```ts -type AuthorizationServerMetadata = { - authorization_endpoint: string; - code_challenge_methods_supported?: string[]; - grant_types_supported?: string[]; - introspection_endpoint?: string; - introspection_endpoint_auth_methods_supported?: string[]; - introspection_endpoint_auth_signing_alg_values_supported?: string[]; - issuer: string; - jwks_uri?: string; - op_policy_uri?: string; - op_tos_uri?: string; - registration_endpoint?: string; - response_modes_supported?: string[]; - response_types_supported: string[]; - revocation_endpoint?: string; - revocation_endpoint_auth_methods_supported?: string[]; - revocation_endpoint_auth_signing_alg_values_supported?: string[]; - scopes_supported?: string[]; - service_documentation?: string; - token_endpoint: string; - token_endpoint_auth_methods_supported?: string[]; - token_endpoint_auth_signing_alg_values_supported?: string[]; - ui_locales_supported?: string[]; - userinfo_endpoint?: string; -}; +type AuthorizationServerMetadata = z.infer; ``` -Esquema para os metadados do servidor de autorização OAuth 2.0 conforme definido na RFC 8414. - -## Declaração do tipo {#type-declaration} - -### authorization\_endpoint {#authorization-endpoint} - -```ts -authorization_endpoint: string; -``` - -URL do endpoint de autorização do servidor de autorização [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. -Isto é OBRIGATÓRIO, a menos que nenhum tipo de concessão seja suportado que utilize o endpoint de autorização. - -#### Veja {#see} - -https://rfc-editor.org/rfc/rfc6749#section-3.1 - -### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} - -```ts -optional code_challenge_methods_supported: string[]; -``` - -Array JSON contendo uma lista de métodos de desafio de código Proof Key for Code Exchange (PKCE) -[[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] suportados por este servidor de autorização. - -### grant\_types\_supported? {#grant-types-supported} - -```ts -optional grant_types_supported: string[]; -``` - -Array JSON contendo uma lista dos valores de tipo de concessão OAuth 2.0 que este servidor de autorização -suporta. Os valores do array usados são os mesmos usados com o parâmetro `grant_types` -definido pelo "OAuth 2.0 Dynamic Client Registration Protocol" [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. -Se omitido, o valor padrão é `["authorization_code", "implicit"]`. - -### introspection\_endpoint? {#introspection-endpoint} - -```ts -optional introspection_endpoint: string; -``` - -URL do endpoint de introspecção OAuth 2.0 do servidor de autorização -[[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]. - -### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} - -```ts -optional introspection_endpoint_auth_methods_supported: string[]; -``` - -### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} - -```ts -optional introspection_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### issuer {#issuer} - -```ts -issuer: string; -``` - -O identificador do emissor (Issuer) do servidor de autorização, que é uma URL que utiliza o esquema `https` e -não possui componentes de consulta ou fragmento. - -### jwks\_uri? {#jwks-uri} - -```ts -optional jwks_uri: string; -``` - -URL do documento JWK Set [[JWK](https://www.rfc-editor.org/rfc/rfc8414.html#ref-JWK)] -do servidor de autorização. O documento referenciado contém a(s) chave(s) de assinatura que o cliente usa para validar -assinaturas do servidor de autorização. Esta URL DEVE usar o esquema `https`. - -### op\_policy\_uri? {#op-policy-uri} - -```ts -optional op_policy_uri: string; -``` - -### op\_tos\_uri? {#op-tos-uri} - -```ts -optional op_tos_uri: string; -``` - -### registration\_endpoint? {#registration-endpoint} - -```ts -optional registration_endpoint: string; -``` - -URL do endpoint de Registro Dinâmico de Cliente OAuth 2.0 do servidor de autorização -[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. - -### response\_modes\_supported? {#response-modes-supported} - -```ts -optional response_modes_supported: string[]; -``` - -Array JSON contendo uma lista dos valores de `response_mode` do OAuth 2.0 que este -servidor de autorização suporta, conforme especificado em "OAuth 2.0 Multiple Response -Type Encoding Practices" -[[OAuth.Responses](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Responses)]. - -Se omitido, o padrão é `["query", "fragment"]`. O valor de response mode `"form_post"` também é -definido em "OAuth 2.0 Form Post Response Mode" -[[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)]. - -### response\_types\_supported {#response-types-supported} - -```ts -response_types_supported: string[]; -``` - -Array JSON contendo uma lista dos valores de `response_type` do OAuth 2.0 que este servidor de autorização -suporta. Os valores do array usados são os mesmos usados com o parâmetro `response_types` -definido pelo "OAuth 2.0 Dynamic Client Registration Protocol" -[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]. - -### revocation\_endpoint? {#revocation-endpoint} - -```ts -optional revocation_endpoint: string; -``` - -URL do endpoint de revogação OAuth 2.0 do servidor de autorização -[[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]. - -### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} - -```ts -optional revocation_endpoint_auth_methods_supported: string[]; -``` - -### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} - -```ts -optional revocation_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### scopes\_supported? {#scopes-supported} - -```ts -optional scopes_supported: string[]; -``` - -Array JSON contendo uma lista dos valores de `scope` do OAuth 2.0 que este servidor de autorização -suporta. -[[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] - -### service\_documentation? {#service-documentation} - -```ts -optional service_documentation: string; -``` - -### token\_endpoint {#token-endpoint} - -```ts -token_endpoint: string; -``` - -URL do endpoint de token do servidor de autorização [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]. -Isto é OBRIGATÓRIO, a menos que apenas o tipo de concessão implícita seja suportado. - -#### Veja {#see} - -https://rfc-editor.org/rfc/rfc6749#section-3.2 - -### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} - -```ts -optional token_endpoint_auth_methods_supported: string[]; -``` - -### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} - -```ts -optional token_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### ui\_locales\_supported? {#ui-locales-supported} - -```ts -optional ui_locales_supported: string[]; -``` - -### userinfo\_endpoint? {#userinfo-endpoint} - -```ts -optional userinfo_endpoint: string; -``` - -URL do [userinfo endpoint](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) do OpenID Connect. -Este endpoint é usado para recuperar informações sobre o usuário autenticado. +Esquema para Metadados do Servidor de Autorização OAuth 2.0 conforme definido na RFC 8414. ## Veja também {#see} 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 index 7aa9fe1..dd6c28e 100644 --- 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 @@ -27,8 +27,8 @@ 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 o seu servidor de autorização não suporta Indicadores de Recurso (Resource Indicators) (RFC 8707), -você pode omitir este campo, pois o público pode não ser relevante. +**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} @@ -90,8 +90,8 @@ servidores de autorização configurados para este recurso para validar o token optional showErrorDetails: boolean; ``` -Indica se deve mostrar informações detalhadas de erro na resposta. Isso é útil para depuração -durante o desenvolvimento, mas deve ser desabilitado em produção para evitar vazamento de informações sensíveis. +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} 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 index 7b7d02e..08c11ae 100644 --- 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 @@ -5,174 +5,10 @@ sidebar_label: CamelCaseAuthorizationServerMetadata # Alias de Tipo: CamelCaseAuthorizationServerMetadata ```ts -type CamelCaseAuthorizationServerMetadata = { - authorizationEndpoint: string; - codeChallengeMethodsSupported?: string[]; - grantTypesSupported?: string[]; - introspectionEndpoint?: string; - introspectionEndpointAuthMethodsSupported?: string[]; - introspectionEndpointAuthSigningAlgValuesSupported?: string[]; - issuer: string; - jwksUri?: string; - opPolicyUri?: string; - opTosUri?: string; - registrationEndpoint?: string; - responseModesSupported?: string[]; - responseTypesSupported: string[]; - revocationEndpoint?: string; - revocationEndpointAuthMethodsSupported?: string[]; - revocationEndpointAuthSigningAlgValuesSupported?: string[]; - scopesSupported?: string[]; - serviceDocumentation?: string; - tokenEndpoint: string; - tokenEndpointAuthMethodsSupported?: string[]; - tokenEndpointAuthSigningAlgValuesSupported?: string[]; - uiLocalesSupported?: string[]; - userinfoEndpoint?: string; -}; +type CamelCaseAuthorizationServerMetadata = z.infer; ``` -A versão em camelCase do tipo de Metadados do Servidor de Autorização OAuth 2.0 (OAuth 2.0 Authorization Server Metadata type). - -## Declaração do tipo {#type-declaration} - -### authorizationEndpoint {#authorizationendpoint} - -```ts -authorizationEndpoint: string; -``` - -### codeChallengeMethodsSupported? {#codechallengemethodssupported} - -```ts -optional codeChallengeMethodsSupported: string[]; -``` - -### grantTypesSupported? {#granttypessupported} - -```ts -optional grantTypesSupported: string[]; -``` - -### introspectionEndpoint? {#introspectionendpoint} - -```ts -optional introspectionEndpoint: string; -``` - -### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} - -```ts -optional introspectionEndpointAuthMethodsSupported: string[]; -``` - -### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} - -```ts -optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### issuer {#issuer} - -```ts -issuer: string; -``` - -### jwksUri? {#jwksuri} - -```ts -optional jwksUri: string; -``` - -### opPolicyUri? {#oppolicyuri} - -```ts -optional opPolicyUri: string; -``` - -### opTosUri? {#optosuri} - -```ts -optional opTosUri: string; -``` - -### registrationEndpoint? {#registrationendpoint} - -```ts -optional registrationEndpoint: string; -``` - -### responseModesSupported? {#responsemodessupported} - -```ts -optional responseModesSupported: string[]; -``` - -### responseTypesSupported {#responsetypessupported} - -```ts -responseTypesSupported: string[]; -``` - -### revocationEndpoint? {#revocationendpoint} - -```ts -optional revocationEndpoint: string; -``` - -### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} - -```ts -optional revocationEndpointAuthMethodsSupported: string[]; -``` - -### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} - -```ts -optional revocationEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### scopesSupported? {#scopessupported} - -```ts -optional scopesSupported: string[]; -``` - -### serviceDocumentation? {#servicedocumentation} - -```ts -optional serviceDocumentation: string; -``` - -### tokenEndpoint {#tokenendpoint} - -```ts -tokenEndpoint: string; -``` - -### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} - -```ts -optional tokenEndpointAuthMethodsSupported: string[]; -``` - -### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} - -```ts -optional tokenEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### uiLocalesSupported? {#uilocalessupported} - -```ts -optional uiLocalesSupported: string[]; -``` - -### userinfoEndpoint? {#userinfoendpoint} - -```ts -optional userinfoEndpoint: string; -``` +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} 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 index 1de9b37..c2d56b3 100644 --- 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 @@ -5,118 +5,10 @@ sidebar_label: CamelCaseProtectedResourceMetadata # Alias de Tipo: CamelCaseProtectedResourceMetadata ```ts -type CamelCaseProtectedResourceMetadata = { - authorizationDetailsTypesSupported?: string[]; - authorizationServers?: string[]; - bearerMethodsSupported?: string[]; - dpopBoundAccessTokensRequired?: boolean; - dpopSigningAlgValuesSupported?: string[]; - jwksUri?: string; - resource: string; - resourceDocumentation?: string; - resourceName?: string; - resourcePolicyUri?: string; - resourceSigningAlgValuesSupported?: string[]; - resourceTosUri?: string; - scopesSupported?: string[]; - signedMetadata?: string; - tlsClientCertificateBoundAccessTokens?: boolean; -}; +type CamelCaseProtectedResourceMetadata = z.infer; ``` -A versão camelCase do tipo de Metadados de Recurso Protegido do OAuth 2.0 (OAuth 2.0 Protected Resource Metadata). - -## Declaração do tipo {#type-declaration} - -### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} - -```ts -optional authorizationDetailsTypesSupported: string[]; -``` - -### authorizationServers? {#authorizationservers} - -```ts -optional authorizationServers: string[]; -``` - -### bearerMethodsSupported? {#bearermethodssupported} - -```ts -optional bearerMethodsSupported: string[]; -``` - -### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} - -```ts -optional dpopBoundAccessTokensRequired: boolean; -``` - -### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} - -```ts -optional dpopSigningAlgValuesSupported: string[]; -``` - -### jwksUri? {#jwksuri} - -```ts -optional jwksUri: string; -``` - -### resource {#resource} - -```ts -resource: string; -``` - -### resourceDocumentation? {#resourcedocumentation} - -```ts -optional resourceDocumentation: string; -``` - -### resourceName? {#resourcename} - -```ts -optional resourceName: string; -``` - -### resourcePolicyUri? {#resourcepolicyuri} - -```ts -optional resourcePolicyUri: string; -``` - -### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} - -```ts -optional resourceSigningAlgValuesSupported: string[]; -``` - -### resourceTosUri? {#resourcetosuri} - -```ts -optional resourceTosUri: string; -``` - -### scopesSupported? {#scopessupported} - -```ts -optional scopesSupported: string[]; -``` - -### signedMetadata? {#signedmetadata} - -```ts -optional signedMetadata: string; -``` - -### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} - -```ts -optional tlsClientCertificateBoundAccessTokens: boolean; -``` +A versão em camelCase do tipo de Metadados de Recurso Protegido do OAuth 2.0. ## Veja também {#see} 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 index 0168f0b..86a0ebc 100644 --- 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 @@ -5,152 +5,7 @@ sidebar_label: ProtectedResourceMetadata # Alias de Tipo: ProtectedResourceMetadata ```ts -type ProtectedResourceMetadata = { - authorization_details_types_supported?: string[]; - authorization_servers?: string[]; - bearer_methods_supported?: string[]; - dpop_bound_access_tokens_required?: boolean; - dpop_signing_alg_values_supported?: string[]; - jwks_uri?: string; - resource: string; - resource_documentation?: string; - resource_name?: string; - resource_policy_uri?: string; - resource_signing_alg_values_supported?: string[]; - resource_tos_uri?: string; - scopes_supported?: string[]; - signed_metadata?: string; - tls_client_certificate_bound_access_tokens?: boolean; -}; +type ProtectedResourceMetadata = z.infer; ``` -Esquema para Metadados de Recurso Protegido do OAuth 2.0. - -## Declaração do tipo {#type-declaration} - -### authorization\_details\_types\_supported? {#authorization-details-types-supported} - -```ts -optional authorization_details_types_supported: string[]; -``` - -Valores de tipo de detalhes de autorização suportados ao usar o parâmetro de solicitação authorization_details. - -### authorization\_servers? {#authorization-servers} - -```ts -optional authorization_servers: string[]; -``` - -Lista de identificadores de emissor do servidor de autorização OAuth que podem ser usados com este recurso protegido. - -### bearer\_methods\_supported? {#bearer-methods-supported} - -```ts -optional bearer_methods_supported: string[]; -``` - -Métodos suportados para envio de tokens bearer do OAuth 2.0. Valores: ["header", "body", "query"]. - -### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} - -```ts -optional dpop_bound_access_tokens_required: boolean; -``` - -Se o recurso protegido sempre exige tokens de acesso vinculados ao DPoP. - -### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} - -```ts -optional dpop_signing_alg_values_supported: string[]; -``` - -Algoritmos JWS suportados para validação de provas JWT DPoP. - -### jwks\_uri? {#jwks-uri} - -```ts -optional jwks_uri: string; -``` - -URL do documento JSON Web Key (JWK) Set do recurso protegido. Este documento contém as chaves públicas -que podem ser usadas para verificar assinaturas digitais de respostas ou dados retornados por este recurso protegido. -Isso difere do jwks_uri do servidor de autorização, que é usado para validação de tokens. Quando o recurso protegido -assina suas respostas, os clientes podem buscar essas chaves públicas para verificar a autenticidade e integridade -dos dados recebidos. - -### resource {#resource} - -```ts -resource: string; -``` - -O identificador de recurso do recurso protegido. - -### resource\_documentation? {#resource-documentation} - -```ts -optional resource_documentation: string; -``` - -URL contendo a documentação para desenvolvedores sobre o uso do recurso protegido. - -### resource\_name? {#resource-name} - -```ts -optional resource_name: string; -``` - -Nome legível por humanos do recurso protegido para exibição aos usuários finais. - -### resource\_policy\_uri? {#resource-policy-uri} - -```ts -optional resource_policy_uri: string; -``` - -URL contendo informações sobre os requisitos de uso de dados do recurso protegido. - -### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} - -```ts -optional resource_signing_alg_values_supported: string[]; -``` - -Algoritmos de assinatura JWS suportados pelo recurso protegido para assinar respostas do recurso. - -### resource\_tos\_uri? {#resource-tos-uri} - -```ts -optional resource_tos_uri: string; -``` - -URL contendo os termos de serviço do recurso protegido. - -### scopes\_supported? {#scopes-supported} - -```ts -optional scopes_supported: string[]; -``` - -Lista de valores de escopo usados em solicitações de autorização para acessar este recurso protegido. - -### signed\_metadata? {#signed-metadata} - -```ts -optional signed_metadata: string; -``` - -Um JWT assinado contendo parâmetros de metadados como reivindicações. O JWT deve ser assinado usando JWS e incluir -uma reivindicação 'iss'. Este campo fornece uma maneira de verificar criptograficamente a autenticidade dos próprios metadados. -A assinatura pode ser verificada usando as chaves públicas disponíveis no endpoint `jwks_uri`. -Quando presente, os valores neste metadado assinado têm precedência sobre os valores JSON simples correspondentes neste documento de metadados. Isso ajuda a evitar adulteração dos metadados do recurso. - -### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} - -```ts -optional tls_client_certificate_bound_access_tokens: boolean; -``` - -Se o recurso protegido suporta tokens de acesso vinculados a certificado de cliente mutual-TLS. \ No newline at end of file +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 new file mode 100644 index 0000000..0bcb309 --- /dev/null +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md @@ -0,0 +1,53 @@ +--- +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/ValidateIssuerFunction.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md index 2cc6468..35b96f7 100644 --- 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 @@ -21,10 +21,10 @@ Esta função deve lançar um [MCPAuthBearerAuthError](/references/js/classes/MC `string` -## Retorna {#returns} +## Retorno {#returns} `void` -## Lança {#throws} +## Lança exceção {#throws} -Quando o emissor não é reconhecido ou é inválido. \ No newline at end of file +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 index d1ab25d..a16a14c 100644 --- 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 @@ -19,9 +19,9 @@ assinatura do token, validar sua expiração e extrair as reivindicações (Clai **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) +- `iss` (emissor / issuer) +- `aud` (público / audience) +- `scope` (escopos / scopes) ## Parâmetros {#parameters} @@ -35,5 +35,5 @@ A string do token de acesso (Access token) a ser verificada. `MaybePromise`\<`AuthInfo`\> -Uma promessa que resolve para um objeto AuthInfo ou um valor síncrono se o +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/variables/authorizationServerMetadataSchema.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/authorizationServerMetadataSchema.md index 6f1c6c7..426eca9 100644 --- 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 @@ -5,7 +5,31 @@ sidebar_label: authorizationServerMetadataSchema # Variável: authorizationServerMetadataSchema ```ts -const authorizationServerMetadataSchema: ZodObject; +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. 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 index f998119..4b08e9b 100644 --- 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 @@ -5,11 +5,35 @@ sidebar_label: camelCaseAuthorizationServerMetadataSchema # Variável: camelCaseAuthorizationServerMetadataSchema ```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject; +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 em camelCase do esquema Zod de Metadados do Servidor de Autorização (Authorization Server Metadata) do OAuth 2.0. +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 esquema original e informações dos campos. \ No newline at end of file +[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 index a6e0617..816a3ec 100644 --- 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 @@ -5,11 +5,27 @@ sidebar_label: camelCaseProtectedResourceMetadataSchema # Variável: camelCaseProtectedResourceMetadataSchema ```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject; +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 em camelCase do esquema Zod de Metadados de Recurso Protegido do OAuth 2.0. +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 esquema original e informações dos campos. \ No newline at end of file +[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/protectedResourceMetadataSchema.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md index 0b3fee6..5080765 100644 --- 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 @@ -5,7 +5,23 @@ sidebar_label: protectedResourceMetadataSchema # Variável: protectedResourceMetadataSchema ```ts -const protectedResourceMetadataSchema: ZodObject; +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/zh-CN/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/README.md index 2412dc6..6e8e663 100644 --- 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 @@ -21,6 +21,7 @@ sidebar_label: Node.js SDK - [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) @@ -33,6 +34,7 @@ sidebar_label: Node.js SDK - [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) @@ -56,4 +58,5 @@ sidebar_label: Node.js SDK - [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 index 42d7d58..500711a 100644 --- 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 @@ -10,21 +10,48 @@ mcp-auth 库的主类。它作为工厂和注册中心,用于为你的受保 ## 示例 {#example} -### 在 `resource server` 模式下的用法 {#usage-in-resource-server-mode} +### 在 `资源服务器` 模式下的用法 {#usage-in-resource-server-mode} -这是新应用推荐的方式。 +这是新应用程序推荐的方式。 + +#### 选项 1:发现配置(推荐用于边缘运行时) {#option-1-discovery-config-recommended-for-edge-runtimes} + +当你希望按需获取元数据时使用此方式。对于如 Cloudflare Workers 这类不允许顶层异步 fetch 的边缘运行时尤其有用。 ```ts import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; +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` 可以是单个配置对象,也可以是对象数组。 protectedResources: [ { metadata: { @@ -35,7 +62,11 @@ const mcpAuth = new MCPAuth({ }, ], }); +``` + +#### 使用中间件 {#using-the-middleware} +```ts // 挂载路由以处理受保护资源元数据 app.use(mcpAuth.protectedResourceMetadataRouter()); @@ -44,7 +75,7 @@ app.get( '/notes', mcpAuth.bearerAuth('jwt', { resource: resourceIdentifier, // 指定该端点属于哪个资源 - audience: resourceIdentifier, // 可选,校验 'aud' 声明 + audience: resourceIdentifier, // 可选,校验 'aud' 声明 (Claim) requiredScopes: ['read:notes'], }), (req, res) => { @@ -54,20 +85,18 @@ app.get( ); ``` -### 传统 `authorization server` 模式用法(已弃用) {#legacy-usage-in-authorization-server-mode-deprecated} +### 传统 `授权 (Authorization) 服务器` 模式用法(已弃用) {#legacy-usage-in-authorization-server-mode-deprecated} 此方式为向后兼容而保留。 ```ts import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; +import { MCPAuth } from 'mcp-auth'; const app = express(); const mcpAuth = new MCPAuth({ - server: await fetchServerConfig( - 'https://auth.logto.io/oidc', - { type: 'oidc' } - ), + // 发现配置 - 按需获取元数据 + server: { issuer: 'https://auth.logto.io/oidc', type: 'oidc' }, }); // 挂载路由以处理传统授权 (Authorization) 服务器元数据 @@ -79,7 +108,7 @@ app.get( mcpAuth.bearerAuth('jwt', { requiredScopes: ['read', 'write'] }), (req, res) => { console.log('Auth info:', req.auth); - // 在这里处理 MCP 请求 + // 在此处理 MCP 请求 }, ); ``` @@ -92,7 +121,7 @@ app.get( new MCPAuth(config: MCPAuthConfig): MCPAuth; ``` -创建 MCPAuth 的实例。 +创建 MCPAuth 实例。 它会提前验证整个配置,以便在出错时快速失败。 #### 参数 {#parameters} @@ -127,7 +156,7 @@ readonly config: MCPAuthConfig; bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; ``` -创建一个 Bearer 认证 (Authentication) 处理器(Express 中间件),用于验证请求中 `Authorization` 头部的访问令牌 (Access token)。 +创建一个 Bearer 认证 (Authentication) 处理器(Express 中间件),用于验证请求的 `Authorization` 头中的访问令牌 (Access token)。 ##### 参数 {#parameters} @@ -155,11 +184,11 @@ Bearer 认证 (Authentication) 处理器的可选配置。 `RequestHandler` -一个 Express 中间件函数,用于验证访问令牌 (Access token) 并将验证结果添加到请求对象(`req.auth`)。 +一个 Express 中间件函数,用于验证访问令牌 (Access token) 并将验证结果添加到请求对象 (`req.auth`)。 ##### 参见 {#see} -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) 以了解实现细节及 `req.auth`(`AuthInfo`)对象的扩展类型。 +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) 以了解实现细节及 `req.auth` (`AuthInfo`) 对象的扩展类型。 #### 调用签名 {#call-signature} @@ -167,7 +196,7 @@ Bearer 认证 (Authentication) 处理器的可选配置。 bearerAuth(mode: "jwt", config?: Omit & VerifyJwtConfig): RequestHandler; ``` -创建一个 Bearer 认证 (Authentication) 处理器(Express 中间件),使用预定义的验证模式验证请求中 `Authorization` 头部的访问令牌 (Access token)。 +创建一个 Bearer 认证 (Authentication) 处理器(Express 中间件),使用预定义的验证模式验证请求的 `Authorization` 头中的访问令牌 (Access token)。 在 `'jwt'` 模式下,处理器将使用授权 (Authorization) 服务器的 JWKS URI 创建 JWT 验证函数。 @@ -198,15 +227,15 @@ Bearer 认证 (Authentication) 处理器的可选配置,包括 JWT 验证选 `RequestHandler` -一个 Express 中间件函数,用于验证访问令牌 (Access token) 并将验证结果添加到请求对象(`req.auth`)。 +一个 Express 中间件函数,用于验证访问令牌 (Access token) 并将验证结果添加到请求对象 (`req.auth`)。 ##### 参见 {#see} -[handleBearerAuth](/references/js/functions/handleBearerAuth.md) 以了解实现细节及 `req.auth`(`AuthInfo`)对象的扩展类型。 +[handleBearerAuth](/references/js/functions/handleBearerAuth.md) 以了解实现细节及 `req.auth` (`AuthInfo`) 对象的扩展类型。 ##### 抛出 {#throws} -当在 `'jwt'` 模式下,服务器元数据未提供 JWKS URI 时抛出。 +当在 `'jwt'` 模式下,服务器元数据中未提供 JWKS URI 时抛出。 *** @@ -216,13 +245,14 @@ Bearer 认证 (Authentication) 处理器的可选配置,包括 JWT 验证选 delegatedRouter(): Router; ``` -创建一个用于服务传统 OAuth 2.0 授权 (Authorization) 服务器元数据端点(`/.well-known/oauth-authorization-server`)的委托路由器,使用实例中提供的元数据。 +创建一个代理路由器,用于提供传统 OAuth 2.0 授权 (Authorization) 服务器元数据端点 +(`/.well-known/oauth-authorization-server`),并使用实例提供的元数据。 #### 返回值 {#returns} `Router` -用于服务 OAuth 2.0 授权 (Authorization) 服务器元数据端点的路由器,使用实例中提供的元数据。 +用于提供 OAuth 2.0 授权 (Authorization) 服务器元数据端点的路由器,使用实例提供的元数据。 #### 已弃用 {#deprecated} @@ -241,7 +271,7 @@ app.use(mcpAuth.delegatedRouter()); #### 抛出 {#throws} -如果在 `resource server` 模式下调用,则抛出。 +如果在 `资源服务器` 模式下调用,则抛出。 *** @@ -251,7 +281,7 @@ app.use(mcpAuth.delegatedRouter()); protectedResourceMetadataRouter(): Router; ``` -创建一个路由器,用于为所有已配置资源服务 OAuth 2.0 受保护资源元数据端点。 +创建一个路由器,用于为所有已配置资源提供 OAuth 2.0 受保护资源元数据端点。 该路由器会根据你配置中提供的每个资源标识符,自动创建正确的 `.well-known` 端点。 @@ -259,11 +289,11 @@ protectedResourceMetadataRouter(): Router; `Router` -用于服务 OAuth 2.0 受保护资源元数据端点的路由器。 +用于提供 OAuth 2.0 受保护资源元数据端点的路由器。 #### 抛出 {#throws} -如果在 `authorization server` 模式下调用,则抛出。 +如果在 `授权 (Authorization) 服务器` 模式下调用,则抛出。 #### 示例 {#example} 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 index 73c8302..75a6081 100644 --- 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 @@ -56,7 +56,7 @@ readonly optional cause: unknown; readonly code: AuthServerErrorCode; ``` -错误代码,采用 snake_case 格式。 +以 snake_case 格式表示的错误代码。 #### 继承自 {#inherited-from} @@ -100,17 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` 属性指定堆栈跟踪收集的堆栈帧数量(无论是由 `new Error().stack` 还是 `Error.captureStackTrace(obj)` 生成)。 +可选的堆栈跟踪格式化重写 + +#### 参数 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 返回 {#returns} + +`any` + +#### 参考 {#see} -默认值为 `10`,但可以设置为任何有效的 JavaScript 数字。更改后将影响之后捕获的所有堆栈跟踪。 +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} @@ -132,7 +158,8 @@ toJson(showCause: boolean): Record; `boolean` = `false` -是否在 JSON 响应中包含错误原因。默认为 `false`。 +是否在 JSON 响应中包含错误原因。 +默认为 `false`。 #### 返回 {#returns} @@ -150,43 +177,7 @@ toJson(showCause: boolean): Record; static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -在 `targetObject` 上创建一个 `.stack` 属性,当访问时返回一个字符串,表示调用 `Error.captureStackTrace()` 时代码中的位置。 - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // 类似于 `new Error().stack` -``` - -跟踪的第一行将以 `${myObject.name}: ${myObject.message}` 为前缀。 - -可选的 `constructorOpt` 参数接受一个函数。如果提供,则所有高于 `constructorOpt` 的帧(包括 `constructorOpt`)都将从生成的堆栈跟踪中省略。 - -`constructorOpt` 参数用于隐藏错误生成的实现细节。例如: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // 创建一个没有堆栈跟踪的错误,以避免重复计算堆栈跟踪。 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 捕获高于函数 b 的堆栈跟踪 - Error.captureStackTrace(error, b); // 堆栈跟踪中既不包含函数 c,也不包含 b - throw error; -} - -a(); -``` +在目标对象上创建 .stack 属性 #### 参数 {#parameters} @@ -205,33 +196,3 @@ a(); #### 继承自 {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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) 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 index e70b1da..04accac 100644 --- 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 @@ -28,7 +28,7 @@ new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthE [`MCPAuthBearerAuthErrorDetails`](/references/js/type-aliases/MCPAuthBearerAuthErrorDetails.md) -#### 返回 {#returns} +#### 返回值 {#returns} `MCPAuthBearerAuthError` @@ -56,7 +56,7 @@ readonly optional cause: MCPAuthBearerAuthErrorDetails; readonly code: BearerAuthErrorCode; ``` -错误代码,采用 snake_case 格式。 +错误码,采用 snake_case 格式。 #### 继承自 {#inherited-from} @@ -100,17 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` 属性指定堆栈跟踪收集的堆栈帧数量(无论是由 `new Error().stack` 还是 `Error.captureStackTrace(obj)` 生成)。 +可选的堆栈跟踪格式化重写 -默认值为 `10`,但可以设置为任何有效的 JavaScript 数字。更改后将影响之后捕获的任何堆栈跟踪。 +#### 参数 {#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} @@ -135,7 +161,7 @@ toJson(showCause: boolean): Record; 是否在 JSON 响应中包含错误原因。 默认为 `false`。 -#### 返回 {#returns} +#### 返回值 {#returns} `Record`\<`string`, `unknown`\> @@ -151,43 +177,7 @@ toJson(showCause: boolean): Record; static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -在 `targetObject` 上创建一个 `.stack` 属性,当访问时返回一个字符串,表示调用 `Error.captureStackTrace()` 时代码中的位置。 - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // 类似于 `new Error().stack` -``` - -跟踪的第一行将以 `${myObject.name}: ${myObject.message}` 为前缀。 - -可选的 `constructorOpt` 参数接受一个函数。如果提供,则在生成的堆栈跟踪中,将省略 `constructorOpt` 及其以上的所有帧。 - -`constructorOpt` 参数用于隐藏错误生成的实现细节。例如: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // 创建一个没有堆栈跟踪的错误,以避免重复计算堆栈跟踪。 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 捕获 function b 以上的堆栈跟踪 - Error.captureStackTrace(error, b); // 堆栈跟踪中不包含 function c 和 b - throw error; -} - -a(); -``` +在目标对象上创建 .stack 属性 #### 参数 {#parameters} @@ -199,40 +189,10 @@ a(); `Function` -#### 返回 {#returns} +#### 返回值 {#returns} `void` #### 继承自 {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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) 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 index f258636..b79c254 100644 --- 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 @@ -32,7 +32,7 @@ new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; 对错误的人类可读描述。 -#### 返回 {#returns} +#### 返回值 {#returns} `MCPAuthConfigError` @@ -104,17 +104,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` 属性指定堆栈跟踪收集的堆栈帧数量(无论是由 `new Error().stack` 还是 `Error.captureStackTrace(obj)` 生成)。 +可选的堆栈跟踪格式化重写 + +#### 参数 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 返回值 {#returns} + +`any` + +#### 参考 {#see} + +https://v8.dev/docs/stack-trace-api#customizing-stack-traces -默认值为 `10`,但可以设置为任何有效的 JavaScript 数字。更改后将影响之后捕获的所有堆栈跟踪。 +#### 继承自 {#inherited-from} -如果设置为非数字值或负数,则堆栈跟踪不会捕获任何帧。 +[`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`prepareStackTrace`](/references/js/classes/MCPAuthError.md#preparestacktrace) + +*** + +### stackTraceLimit {#stacktracelimit} + +```ts +static stackTraceLimit: number; +``` #### 继承自 {#inherited-from} @@ -136,9 +162,10 @@ toJson(showCause: boolean): Record; `boolean` = `false` -是否在 JSON 响应中包含错误原因。默认为 `false`。 +是否在 JSON 响应中包含错误原因。 +默认为 `false`。 -#### 返回 {#returns} +#### 返回值 {#returns} `Record`\<`string`, `unknown`\> @@ -154,43 +181,7 @@ toJson(showCause: boolean): Record; static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -在 `targetObject` 上创建一个 `.stack` 属性,当访问时返回一个字符串,表示调用 `Error.captureStackTrace()` 时代码中的位置。 - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // 类似于 `new Error().stack` -``` - -跟踪的第一行将以 `${myObject.name}: ${myObject.message}` 为前缀。 - -可选的 `constructorOpt` 参数接受一个函数。如果提供,所有在 `constructorOpt` 之上的帧(包括 `constructorOpt`)都将从生成的堆栈跟踪中省略。 - -`constructorOpt` 参数用于隐藏错误生成的实现细节。例如: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // 创建一个没有堆栈跟踪的错误,以避免重复计算堆栈跟踪。 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 捕获 function b 之上的堆栈跟踪 - Error.captureStackTrace(error, b); // 堆栈跟踪中不包含 function c 和 b - throw error; -} - -a(); -``` +在目标对象上创建 .stack 属性 #### 参数 {#parameters} @@ -202,40 +193,10 @@ a(); `Function` -#### 返回 {#returns} +#### 返回值 {#returns} `void` #### 继承自 {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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) 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 index ec40f17..e20aab8 100644 --- 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 @@ -33,7 +33,7 @@ new MCPAuthError(code: string, message: string): MCPAuthError; `string` -错误代码,采用 snake_case 格式。 +以 snake_case 格式表示的错误代码。 ##### message {#message} @@ -73,7 +73,7 @@ Error.cause readonly code: string; ``` -错误代码,采用 snake_case 格式。 +以 snake_case 格式表示的错误代码。 *** @@ -119,17 +119,45 @@ Error.stack *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` 属性指定堆栈跟踪收集的堆栈帧数量(无论是由 `new Error().stack` 还是 `Error.captureStackTrace(obj)` 生成)。 +可选的堆栈跟踪格式化重写 + +#### 参数 {#parameters} + +##### err {#err} -默认值为 `10`,但可以设置为任何有效的 JavaScript 数字。更改后将影响之后捕获的所有堆栈跟踪。 +`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} @@ -153,7 +181,8 @@ toJson(showCause: boolean): Record; `boolean` = `false` -是否在 JSON 响应中包含错误原因。默认为 `false`。 +是否在 JSON 响应中包含错误原因。 +默认为 `false`。 #### 返回 {#returns} @@ -167,43 +196,7 @@ toJson(showCause: boolean): Record; static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -在 `targetObject` 上创建一个 `.stack` 属性,当访问时返回一个字符串,表示调用 `Error.captureStackTrace()` 时代码中的位置。 - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // 类似于 `new Error().stack` -``` - -跟踪的第一行将以 `${myObject.name}: ${myObject.message}` 为前缀。 - -可选的 `constructorOpt` 参数接受一个函数。如果提供,则生成的堆栈跟踪中将省略 `constructorOpt` 及其以上的所有帧。 - -`constructorOpt` 参数用于隐藏错误生成的实现细节。例如: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // 创建一个没有堆栈跟踪的错误以避免重复计算堆栈。 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 捕获 b 以上的堆栈跟踪 - Error.captureStackTrace(error, b); // 堆栈跟踪中不包含 c 和 b - throw error; -} - -a(); -``` +在目标对象上创建 .stack 属性 #### 参数 {#parameters} @@ -224,35 +217,3 @@ a(); ```ts Error.captureStackTrace ``` - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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 -``` 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 index 4897dea..2784c6d 100644 --- 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 @@ -28,7 +28,7 @@ new MCPAuthTokenVerificationError(code: MCPAuthTokenVerificationErrorCode, cause `unknown` -#### 返回 {#returns} +#### 返回值 {#returns} `MCPAuthTokenVerificationError` @@ -100,17 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` 属性指定堆栈跟踪收集的堆栈帧数量(无论是由 `new Error().stack` 还是 `Error.captureStackTrace(obj)` 生成)。 +可选的堆栈跟踪格式化重写 -默认值为 `10`,但可以设置为任何有效的 JavaScript 数字。更改后将影响之后捕获的所有堆栈跟踪。 +#### 参数 {#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} @@ -135,7 +161,7 @@ toJson(showCause: boolean): Record; 是否在 JSON 响应中包含错误原因。 默认为 `false`。 -#### 返回 {#returns} +#### 返回值 {#returns} `Record`\<`string`, `unknown`\> @@ -151,43 +177,7 @@ toJson(showCause: boolean): Record; static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -在 `targetObject` 上创建一个 `.stack` 属性,当访问时返回一个字符串,表示调用 `Error.captureStackTrace()` 时在代码中的位置。 - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // 类似于 `new Error().stack` -``` - -跟踪的第一行将以 `${myObject.name}: ${myObject.message}` 为前缀。 - -可选的 `constructorOpt` 参数接受一个函数。如果提供,则在生成的堆栈跟踪中,`constructorOpt` 及其以上的所有帧都将被省略。 - -`constructorOpt` 参数对于隐藏错误生成的实现细节很有用。例如: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // 创建一个没有堆栈跟踪的错误,以避免重复计算堆栈跟踪。 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 捕获 b 函数以上的堆栈跟踪 - Error.captureStackTrace(error, b); // 堆栈跟踪中不包含 c 和 b 函数 - throw error; -} - -a(); -``` +在目标对象上创建 .stack 属性 #### 参数 {#parameters} @@ -199,40 +189,10 @@ a(); `Function` -#### 返回 {#returns} +#### 返回值 {#returns} `void` #### 继承自 {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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) 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 index 69a9a84..b3c3169 100644 --- 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 @@ -8,7 +8,7 @@ sidebar_label: createVerifyJwt function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; ``` -使用提供的密钥获取函数和选项,创建一个用于验证 JWT 访问令牌 (Access token) 的函数。 +使用提供的密钥检索函数和选项,创建一个用于验证 JWT 访问令牌 (Access token) 的函数。 ## 参数 {#parameters} @@ -16,11 +16,11 @@ function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): V `JWTVerifyGetKey` -用于获取验证 JWT 所需密钥的函数。 +用于检索验证 JWT 所需密钥的函数。 **参见** -JWTVerifyGetKey,了解密钥获取函数的类型定义。 +JWTVerifyGetKey 以获取密钥检索函数的类型定义。 ### options? {#options} @@ -30,14 +30,14 @@ JWTVerifyGetKey,了解密钥获取函数的类型定义。 **参见** -JWTVerifyOptions,了解选项的类型定义。 +JWTVerifyOptions 以获取选项的类型定义。 ## 返回值 {#returns} [`VerifyAccessTokenFunction`](/references/js/type-aliases/VerifyAccessTokenFunction.md) -一个用于验证 JWT 访问令牌 (Access token) 的函数,如果令牌有效,则返回一个 AuthInfo 对象。该函数要求 JWT 的 payload 中包含 `iss`、`client_id` 和 `sub` 字段,并且可以选择包含 `scope` 或 `scopes` 字段。该函数底层使用 `jose` 库进行 JWT 验证。 +一个用于验证 JWT 访问令牌 (Access token) 的函数,如果令牌有效,则返回一个 AuthInfo 对象。该函数要求 JWT 的 payload 中包含 `iss`、`client_id` 和 `sub` 字段,并且可以选择性地包含 `scope` 或 `scopes` 字段。该函数底层使用 `jose` 库来执行 JWT 验证。 ## 参见 {#see} -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md),了解返回函数的类型定义。 +[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 index 5cf1460..f826435 100644 --- 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 @@ -5,7 +5,7 @@ sidebar_label: fetchServerConfig # 函数:fetchServerConfig() ```ts -function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; +function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; ``` 根据发行者 (Issuer) 和授权 (Authorization) 服务器类型获取服务器配置。 @@ -28,9 +28,9 @@ function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promis ## 返回值 {#returns} -`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> +`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -一个解析为服务器配置的 Promise。 +一个 promise,解析为带有获取到元数据的静态服务器配置。 ## 参见 {#see} @@ -51,10 +51,10 @@ const oauthConfig = await fetchServerConfig('https://auth.logto.io/oauth', { typ const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); ``` -## 抛出异常 {#throws} +## 抛出 {#throws} 如果获取操作失败。 -## 抛出异常 {#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 index 6bdbc00..871ca9d 100644 --- 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 @@ -5,7 +5,7 @@ sidebar_label: fetchServerConfigByWellKnownUrl # 函数:fetchServerConfigByWellKnownUrl() ```ts -function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; +function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; ``` 从提供的 well-known URL 获取服务器配置,并根据 MCP 规范进行校验。 @@ -28,14 +28,14 @@ function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: Ser ## 返回值 {#returns} -`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> +`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -一个解析为服务器配置的 Promise。 +一个 promise,解析为带有获取到的元数据的静态服务器配置。 ## 抛出异常 {#throws} -如果获取操作失败,则抛出异常。 +如果获取操作失败。 ## 抛出异常 {#throws} -如果服务器元数据无效或不符合 MCP 规范,则抛出异常。 +如果服务器元数据无效或不符合 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 new file mode 100644 index 0000000..338c84c --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md @@ -0,0 +1,24 @@ +--- +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 index a2c3753..5b761ea 100644 --- 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 @@ -12,13 +12,13 @@ function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; 该中间件会从 `Authorization` 头中提取 Bearer 令牌,使用提供的 `verifyAccessToken` 函数进行验证,并检查发行者 (Issuer)、受众 (Audience) 和所需权限 (Scopes)。 -- 如果令牌有效,会将认证 (Authentication) 信息添加到 `request.auth` 属性中; +- 如果令牌有效,会将认证 (Authentication) 信息添加到 `request.auth` 属性; 如果无效,则返回相应的错误信息。 - 如果访问令牌 (Access token) 验证失败,则返回 401 未授权错误。 - 如果令牌不包含所需的权限 (Scopes),则返回 403 禁止访问错误。 - 如果在认证 (Authentication) 过程中发生意外错误,中间件会重新抛出这些错误。 -**注意:** `request.auth` 对象将包含比 `@modelcontextprotocol/sdk` 模块中定义的标准 AuthInfo 接口更多的扩展字段。详情请参见本文件中的扩展接口。 +**注意:** `request.auth` 对象会包含比 `@modelcontextprotocol/sdk` 模块中定义的标准 AuthInfo 接口更多的扩展字段。详细信息请参见本文件中的扩展接口。 ## 参数 {#parameters} @@ -36,4 +36,4 @@ Bearer 认证 (Authentication) 处理器的配置。 ## 参见 {#see} -[BearerAuthConfig](/references/js/type-aliases/BearerAuthConfig.md) 以获取配置选项。 +[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 index 61f9c4c..36b0b97 100644 --- 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 @@ -5,44 +5,13 @@ sidebar_label: AuthServerConfig # 类型别名:AuthServerConfig ```ts -type AuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; - type: AuthServerType; -}; +type AuthServerConfig = + | ResolvedAuthServerConfig + | AuthServerDiscoveryConfig; ``` -与 MCP 服务器集成的远程授权服务器 (Authorization Server) 的配置。 +与 MCP 服务器集成的远程授权服务器 (Authorization server) 配置。 -## 属性 {#properties} - -### metadata {#metadata} - -```ts -metadata: CamelCaseAuthorizationServerMetadata; -``` - -授权服务器 (Authorization Server) 的元数据,需符合 MCP 规范 -(基于 OAuth 2.0 授权服务器元数据 (Authorization Server Metadata))。 - -该元数据通常从服务器的 well-known 端点(OAuth 2.0 授权服务器元数据 (Authorization Server Metadata) 或 OpenID Connect Discovery)获取;如果服务器不支持这些端点,也可以直接在配置中提供。 - -**注意:** 元数据应采用 camelCase 格式,这是 mcp-auth 库推荐的格式。 - -#### 参见 {#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} - -[AuthServerType](/references/js/type-aliases/AuthServerType.md) 以获取可能的取值。 +可以是以下两种之一: +- **已解析(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 index f442d8f..94d1e9c 100644 --- 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 @@ -22,7 +22,7 @@ type AuthServerConfigError = { optional cause: Error; ``` -错误的可选原因,通常是一个 `Error` 实例,用于提供更多上下文信息。 +错误的可选原因,通常是 `Error` 的实例,用于提供更多上下文信息。 *** 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 index a73ff3c..ec6df03 100644 --- 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 @@ -11,7 +11,7 @@ type AuthServerConfigWarning = { }; ``` -表示在验证授权服务器元数据期间发生的警告。 +表示在验证授权服务器元数据时发生的警告。 ## 属性 {#properties} @@ -31,4 +31,4 @@ code: AuthServerConfigWarningCode; description: string; ``` -对警告的人类可读描述。 +该警告的人类可读描述。 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 new file mode 100644 index 0000000..e43d00a --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md @@ -0,0 +1,57 @@ +--- +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/AuthorizationServerMetadata.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md index 3d7b45f..52c5694 100644 --- 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 @@ -5,218 +5,10 @@ sidebar_label: AuthorizationServerMetadata # 类型别名:AuthorizationServerMetadata ```ts -type AuthorizationServerMetadata = { - authorization_endpoint: string; - code_challenge_methods_supported?: string[]; - grant_types_supported?: string[]; - introspection_endpoint?: string; - introspection_endpoint_auth_methods_supported?: string[]; - introspection_endpoint_auth_signing_alg_values_supported?: string[]; - issuer: string; - jwks_uri?: string; - op_policy_uri?: string; - op_tos_uri?: string; - registration_endpoint?: string; - response_modes_supported?: string[]; - response_types_supported: string[]; - revocation_endpoint?: string; - revocation_endpoint_auth_methods_supported?: string[]; - revocation_endpoint_auth_signing_alg_values_supported?: string[]; - scopes_supported?: string[]; - service_documentation?: string; - token_endpoint: string; - token_endpoint_auth_methods_supported?: string[]; - token_endpoint_auth_signing_alg_values_supported?: string[]; - ui_locales_supported?: string[]; - userinfo_endpoint?: string; -}; +type AuthorizationServerMetadata = z.infer; ``` -OAuth 2.0 授权服务器元数据(Authorization Server Metadata)的模式,定义见 RFC 8414。 - -## 类型声明 {#type-declaration} - -### authorization\_endpoint {#authorization-endpoint} - -```ts -authorization_endpoint: string; -``` - -授权服务器的授权端点(authorization endpoint)的 URL [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]。 -除非不支持任何使用授权端点的授权类型,否则这是必需的。 - -#### 参考 {#see} - -https://rfc-editor.org/rfc/rfc6749#section-3.1 - -### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} - -```ts -optional code_challenge_methods_supported: string[]; -``` - -包含此授权服务器支持的 Proof Key for Code Exchange (PKCE) [[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] code challenge 方法列表的 JSON 数组。 - -### grant\_types\_supported? {#grant-types-supported} - -```ts -optional grant_types_supported: string[]; -``` - -包含此授权服务器支持的 OAuth 2.0 授权类型(grant type)值列表的 JSON 数组。数组中的值与 "OAuth 2.0 动态客户端注册协议" [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)] 中 `grant_types` 参数使用的值相同。 -如果省略,默认值为 `["authorization_code", "implicit"]`。 - -### introspection\_endpoint? {#introspection-endpoint} - -```ts -optional introspection_endpoint: string; -``` - -授权服务器的 OAuth 2.0 introspection 端点的 URL [[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]。 - -### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} - -```ts -optional introspection_endpoint_auth_methods_supported: string[]; -``` - -### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} - -```ts -optional introspection_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### issuer {#issuer} - -```ts -issuer: string; -``` - -授权服务器的发行者 (Issuer) 标识符,是一个使用 `https` 协议且没有查询或片段组件的 URL。 - -### jwks\_uri? {#jwks-uri} - -```ts -optional jwks_uri: string; -``` - -授权服务器的 JWK Set [[JWK](https://www.rfc-editor.org/rfc/rfc8414.html#ref-JWK)] 文档的 URL。被引用的文档包含客户端用于验证授权服务器签名的密钥。此 URL 必须使用 `https` 协议。 - -### op\_policy\_uri? {#op-policy-uri} - -```ts -optional op_policy_uri: string; -``` - -### op\_tos\_uri? {#op-tos-uri} - -```ts -optional op_tos_uri: string; -``` - -### registration\_endpoint? {#registration-endpoint} - -```ts -optional registration_endpoint: string; -``` - -授权服务器的 OAuth 2.0 动态客户端注册端点的 URL [[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]。 - -### response\_modes\_supported? {#response-modes-supported} - -```ts -optional response_modes_supported: string[]; -``` - -包含此授权服务器支持的 OAuth 2.0 `response_mode` 值列表的 JSON 数组,详见 "OAuth 2.0 多响应类型编码实践" -[[OAuth.Responses](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Responses)]。 - -如果省略,默认值为 `["query", "fragment"]`。响应模式值 `"form_post"` 也在 "OAuth 2.0 表单提交响应模式" -[[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)] 中定义。 - -### response\_types\_supported {#response-types-supported} - -```ts -response_types_supported: string[]; -``` - -包含此授权服务器支持的 OAuth 2.0 `response_type` 值列表的 JSON 数组。数组中的值与 "OAuth 2.0 动态客户端注册协议" -[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)] 中 `response_types` 参数使用的值相同。 - -### revocation\_endpoint? {#revocation-endpoint} - -```ts -optional revocation_endpoint: string; -``` - -授权服务器的 OAuth 2.0 撤销端点(revocation endpoint)的 URL [[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]。 - -### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} - -```ts -optional revocation_endpoint_auth_methods_supported: string[]; -``` - -### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} - -```ts -optional revocation_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### scopes\_supported? {#scopes-supported} - -```ts -optional scopes_supported: string[]; -``` - -包含此授权服务器支持的 OAuth 2.0 `scope` 值列表的 JSON 数组。 -[[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] - -### service\_documentation? {#service-documentation} - -```ts -optional service_documentation: string; -``` - -### token\_endpoint {#token-endpoint} - -```ts -token_endpoint: string; -``` - -授权服务器的令牌端点(token endpoint)的 URL [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]。 -除非只支持 implicit 授权类型,否则这是必需的。 - -#### 参考 {#see} - -https://rfc-editor.org/rfc/rfc6749#section-3.2 - -### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} - -```ts -optional token_endpoint_auth_methods_supported: string[]; -``` - -### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} - -```ts -optional token_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### ui\_locales\_supported? {#ui-locales-supported} - -```ts -optional ui_locales_supported: string[]; -``` - -### userinfo\_endpoint? {#userinfo-endpoint} - -```ts -optional userinfo_endpoint: string; -``` - -OpenID Connect [userinfo 端点](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo) 的 URL。 -该端点用于获取已认证用户的信息。 +OAuth 2.0 授权服务器元数据 (Authorization Server Metadata) 的模式,定义见 RFC 8414。 ## 参考 {#see} 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 index f0308cd..edd3620 100644 --- 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 @@ -26,7 +26,7 @@ optional audience: string; 访问令牌 (Access token) 的预期受众 (Audience)(`aud` 声明 (Claim))。这通常是令牌所针对的资源服务器(API)。如果未提供,将跳过受众 (Audience) 检查。 -**注意:** 如果你的授权服务器 (Authorization server) 不支持资源指示器 (Resource Indicators)(RFC 8707),你可以省略此字段,因为受众 (Audience) 可能并不相关。 +**注意:** 如果你的授权服务器不支持资源指示器 (Resource Indicators)(RFC 8707),你可以省略此字段,因为受众 (Audience) 可能不相关。 #### 参见 {#see} @@ -50,7 +50,7 @@ issuer: #### 参见 {#see} -[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) 了解有关验证函数的更多细节。 +[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) 以获取有关验证函数的更多详细信息。 *** @@ -60,9 +60,9 @@ issuer: optional requiredScopes: string[]; ``` -访问令牌 (Access token) 必须包含的权限 (Scopes) 数组。如果令牌未包含所有这些权限 (Scopes),将抛出错误。 +访问令牌 (Access token) 必须具备的权限 (Scopes) 数组。如果令牌未包含所有这些权限 (Scopes),将抛出错误。 -**注意:** 处理器将检查令牌中的 `scope` 声明 (Claim),该声明 (Claim) 可能是以空格分隔的字符串或字符串数组,具体取决于授权服务器 (Authorization server) 的实现。如果未包含 `scope` 声明 (Claim),处理器将检查 `scopes` 声明 (Claim)(如果可用)。 +**注意:** 处理程序会检查令牌中的 `scope` 声明 (Claim),该声明 (Claim) 可能是以空格分隔的字符串或字符串数组,具体取决于授权服务器的实现。如果未包含 `scope` 声明 (Claim),处理程序会检查 `scopes` 声明 (Claim)(如果可用)。 *** @@ -72,7 +72,7 @@ optional requiredScopes: string[]; optional resource: string; ``` -受保护资源的标识符。当提供该字段时,处理器将使用为此资源配置的授权服务器 (Authorization server) 验证收到的令牌。在使用带有 `protectedResources` 配置的处理器时是必需的。 +受保护资源的标识符。当提供该字段时,处理程序将使用为此资源配置的授权服务器来验证收到的令牌。在使用带有 `protectedResources` 配置的处理程序时是必需的。 *** @@ -104,4 +104,4 @@ verifyAccessToken: VerifyAccessTokenFunction; #### 参见 {#see} -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) 了解更多细节。 +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) 以获取更多详细信息。 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 index 21dee17..ef9d329 100644 --- 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 @@ -5,175 +5,11 @@ sidebar_label: CamelCaseAuthorizationServerMetadata # 类型别名:CamelCaseAuthorizationServerMetadata ```ts -type CamelCaseAuthorizationServerMetadata = { - authorizationEndpoint: string; - codeChallengeMethodsSupported?: string[]; - grantTypesSupported?: string[]; - introspectionEndpoint?: string; - introspectionEndpointAuthMethodsSupported?: string[]; - introspectionEndpointAuthSigningAlgValuesSupported?: string[]; - issuer: string; - jwksUri?: string; - opPolicyUri?: string; - opTosUri?: string; - registrationEndpoint?: string; - responseModesSupported?: string[]; - responseTypesSupported: string[]; - revocationEndpoint?: string; - revocationEndpointAuthMethodsSupported?: string[]; - revocationEndpointAuthSigningAlgValuesSupported?: string[]; - scopesSupported?: string[]; - serviceDocumentation?: string; - tokenEndpoint: string; - tokenEndpointAuthMethodsSupported?: string[]; - tokenEndpointAuthSigningAlgValuesSupported?: string[]; - uiLocalesSupported?: string[]; - userinfoEndpoint?: string; -}; +type CamelCaseAuthorizationServerMetadata = z.infer; ``` -OAuth 2.0 授权服务器元数据类型的 camelCase 版本。 - -## 类型声明 {#type-declaration} - -### authorizationEndpoint {#authorizationendpoint} - -```ts -authorizationEndpoint: string; -``` - -### codeChallengeMethodsSupported? {#codechallengemethodssupported} - -```ts -optional codeChallengeMethodsSupported: string[]; -``` - -### grantTypesSupported? {#granttypessupported} - -```ts -optional grantTypesSupported: string[]; -``` - -### introspectionEndpoint? {#introspectionendpoint} - -```ts -optional introspectionEndpoint: string; -``` - -### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} - -```ts -optional introspectionEndpointAuthMethodsSupported: string[]; -``` - -### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} - -```ts -optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### issuer {#issuer} - -```ts -issuer: string; -``` - -### jwksUri? {#jwksuri} - -```ts -optional jwksUri: string; -``` - -### opPolicyUri? {#oppolicyuri} - -```ts -optional opPolicyUri: string; -``` - -### opTosUri? {#optosuri} - -```ts -optional opTosUri: string; -``` - -### registrationEndpoint? {#registrationendpoint} - -```ts -optional registrationEndpoint: string; -``` - -### responseModesSupported? {#responsemodessupported} - -```ts -optional responseModesSupported: string[]; -``` - -### responseTypesSupported {#responsetypessupported} - -```ts -responseTypesSupported: string[]; -``` - -### revocationEndpoint? {#revocationendpoint} - -```ts -optional revocationEndpoint: string; -``` - -### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} - -```ts -optional revocationEndpointAuthMethodsSupported: string[]; -``` - -### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} - -```ts -optional revocationEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### scopesSupported? {#scopessupported} - -```ts -optional scopesSupported: string[]; -``` - -### serviceDocumentation? {#servicedocumentation} - -```ts -optional serviceDocumentation: string; -``` - -### tokenEndpoint {#tokenendpoint} - -```ts -tokenEndpoint: string; -``` - -### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} - -```ts -optional tokenEndpointAuthMethodsSupported: string[]; -``` - -### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} - -```ts -optional tokenEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### uiLocalesSupported? {#uilocalessupported} - -```ts -optional uiLocalesSupported: string[]; -``` - -### userinfoEndpoint? {#userinfoendpoint} - -```ts -optional userinfoEndpoint: string; -``` +OAuth 2.0 授权服务器元数据 (Authorization Server Metadata) 类型的 camelCase 版本。 ## 参见 {#see} -[AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) 以获取原始类型和字段信息。 +[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 index dfcb8ea..7cbb4f0 100644 --- 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 @@ -5,118 +5,10 @@ sidebar_label: CamelCaseProtectedResourceMetadata # 类型别名:CamelCaseProtectedResourceMetadata ```ts -type CamelCaseProtectedResourceMetadata = { - authorizationDetailsTypesSupported?: string[]; - authorizationServers?: string[]; - bearerMethodsSupported?: string[]; - dpopBoundAccessTokensRequired?: boolean; - dpopSigningAlgValuesSupported?: string[]; - jwksUri?: string; - resource: string; - resourceDocumentation?: string; - resourceName?: string; - resourcePolicyUri?: string; - resourceSigningAlgValuesSupported?: string[]; - resourceTosUri?: string; - scopesSupported?: string[]; - signedMetadata?: string; - tlsClientCertificateBoundAccessTokens?: boolean; -}; +type CamelCaseProtectedResourceMetadata = z.infer; ``` -OAuth 2.0 Protected Resource Metadata 类型的 camelCase 版本。 - -## 类型声明 {#type-declaration} - -### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} - -```ts -optional authorizationDetailsTypesSupported: string[]; -``` - -### authorizationServers? {#authorizationservers} - -```ts -optional authorizationServers: string[]; -``` - -### bearerMethodsSupported? {#bearermethodssupported} - -```ts -optional bearerMethodsSupported: string[]; -``` - -### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} - -```ts -optional dpopBoundAccessTokensRequired: boolean; -``` - -### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} - -```ts -optional dpopSigningAlgValuesSupported: string[]; -``` - -### jwksUri? {#jwksuri} - -```ts -optional jwksUri: string; -``` - -### resource {#resource} - -```ts -resource: string; -``` - -### resourceDocumentation? {#resourcedocumentation} - -```ts -optional resourceDocumentation: string; -``` - -### resourceName? {#resourcename} - -```ts -optional resourceName: string; -``` - -### resourcePolicyUri? {#resourcepolicyuri} - -```ts -optional resourcePolicyUri: string; -``` - -### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} - -```ts -optional resourceSigningAlgValuesSupported: string[]; -``` - -### resourceTosUri? {#resourcetosuri} - -```ts -optional resourceTosUri: string; -``` - -### scopesSupported? {#scopessupported} - -```ts -optional scopesSupported: string[]; -``` - -### signedMetadata? {#signedmetadata} - -```ts -optional signedMetadata: string; -``` - -### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} - -```ts -optional tlsClientCertificateBoundAccessTokens: boolean; -``` +OAuth 2.0 受保护资源元数据类型的 camelCase 版本。 ## 参见 {#see} 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 index ba8c708..db7b426 100644 --- 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 @@ -5,146 +5,7 @@ sidebar_label: ProtectedResourceMetadata # 类型别名:ProtectedResourceMetadata ```ts -type ProtectedResourceMetadata = { - authorization_details_types_supported?: string[]; - authorization_servers?: string[]; - bearer_methods_supported?: string[]; - dpop_bound_access_tokens_required?: boolean; - dpop_signing_alg_values_supported?: string[]; - jwks_uri?: string; - resource: string; - resource_documentation?: string; - resource_name?: string; - resource_policy_uri?: string; - resource_signing_alg_values_supported?: string[]; - resource_tos_uri?: string; - scopes_supported?: string[]; - signed_metadata?: string; - tls_client_certificate_bound_access_tokens?: boolean; -}; +type ProtectedResourceMetadata = z.infer; ``` -OAuth 2.0 受保护资源元数据的模式定义。 - -## 类型声明 {#type-declaration} - -### authorization\_details\_types\_supported? {#authorization-details-types-supported} - -```ts -optional authorization_details_types_supported: string[]; -``` - -在使用 authorization_details 请求参数时支持的授权详情类型值。 - -### authorization\_servers? {#authorization-servers} - -```ts -optional authorization_servers: string[]; -``` - -可与此受保护资源一起使用的 OAuth 授权 (Authorization) 服务器发行者标识符列表。 - -### bearer\_methods\_supported? {#bearer-methods-supported} - -```ts -optional bearer_methods_supported: string[]; -``` - -支持的 OAuth 2.0 持有者令牌发送方式。可选值:["header", "body", "query"]。 - -### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} - -```ts -optional dpop_bound_access_tokens_required: boolean; -``` - -该受保护资源是否始终要求 DPoP 绑定访问令牌 (Access token)。 - -### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} - -```ts -optional dpop_signing_alg_values_supported: string[]; -``` - -用于验证 DPoP 证明 JWT 的 JWS 算法。 - -### jwks\_uri? {#jwks-uri} - -```ts -optional jwks_uri: string; -``` - -受保护资源的 JSON Web Key (JWK) 集合文档的 URL。该文档包含可用于验证该受保护资源返回的响应或数据数字签名的公钥。 -这与授权 (Authorization) 服务器的 jwks_uri 不同,后者用于令牌验证。当受保护资源对其响应进行签名时,客户端可以获取这些公钥以验证接收数据的真实性和完整性。 - -### resource {#resource} - -```ts -resource: string; -``` - -受保护资源的资源标识符。 - -### resource\_documentation? {#resource-documentation} - -```ts -optional resource_documentation: string; -``` - -包含用于开发者使用该受保护资源的文档的 URL。 - -### resource\_name? {#resource-name} - -```ts -optional resource_name: string; -``` - -用于展示给终端用户的受保护资源的人类可读名称。 - -### resource\_policy\_uri? {#resource-policy-uri} - -```ts -optional resource_policy_uri: string; -``` - -包含受保护资源数据使用要求信息的 URL。 - -### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} - -```ts -optional resource_signing_alg_values_supported: string[]; -``` - -受保护资源用于对资源响应进行签名所支持的 JWS 签名算法。 - -### resource\_tos\_uri? {#resource-tos-uri} - -```ts -optional resource_tos_uri: string; -``` - -包含受保护资源服务条款的 URL。 - -### scopes\_supported? {#scopes-supported} - -```ts -optional scopes_supported: string[]; -``` - -在授权 (Authorization) 请求中用于访问该受保护资源的权限 (Scope) 值列表。 - -### signed\_metadata? {#signed-metadata} - -```ts -optional signed_metadata: string; -``` - -包含元数据参数作为声明 (Claim) 的已签名 JWT。该 JWT 必须使用 JWS 签名,并包含 'iss' 声明 (Claim)。此字段提供了一种加密方式来验证元数据本身的真实性。签名可通过 `jwks_uri` 端点提供的公钥进行验证。当存在时,该已签名元数据中的值优先于本元数据文档中对应的普通 JSON 值。这有助于防止资源元数据被篡改。 - -### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} - -```ts -optional tls_client_certificate_bound_access_tokens: boolean; -``` - -该受保护资源是否支持基于双向 TLS 客户端证书绑定的访问令牌 (Access token)。 +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 new file mode 100644 index 0000000..35f66b4 --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md @@ -0,0 +1,49 @@ +--- +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/ValidateIssuerFunction.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/type-aliases/ValidateIssuerFunction.md index 97920bc..2168813 100644 --- 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 @@ -8,7 +8,7 @@ sidebar_label: ValidateIssuerFunction type ValidateIssuerFunction = (tokenIssuer: string) => void; ``` -用于验证访问令牌 (Access token) 的发行者 (Issuer) 的函数类型。 +用于验证访问令牌 (Access token) 发行者 (Issuer) 的函数类型。 如果发行者 (Issuer) 无效,此函数应抛出一个带有代码 'invalid_issuer' 的 [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md)。发行者 (Issuer) 应根据以下内容进行验证: @@ -21,10 +21,10 @@ type ValidateIssuerFunction = (tokenIssuer: string) => void; `string` -## 返回 {#returns} +## 返回值 {#returns} `void` ## 抛出 {#throws} -当发行者 (Issuer) 未被识别或无效时。 +当发行者 (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 index 9e24845..514817a 100644 --- 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 @@ -15,7 +15,7 @@ type VerifyAccessTokenFunction = (token: string) => MaybePromise; 例如,如果你有一个 JWT 验证函数,它至少应检查令牌的签名、验证其过期时间,并提取必要的声明 (Claims) 以返回一个 `AuthInfo` 对象。 -**注意:** 无需验证令牌中的以下字段,因为它们会由处理程序进行检查: +**注意:** 无需验证令牌中的以下字段,因为它们会由处理程序检查: - `iss`(发行者 (Issuer)) - `aud`(受众 (Audience)) @@ -33,4 +33,4 @@ type VerifyAccessTokenFunction = (token: string) => MaybePromise; `MaybePromise`\<`AuthInfo`\> -一个 Promise(或同步值),当令牌有效时解析为 AuthInfo 对象。 +一个 Promise,当令牌有效时解析为 AuthInfo 对象,或同步返回该对象。 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 index 1840b81..95c6120 100644 --- 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 @@ -5,10 +5,34 @@ sidebar_label: authorizationServerMetadataSchema # 变量:authorizationServerMetadataSchema ```ts -const authorizationServerMetadataSchema: ZodObject; +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。 +用于 OAuth 2.0 授权服务器元数据(Authorization Server Metadata)的 Zod schema,定义见 RFC 8414。 ## 参考 {#see} 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 index d42244a..e969080 100644 --- 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 @@ -5,10 +5,34 @@ sidebar_label: camelCaseAuthorizationServerMetadataSchema # 变量:camelCaseAuthorizationServerMetadataSchema ```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject; +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 版本。 +OAuth 2.0 授权服务器元数据 Zod schema 的 camelCase 版本。 ## 参见 {#see} 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 index e05876b..9766dba 100644 --- 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 @@ -5,11 +5,27 @@ sidebar_label: camelCaseProtectedResourceMetadataSchema # 变量:camelCaseProtectedResourceMetadataSchema ```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject; +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 和字段信息。 +[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/protectedResourceMetadataSchema.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md index b108660..6b6f99b 100644 --- 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 @@ -5,7 +5,23 @@ sidebar_label: protectedResourceMetadataSchema # 变量:protectedResourceMetadataSchema ```ts -const protectedResourceMetadataSchema: ZodObject; +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-TW/docusaurus-plugin-content-docs/current/references/js/README.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/README.md index 58a91d0..25fb0f5 100644 --- 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 @@ -2,9 +2,9 @@ sidebar_label: Node.js SDK --- -# MCP Auth Node.js SDK 參考文件 +# MCP Auth Node.js SDK 參考文件 (MCP Auth Node.js SDK reference) -## 類別 {#classes} +## 類別 (Classes) {#classes} - [MCPAuth](/references/js/classes/MCPAuth.md) - [MCPAuthAuthServerError](/references/js/classes/MCPAuthAuthServerError.md) @@ -13,7 +13,7 @@ sidebar_label: Node.js SDK - [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) @@ -21,6 +21,7 @@ sidebar_label: Node.js SDK - [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) @@ -33,12 +34,13 @@ sidebar_label: Node.js SDK - [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) {#variables} - [authorizationServerMetadataSchema](/references/js/variables/authorizationServerMetadataSchema.md) - [authServerErrorDescription](/references/js/variables/authServerErrorDescription.md) @@ -51,9 +53,10 @@ sidebar_label: Node.js SDK - [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) 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 index 4dff6e8..d7772a5 100644 --- 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 @@ -4,27 +4,54 @@ sidebar_label: MCPAuth # 類別:MCPAuth -mcp-auth 函式庫的主要類別。它作為工廠與註冊中心,用於建立你受保護資源的驗證 (Authentication) 政策。 +mcp-auth 函式庫的主要類別。它作為工廠與註冊中心,用於建立受保護資源的驗證 (Authentication) 原則。 初始化時需傳入伺服器設定,並提供 `bearerAuth` 方法,用於產生基於權杖的 Express 中介軟體(middleware)。 ## 範例 {#example} -### 在 `resource server` 模式下的用法 {#usage-in-resource-server-mode} +### 在 `資源伺服器 (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, fetchServerConfig } from 'mcp-auth'; +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` 可以是單一設定物件或其陣列。 protectedResources: [ { metadata: { @@ -35,8 +62,12 @@ const mcpAuth = new MCPAuth({ }, ], }); +``` + +#### 使用中介軟體 {#using-the-middleware} -// 掛載路由以處理受保護資源中繼資料 +```ts +// 掛載路由以處理 Protected Resource Metadata app.use(mcpAuth.protectedResourceMetadataRouter()); // 保護已設定資源的 API 端點 @@ -44,7 +75,7 @@ app.get( '/notes', mcpAuth.bearerAuth('jwt', { resource: resourceIdentifier, // 指定此端點所屬資源 - audience: resourceIdentifier, // 可選,驗證 'aud' 宣告 (Claim) + audience: resourceIdentifier, // 可選,驗證 'aud' 宣告 (claim) requiredScopes: ['read:notes'], }), (req, res) => { @@ -54,26 +85,24 @@ app.get( ); ``` -### 傳統 `authorization server` 模式用法(已棄用) {#legacy-usage-in-authorization-server-mode-deprecated} +### 傳統 `授權伺服器 (authorization server)` 模式用法(已棄用) {#legacy-usage-in-authorization-server-mode-deprecated} -此做法為相容舊系統而保留。 +此方式為相容舊版而保留。 ```ts import express from 'express'; -import { MCPAuth, fetchServerConfig } from 'mcp-auth'; +import { MCPAuth } from 'mcp-auth'; const app = express(); const mcpAuth = new MCPAuth({ - server: await fetchServerConfig( - 'https://auth.logto.io/oidc', - { type: 'oidc' } - ), + // 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'] }), @@ -93,7 +122,7 @@ new MCPAuth(config: MCPAuthConfig): MCPAuth; ``` 建立 MCPAuth 實例。 -會預先驗證整份設定,若有錯誤可及早失敗。 +會在初始化時即驗證整份設定,錯誤會立即拋出。 #### 參數 {#parameters} @@ -127,7 +156,7 @@ readonly config: MCPAuthConfig; bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit): RequestHandler; ``` -建立一個 Bearer 權杖驗證處理器(Express 中介軟體),用於驗證請求的 `Authorization` 標頭中的存取權杖 (Access token)。 +建立一個 Bearer 權杖驗證處理器(Express 中介軟體),用於驗證請求 `Authorization` 標頭中的存取權杖 (Access token)。 ##### 參數 {#parameters} @@ -135,17 +164,17 @@ bearerAuth(verifyAccessToken: VerifyAccessTokenFunction, config?: Omit -Bearer 權杖驗證處理器的選用設定。 +Bearer 權杖驗證處理器的可選設定。 **參見** @@ -155,7 +184,7 @@ Bearer 權杖驗證處理器的選用設定。 `RequestHandler` -一個 Express 中介軟體函式,會驗證存取權杖 (Access token) 並將驗證結果加入請求物件(`req.auth`)。 +一個 Express 中介軟體函式,會驗證存取權杖 (Access token) 並將驗證結果加到請求物件 (`req.auth`) 上。 ##### 參見 {#see} @@ -169,7 +198,7 @@ bearerAuth(mode: "jwt", config?: Omit & `VerifyJwtConfig` -Bearer 權杖驗證處理器的選用設定,包含 JWT 驗證選項與遠端 JWK Set 選項。 +Bearer 權杖驗證處理器的可選設定,包含 JWT 驗證選項與遠端 JWK set 選項。 **參見** @@ -198,15 +227,15 @@ Bearer 權杖驗證處理器的選用設定,包含 JWT 驗證選項與遠端 J `RequestHandler` -一個 Express 中介軟體函式,會驗證存取權杖 (Access token) 並將驗證結果加入請求物件(`req.auth`)。 +一個 Express 中介軟體函式,會驗證存取權杖 (Access token) 並將驗證結果加到請求物件 (`req.auth`) 上。 ##### 參見 {#see} [handleBearerAuth](/references/js/functions/handleBearerAuth.md) 以瞭解實作細節與 `req.auth`(`AuthInfo`)物件的擴充型別。 -##### 例外 {#throws} +##### 拋出 {#throws} -若在 `'jwt'` 模式下伺服器中繼資料未提供 JWKS URI,則會拋出例外。 +若在 `'jwt'` 模式下伺服器 metadata 未提供 JWKS URI,則會拋出錯誤。 *** @@ -216,14 +245,14 @@ Bearer 權杖驗證處理器的選用設定,包含 JWT 驗證選項與遠端 J delegatedRouter(): Router; ``` -建立一個代理路由器,用於提供舊版 OAuth 2.0 授權伺服器中繼資料端點 -(`/.well-known/oauth-authorization-server`),並使用實例提供的中繼資料。 +建立一個 delegated router,用於提供舊版 OAuth 2.0 授權伺服器 (Authorization Server) Metadata 端點 +(`/.well-known/oauth-authorization-server`),內容來自實例設定的 metadata。 #### 回傳 {#returns} `Router` -一個路由器,會以實例提供的中繼資料服務 OAuth 2.0 授權伺服器中繼資料端點。 +一個提供 OAuth 2.0 授權伺服器 Metadata 端點的路由器,內容來自實例設定的 metadata。 #### 已棄用 {#deprecated} @@ -240,9 +269,9 @@ const mcpAuth: MCPAuth; // 假設已初始化 app.use(mcpAuth.delegatedRouter()); ``` -#### 例外 {#throws} +#### 拋出 {#throws} -若於 `resource server` 模式下呼叫會拋出例外。 +若於 `資源伺服器 (resource server)` 模式下呼叫會拋出錯誤。 *** @@ -252,7 +281,7 @@ app.use(mcpAuth.delegatedRouter()); protectedResourceMetadataRouter(): Router; ``` -建立一個路由器,為所有已設定資源提供 OAuth 2.0 受保護資源中繼資料端點。 +建立一個路由器,為所有已設定資源提供 OAuth 2.0 Protected Resource Metadata 端點。 此路由器會根據你設定的資源識別符,自動建立正確的 `.well-known` 端點。 @@ -260,11 +289,11 @@ protectedResourceMetadataRouter(): Router; `Router` -一個路由器,會服務 OAuth 2.0 受保護資源中繼資料端點。 +一個提供 OAuth 2.0 Protected Resource Metadata 端點的路由器。 -#### 例外 {#throws} +#### 拋出 {#throws} -若於 `authorization server` 模式下呼叫會拋出例外。 +若於 `授權伺服器 (authorization server)` 模式下呼叫會拋出錯誤。 #### 範例 {#example} @@ -276,6 +305,6 @@ import { MCPAuth } from 'mcp-auth'; const mcpAuth: MCPAuth; const app = express(); -// 這會根據你的資源識別符,在 `/.well-known/oauth-protected-resource/...` 提供中繼資料 +// 這會根據你的資源識別符,在 `/.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 index 68bd37b..e7cd90a 100644 --- 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 @@ -100,17 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` 屬性指定堆疊追蹤(無論是由 `new Error().stack` 或 `Error.captureStackTrace(obj)` 產生)所收集的堆疊框架數量。 +可選的堆疊追蹤格式化覆寫方法 + +#### 參數 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -預設值為 `10`,但可設為任何有效的 JavaScript 數字。變更後將影響之後捕獲的所有堆疊追蹤。 +`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} @@ -132,7 +158,8 @@ toJson(showCause: boolean): Record; `boolean` = `false` -是否在 JSON 回應中包含錯誤原因。預設為 `false`。 +是否在 JSON 回應中包含錯誤原因。 +預設為 `false`。 #### 回傳 {#returns} @@ -150,43 +177,7 @@ toJson(showCause: boolean): Record; static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -在 `targetObject` 上建立 `.stack` 屬性,當存取時會回傳一個字串,表示呼叫 `Error.captureStackTrace()` 時的程式碼位置。 - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // 類似於 `new Error().stack` -``` - -追蹤的第一行會以 `${myObject.name}: ${myObject.message}` 為前綴。 - -可選的 `constructorOpt` 參數接受一個函式。如果提供,則所有在 `constructorOpt` 之上的堆疊框架(包含 `constructorOpt`)都會從產生的堆疊追蹤中省略。 - -`constructorOpt` 參數有助於隱藏錯誤產生的實作細節。例如: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // 建立一個沒有堆疊追蹤的錯誤,以避免重複計算堆疊追蹤。 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 捕獲 function b 之上的堆疊追蹤 - Error.captureStackTrace(error, b); // 堆疊追蹤中不包含 function c 與 b - throw error; -} - -a(); -``` +在目標物件上建立 .stack 屬性 #### 參數 {#parameters} @@ -205,33 +196,3 @@ a(); #### 繼承自 {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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) 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 index 3e0d659..1763134 100644 --- 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 @@ -32,7 +32,7 @@ new MCPAuthBearerAuthError(code: BearerAuthErrorCode, cause?: MCPAuthBearerAuthE `MCPAuthBearerAuthError` -#### 覆寫 {#overrides} +#### 覆寫自 {#overrides} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`constructor`](/references/js/classes/MCPAuthError.md#constructor) @@ -82,7 +82,7 @@ message: string; name: string = 'MCPAuthBearerAuthError'; ``` -#### 覆寫 {#overrides} +#### 覆寫自 {#overrides} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`name`](/references/js/classes/MCPAuthError.md#name) @@ -100,17 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` 屬性指定堆疊追蹤(無論是由 `new Error().stack` 或 `Error.captureStackTrace(obj)` 產生)所收集的堆疊框架數量。 +可選的堆疊追蹤格式化覆寫 + +#### 參數 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 回傳 {#returns} + +`any` + +#### 參考 {#see} -預設值為 `10`,但可以設為任何有效的 JavaScript 數字。變更後將影響之後所擷取的所有堆疊追蹤。 +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} @@ -132,13 +158,14 @@ toJson(showCause: boolean): Record; `boolean` = `false` -是否在 JSON 回應中包含錯誤原因。預設為 `false`。 +是否在 JSON 回應中包含錯誤原因。 +預設為 `false`。 #### 回傳 {#returns} `Record`\<`string`, `unknown`\> -#### 覆寫 {#overrides} +#### 覆寫自 {#overrides} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`toJson`](/references/js/classes/MCPAuthError.md#tojson) @@ -150,43 +177,7 @@ toJson(showCause: boolean): Record; static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -在 `targetObject` 上建立 `.stack` 屬性,當存取時會回傳一個字串,表示呼叫 `Error.captureStackTrace()` 時的程式碼位置。 - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // 類似於 `new Error().stack` -``` - -追蹤的第一行會以 `${myObject.name}: ${myObject.message}` 為前綴。 - -可選的 `constructorOpt` 參數接受一個函式。如果提供,則所有在 `constructorOpt` 之上的堆疊框架(包含 `constructorOpt`)都會從產生的堆疊追蹤中省略。 - -`constructorOpt` 參數可用於隱藏錯誤產生的實作細節。例如: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // 建立一個沒有堆疊追蹤的錯誤,以避免重複計算堆疊追蹤。 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 擷取 function b 之上的堆疊追蹤 - Error.captureStackTrace(error, b); // 堆疊追蹤中不包含 function c 與 b - throw error; -} - -a(); -``` +在目標物件上建立 .stack 屬性 #### 參數 {#parameters} @@ -205,33 +196,3 @@ a(); #### 繼承自 {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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) 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 index 2d225b6..755ad5a 100644 --- 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 @@ -4,7 +4,7 @@ sidebar_label: MCPAuthConfigError # 類別:MCPAuthConfigError -當 mcp-auth 發生設定問題時所拋出的錯誤。 +當 mcp-auth 配置出現問題時所拋出的錯誤。 ## 繼承自 {#extends} @@ -30,7 +30,7 @@ new MCPAuthConfigError(code: string, message: string): MCPAuthConfigError; `string` -錯誤的人類可讀描述。 +易於理解的錯誤描述。 #### 回傳 {#returns} @@ -104,17 +104,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` 屬性指定堆疊追蹤(無論是由 `new Error().stack` 或 `Error.captureStackTrace(obj)` 產生)所收集的堆疊框架數量。 +可選的堆疊追蹤格式化覆寫 + +#### 參數 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} -預設值為 `10`,但可設為任何有效的 JavaScript 數字。變更後會影響之後所擷取的所有堆疊追蹤。 +`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} @@ -136,7 +162,8 @@ toJson(showCause: boolean): Record; `boolean` = `false` -是否在 JSON 回應中包含錯誤原因。預設為 `false`。 +是否在 JSON 回應中包含錯誤原因。 +預設為 `false`。 #### 回傳 {#returns} @@ -154,43 +181,7 @@ toJson(showCause: boolean): Record; static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -在 `targetObject` 上建立 `.stack` 屬性,當存取時會回傳一個字串,表示呼叫 `Error.captureStackTrace()` 時在程式碼中的位置。 - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // 類似於 `new Error().stack` -``` - -追蹤的第一行會以 `${myObject.name}: ${myObject.message}` 為前綴。 - -可選的 `constructorOpt` 參數接受一個函式。如果提供,則所有在 `constructorOpt` 之上的堆疊框架(包含 `constructorOpt`)都會從產生的堆疊追蹤中省略。 - -`constructorOpt` 參數有助於隱藏錯誤產生的實作細節。例如: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // 建立一個沒有堆疊追蹤的錯誤,以避免重複計算堆疊追蹤。 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 擷取 function b 之上的堆疊追蹤 - Error.captureStackTrace(error, b); // 堆疊追蹤中不包含 function c 與 b - throw error; -} - -a(); -``` +在目標物件上建立 .stack 屬性 #### 參數 {#parameters} @@ -209,33 +200,3 @@ a(); #### 繼承自 {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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) 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 index 1900095..8516f21 100644 --- 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 @@ -12,7 +12,7 @@ sidebar_label: MCPAuthError - `Error` -## 被以下類別擴充 {#extended-by} +## 被繼承於 {#extended-by} - [`MCPAuthConfigError`](/references/js/classes/MCPAuthConfigError.md) - [`MCPAuthAuthServerError`](/references/js/classes/MCPAuthAuthServerError.md) @@ -39,13 +39,13 @@ new MCPAuthError(code: string, message: string): MCPAuthError; `string` -錯誤的人類可讀描述。 +易於理解的錯誤描述。 #### 回傳 {#returns} `MCPAuthError` -#### 覆寫 {#overrides} +#### 覆寫自 {#overrides} ```ts Error.constructor @@ -97,7 +97,7 @@ Error.message name: string = 'MCPAuthError'; ``` -#### 覆寫 {#overrides} +#### 覆寫自 {#overrides} ```ts Error.name @@ -119,17 +119,45 @@ Error.stack *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` 屬性指定堆疊追蹤(無論是由 `new Error().stack` 或 `Error.captureStackTrace(obj)` 產生)所收集的堆疊框架數量。 +可選的堆疊追蹤格式化覆寫方法 + +#### 參數 {#parameters} + +##### err {#err} -預設值為 `10`,但可以設為任何有效的 JavaScript 數字。更改後會影響之後捕獲的所有堆疊追蹤。 +`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} @@ -153,7 +181,7 @@ toJson(showCause: boolean): Record; `boolean` = `false` -是否在 JSON 回應中包含錯誤原因(cause)。 +是否在 JSON 回應中包含錯誤原因。 預設為 `false`。 #### 回傳 {#returns} @@ -168,43 +196,7 @@ toJson(showCause: boolean): Record; static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -在 `targetObject` 上建立 `.stack` 屬性,當存取時會回傳一個字串,表示呼叫 `Error.captureStackTrace()` 時的程式碼位置。 - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // 類似於 `new Error().stack` -``` - -追蹤的第一行會以 `${myObject.name}: ${myObject.message}` 為前綴。 - -可選的 `constructorOpt` 參數接受一個函式。如果提供,則所有在 `constructorOpt` 之上的堆疊框架(包含 `constructorOpt`)都會從產生的堆疊追蹤中省略。 - -`constructorOpt` 參數有助於隱藏錯誤產生的實作細節。例如: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // 建立一個沒有堆疊追蹤的錯誤,以避免重複計算堆疊追蹤。 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 捕獲 function b 之上的堆疊追蹤 - Error.captureStackTrace(error, b); // 堆疊追蹤中不包含 function c 與 b - throw error; -} - -a(); -``` +在目標物件上建立 .stack 屬性 #### 參數 {#parameters} @@ -225,35 +217,3 @@ a(); ```ts Error.captureStackTrace ``` - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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 -``` 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 index ab49f22..5592dd9 100644 --- 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 @@ -100,17 +100,43 @@ optional stack: string; *** -### stackTraceLimit {#stacktracelimit} +### prepareStackTrace()? {#preparestacktrace} ```ts -static stackTraceLimit: number; +static optional prepareStackTrace: (err: Error, stackTraces: CallSite[]) => any; ``` -`Error.stackTraceLimit` 屬性指定堆疊追蹤(stack trace)所收集的堆疊框架數量(無論是由 `new Error().stack` 或 `Error.captureStackTrace(obj)` 產生)。 +可選的堆疊追蹤格式化覆寫 + +#### 參數 {#parameters} + +##### err {#err} + +`Error` + +##### stackTraces {#stacktraces} + +`CallSite`[] + +#### 回傳 {#returns} + +`any` + +#### 參考 {#see} -預設值為 `10`,但可以設為任何有效的 JavaScript 數字。變更後會影響之後所擷取的所有堆疊追蹤。 +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} @@ -132,7 +158,7 @@ toJson(showCause: boolean): Record; `boolean` = `false` -是否在 JSON 回應中包含錯誤原因(cause)。 +是否在 JSON 回應中包含錯誤原因。 預設為 `false`。 #### 回傳 {#returns} @@ -151,43 +177,7 @@ toJson(showCause: boolean): Record; static captureStackTrace(targetObject: object, constructorOpt?: Function): void; ``` -在 `targetObject` 上建立 `.stack` 屬性,當存取時會回傳一個字串,表示呼叫 `Error.captureStackTrace()` 時的程式碼位置。 - -```js -const myObject = {}; -Error.captureStackTrace(myObject); -myObject.stack; // 類似於 `new Error().stack` -``` - -追蹤的第一行會加上 `${myObject.name}: ${myObject.message}` 前綴。 - -可選的 `constructorOpt` 參數接受一個函式。如果提供,則產生的堆疊追蹤中,`constructorOpt` 及其以上的所有框架都會被省略。 - -`constructorOpt` 參數可用於隱藏錯誤產生的實作細節。例如: - -```js -function a() { - b(); -} - -function b() { - c(); -} - -function c() { - // 建立一個沒有堆疊追蹤的錯誤,以避免重複計算堆疊追蹤。 - const { stackTraceLimit } = Error; - Error.stackTraceLimit = 0; - const error = new Error(); - Error.stackTraceLimit = stackTraceLimit; - - // 擷取 function b 以上的堆疊追蹤 - Error.captureStackTrace(error, b); // 堆疊追蹤中不包含 function c 與 b - throw error; -} - -a(); -``` +在目標物件上建立 .stack 屬性 #### 參數 {#parameters} @@ -206,33 +196,3 @@ a(); #### 繼承自 {#inherited-from} [`MCPAuthError`](/references/js/classes/MCPAuthError.md).[`captureStackTrace`](/references/js/classes/MCPAuthError.md#capturestacktrace) - -*** - -### prepareStackTrace() {#preparestacktrace} - -```ts -static 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) 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 index cabf98e..40858f0 100644 --- 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 @@ -8,7 +8,7 @@ sidebar_label: createVerifyJwt function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): VerifyAccessTokenFunction; ``` -建立一個函式,使用提供的金鑰取得函式與選項來驗證 JWT 存取權杖 (Access token)。 +建立一個函式,使用提供的金鑰擷取函式與選項來驗證 JWT 存取權杖 (Access token)。 ## 參數 {#parameters} @@ -16,11 +16,11 @@ function createVerifyJwt(getKey: JWTVerifyGetKey, options?: JWTVerifyOptions): V `JWTVerifyGetKey` -用於取得驗證 JWT 所需金鑰的函式。 +用於擷取驗證 JWT 所需金鑰的函式。 **參見** -JWTVerifyGetKey 以瞭解金鑰取得函式的型別定義。 +JWTVerifyGetKey 以取得金鑰擷取函式的型別定義。 ### options? {#options} @@ -30,7 +30,7 @@ JWTVerifyGetKey 以瞭解金鑰取得函式的型別定義。 **參見** -JWTVerifyOptions 以瞭解選項的型別定義。 +JWTVerifyOptions 以取得選項的型別定義。 ## 回傳值 {#returns} @@ -40,4 +40,4 @@ JWTVerifyOptions 以瞭解選項的型別定義。 ## 參見 {#see} -[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) 以瞭解回傳函式的型別定義。 \ No newline at end of file +[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 index b0af0e4..f9f6800 100644 --- 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 @@ -5,10 +5,10 @@ sidebar_label: fetchServerConfig # 函式:fetchServerConfig() ```ts -function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; +function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promise; ``` -根據簽發者 (Issuer) 與授權伺服器類型,取得伺服器設定。 +根據簽發者(Issuer)與授權伺服器類型,擷取伺服器設定。 此函式會根據伺服器類型自動判斷 well-known URL,因為 OAuth 及 OpenID Connect 伺服器的 metadata endpoint 慣例不同。 @@ -18,19 +18,19 @@ function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promis `string` -授權伺服器的簽發者 (Issuer) URL。 +授權伺服器的簽發者(Issuer)URL。 ### config {#config} `ServerMetadataConfig` -包含伺服器類型與可選轉換函式的設定物件。 +包含伺服器類型與可選轉譯函式的設定物件。 ## 回傳值 {#returns} -`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> +`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -一個 promise,解析後會得到伺服器設定。 +一個 promise,解析後會取得包含 metadata 的靜態伺服器設定。 ## 參見 {#see} @@ -43,17 +43,17 @@ function fetchServerConfig(issuer: string, config: ServerMetadataConfig): Promis ```ts import { fetchServerConfig } from 'mcp-auth'; // 取得 OAuth 伺服器設定 -// 這會從 `https://auth.logto.io/.well-known/oauth-authorization-server/oauth` 取得 metadata +// 這會從 `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 +// 這會從 `https://auth.logto.io/oidc/.well-known/openid-configuration` 擷取 metadata const oidcConfig = await fetchServerConfig('https://auth.logto.io/oidc', { type: 'oidc' }); ``` ## 例外 {#throws} -若 fetch 操作失敗則會拋出例外。 +若擷取操作失敗則會拋出例外。 ## 例外 {#throws} 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 index f44bf19..a9ca8a8 100644 --- 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 @@ -5,12 +5,12 @@ sidebar_label: fetchServerConfigByWellKnownUrl # 函式:fetchServerConfigByWellKnownUrl() ```ts -function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; +function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: ServerMetadataConfig): Promise; ``` -從提供的 well-known URL 取得伺服器設定,並依據 MCP 規範進行驗證。 +從指定的 well-known URL 取得伺服器設定,並根據 MCP 規範進行驗證。 -如果伺服器中繼資料不符合預期的結構,但你確定其相容,你可以定義 `transpileData` 函式,將中繼資料轉換為預期格式。 +如果伺服器中繼資料不符合預期的結構,但你確定其相容,可以定義 `transpileData` 函式,將中繼資料轉換為預期格式。 ## 參數 {#parameters} @@ -28,9 +28,9 @@ function fetchServerConfigByWellKnownUrl(wellKnownUrl: string | URL, config: Ser ## 回傳值 {#returns} -`Promise`\<[`AuthServerConfig`](/references/js/type-aliases/AuthServerConfig.md)\> +`Promise`\<[`ResolvedAuthServerConfig`](/references/js/type-aliases/ResolvedAuthServerConfig.md)\> -一個 promise,解析後會得到伺服器設定。 +一個 promise,解析後會取得包含中繼資料的靜態伺服器設定。 ## 例外 {#throws} 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 new file mode 100644 index 0000000..b7a94ed --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/functions/getIssuer.md @@ -0,0 +1,24 @@ +--- +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 index 117283a..707e4cb 100644 --- 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 @@ -10,15 +10,15 @@ function handleBearerAuth(param0: BearerAuthConfig): RequestHandler; 建立一個用於在 Express 應用程式中處理 Bearer 驗證 (Authentication) 的中介軟體函式。 -此中介軟體會從 `Authorization` 標頭中擷取 Bearer 存取權杖 (Access token),使用提供的 `verifyAccessToken` 函式進行驗證,並檢查簽發者 (Issuer)、受眾 (Audience) 及所需權限範圍 (Scopes)。 +此中介軟體會從 `Authorization` 標頭中擷取 Bearer 存取權杖 (Access token),使用提供的 `verifyAccessToken` 函式進行驗證,並檢查簽發者 (Issuer)、受眾 (Audience) 以及所需權限範圍 (Scopes)。 - 如果權杖有效,會將驗證資訊加入 `request.auth` 屬性; 若無效,則回應相應的錯誤訊息。 -- 若存取權杖 (Access token) 驗證失敗,會回應 401 未授權錯誤。 -- 若權杖未包含所需權限範圍 (Scopes),會回應 403 禁止存取錯誤。 +- 若存取權杖 (Access token) 驗證失敗,會回應 401 未授權 (Unauthorized) 錯誤。 +- 若權杖未包含所需權限範圍 (Scopes),會回應 403 禁止存取 (Forbidden) 錯誤。 - 若驗證 (Authentication) 流程中發生非預期錯誤,中介軟體會重新拋出錯誤。 -**注意:** `request.auth` 物件會包含比 `@modelcontextprotocol/sdk` 模組中定義的標準 AuthInfo 介面更多的延伸欄位。詳情請參閱本檔案中的延伸介面。 +**注意:** `request.auth` 物件會包含比 `@modelcontextprotocol/sdk` 模組中標準 AuthInfo 介面更多的擴充欄位。詳情請參閱本檔案中的擴充介面。 ## 參數 {#parameters} 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 index 1927ee0..64c1e47 100644 --- 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 @@ -5,45 +5,13 @@ sidebar_label: AuthServerConfig # 型別別名:AuthServerConfig ```ts -type AuthServerConfig = { - metadata: CamelCaseAuthorizationServerMetadata; - type: AuthServerType; -}; +type AuthServerConfig = + | ResolvedAuthServerConfig + | AuthServerDiscoveryConfig; ``` -與 MCP 伺服器整合的遠端授權伺服器(Authorization Server)設定。 +用於與 MCP 伺服器整合的遠端授權伺服器(Authorization server)設定。 -## 屬性 {#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 授權伺服器中繼資料 (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 +可以是以下其中之一: +- **已解析(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 index efb48cd..87d6db5 100644 --- 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 @@ -22,7 +22,7 @@ type AuthServerConfigError = { optional cause: Error; ``` -錯誤的可選原因,通常是 `Error` 實例,用於提供更多背景資訊。 +錯誤的可選原因,通常為 `Error` 實例,用於提供更多背景資訊。 *** @@ -42,4 +42,4 @@ code: AuthServerConfigErrorCode; description: string; ``` -對錯誤的人類可讀描述。 +錯誤的人類可讀描述。 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 new file mode 100644 index 0000000..30a531c --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthServerDiscoveryConfig.md @@ -0,0 +1,57 @@ +--- +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/AuthorizationServerMetadata.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/AuthorizationServerMetadata.md index 0309624..5ee40ed 100644 --- 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 @@ -1,229 +1,15 @@ --- -sidebar_label: AuthorizationServerMetadata +sidebar_label: 授權伺服器中繼資料 (AuthorizationServerMetadata) --- -# 型別別名:AuthorizationServerMetadata +# 型別別名:授權伺服器中繼資料 (AuthorizationServerMetadata) ```ts -type AuthorizationServerMetadata = { - authorization_endpoint: string; - code_challenge_methods_supported?: string[]; - grant_types_supported?: string[]; - introspection_endpoint?: string; - introspection_endpoint_auth_methods_supported?: string[]; - introspection_endpoint_auth_signing_alg_values_supported?: string[]; - issuer: string; - jwks_uri?: string; - op_policy_uri?: string; - op_tos_uri?: string; - registration_endpoint?: string; - response_modes_supported?: string[]; - response_types_supported: string[]; - revocation_endpoint?: string; - revocation_endpoint_auth_methods_supported?: string[]; - revocation_endpoint_auth_signing_alg_values_supported?: string[]; - scopes_supported?: string[]; - service_documentation?: string; - token_endpoint: string; - token_endpoint_auth_methods_supported?: string[]; - token_endpoint_auth_signing_alg_values_supported?: string[]; - ui_locales_supported?: string[]; - userinfo_endpoint?: string; -}; +type AuthorizationServerMetadata = z.infer; ``` -OAuth 2.0 授權伺服器中繼資料(Authorization Server Metadata)的結構,定義於 RFC 8414。 +根據 RFC 8414 所定義的 OAuth 2.0 授權伺服器中繼資料 (Authorization Server Metadata) 架構。 -## 型別宣告 {#type-declaration} - -### authorization\_endpoint {#authorization-endpoint} - -```ts -authorization_endpoint: string; -``` - -授權伺服器的授權端點(authorization endpoint)URL [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]。 -除非不支援任何使用授權端點的授權類型(grant types),否則此欄位為必填。 - -#### 參見 {#see} - -https://rfc-editor.org/rfc/rfc6749#section-3.1 - -### code\_challenge\_methods\_supported? {#code-challenge-methods-supported} - -```ts -optional code_challenge_methods_supported: string[]; -``` - -JSON 陣列,包含此授權伺服器支援的 PKCE(Proof Key for Code Exchange) -[[RFC7636](https://www.rfc-editor.org/rfc/rfc7636)] code challenge 方法列表。 - -### grant\_types\_supported? {#grant-types-supported} - -```ts -optional grant_types_supported: string[]; -``` - -JSON 陣列,包含此授權伺服器支援的 OAuth 2.0 授權類型(grant type)值。 -陣列值與「OAuth 2.0 動態用戶端註冊協議」[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]中 `grant_types` 參數所用值相同。 -若省略,預設值為 `["authorization_code", "implicit"]`。 - -### introspection\_endpoint? {#introspection-endpoint} - -```ts -optional introspection_endpoint: string; -``` - -授權伺服器的 OAuth 2.0 introspection 端點 URL -[[RFC7662](https://www.rfc-editor.org/rfc/rfc7662)]。 - -### introspection\_endpoint\_auth\_methods\_supported? {#introspection-endpoint-auth-methods-supported} - -```ts -optional introspection_endpoint_auth_methods_supported: string[]; -``` - -### introspection\_endpoint\_auth\_signing\_alg\_values\_supported? {#introspection-endpoint-auth-signing-alg-values-supported} - -```ts -optional introspection_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### issuer {#issuer} - -```ts -issuer: string; -``` - -授權伺服器的簽發者(Issuer)識別符,為一個使用 `https` 協定且無查詢或片段組件的 URL。 - -### jwks\_uri? {#jwks-uri} - -```ts -optional jwks_uri: string; -``` - -授權伺服器 JWK Set [[JWK](https://www.rfc-editor.org/rfc/rfc8414.html#ref-JWK)] -文件的 URL。該文件包含用戶端用於驗證授權伺服器簽章的簽名金鑰。此 URL 必須使用 `https` 協定。 - -### op\_policy\_uri? {#op-policy-uri} - -```ts -optional op_policy_uri: string; -``` - -### op\_tos\_uri? {#op-tos-uri} - -```ts -optional op_tos_uri: string; -``` - -### registration\_endpoint? {#registration-endpoint} - -```ts -optional registration_endpoint: string; -``` - -授權伺服器的 OAuth 2.0 動態用戶端註冊端點 URL -[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]。 - -### response\_modes\_supported? {#response-modes-supported} - -```ts -optional response_modes_supported: string[]; -``` - -JSON 陣列,包含此授權伺服器支援的 OAuth 2.0 `response_mode` 值,詳見「OAuth 2.0 多重回應型態編碼實踐」 -[[OAuth.Responses](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Responses)]。 - -若省略,預設為 `["query", "fragment"]`。回應模式值 `"form_post"` 亦定義於「OAuth 2.0 表單回傳回應模式」 -[[OAuth.FormPost](https://datatracker.ietf.org/doc/html/rfc8414#ref-OAuth.Post)]。 - -### response\_types\_supported {#response-types-supported} - -```ts -response_types_supported: string[]; -``` - -JSON 陣列,包含此授權伺服器支援的 OAuth 2.0 `response_type` 值。 -陣列值與「OAuth 2.0 動態用戶端註冊協議」[[RFC7591](https://www.rfc-editor.org/rfc/rfc7591)]中 `response_types` 參數所用值相同。 - -### revocation\_endpoint? {#revocation-endpoint} - -```ts -optional revocation_endpoint: string; -``` - -授權伺服器的 OAuth 2.0 撤銷端點(revocation endpoint)URL -[[RFC7009](https://www.rfc-editor.org/rfc/rfc7009)]。 - -### revocation\_endpoint\_auth\_methods\_supported? {#revocation-endpoint-auth-methods-supported} - -```ts -optional revocation_endpoint_auth_methods_supported: string[]; -``` - -### revocation\_endpoint\_auth\_signing\_alg\_values\_supported? {#revocation-endpoint-auth-signing-alg-values-supported} - -```ts -optional revocation_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### scopes\_supported? {#scopes-supported} - -```ts -optional scopes_supported: string[]; -``` - -JSON 陣列,包含此授權伺服器支援的 OAuth 2.0 `scope` 值。 -[[RFC8414](https://datatracker.ietf.org/doc/html/rfc8414#section-2)] - -### service\_documentation? {#service-documentation} - -```ts -optional service_documentation: string; -``` - -### token\_endpoint {#token-endpoint} - -```ts -token_endpoint: string; -``` - -授權伺服器的權杖端點(token endpoint)URL [[RFC6749](https://rfc-editor.org/rfc/rfc6749)]。 -除非僅支援 implicit 授權類型,否則此欄位為必填。 - -#### 參見 {#see} - -https://rfc-editor.org/rfc/rfc6749#section-3.2 - -### token\_endpoint\_auth\_methods\_supported? {#token-endpoint-auth-methods-supported} - -```ts -optional token_endpoint_auth_methods_supported: string[]; -``` - -### token\_endpoint\_auth\_signing\_alg\_values\_supported? {#token-endpoint-auth-signing-alg-values-supported} - -```ts -optional token_endpoint_auth_signing_alg_values_supported: string[]; -``` - -### ui\_locales\_supported? {#ui-locales-supported} - -```ts -optional ui_locales_supported: string[]; -``` - -### userinfo\_endpoint? {#userinfo-endpoint} - -```ts -optional userinfo_endpoint: string; -``` - -OpenID Connect [userinfo 端點](https://openid.net/specs/openid-connect-core-1_0.html#UserInfo)的 URL。 -此端點用於取得已驗證使用者的資訊。 - -## 參見 {#see} +## 參考 {#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 index 85f5b54..f56862a 100644 --- 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 @@ -2,7 +2,7 @@ sidebar_label: BearerAuthConfig --- -# 型別別名:BearerAuthConfig (Type Alias: BearerAuthConfig) +# 型別別名:BearerAuthConfig ```ts type BearerAuthConfig = { @@ -16,7 +16,7 @@ type BearerAuthConfig = { }; ``` -## 屬性 (Properties) {#properties} +## 屬性說明 {#properties} ### audience? {#audience} @@ -26,7 +26,7 @@ optional audience: string; 存取權杖 (Access token) 預期的受眾 (Audience)(`aud` 宣告 (claim))。這通常是該權杖預期要存取的資源伺服器(API)。如果未提供,將略過受眾檢查。 -**注意:** 如果你的授權伺服器不支援資源標示符 (Resource Indicators, RFC 8707),可以省略此欄位,因為受眾可能不適用。 +**注意:** 如果你的授權伺服器 (Authorization server) 不支援資源標示符 (Resource Indicators, RFC 8707),可以省略此欄位,因為受眾可能不適用。 #### 參考 {#see} @@ -42,15 +42,15 @@ issuer: | ValidateIssuerFunction; ``` -代表有效簽發者 (Issuer) 的字串,或用於驗證存取權杖 (Access token) 簽發者的函式。 +代表有效簽發者 (Issuer) 的字串,或用於驗證存取權杖簽發者的函式。 -如果提供字串,將作為預期的簽發者值進行直接比對。 +如果提供字串,將直接作為預期的簽發者值進行比對。 -如果提供函式,應依據 [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) 的規則驗證簽發者。 +如果提供函式,則應依據 [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) 的規則驗證簽發者。 #### 參考 {#see} -更多驗證函式細節請見 [ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md)。 +[ValidateIssuerFunction](/references/js/type-aliases/ValidateIssuerFunction.md) 以取得更多驗證函式細節。 *** @@ -60,9 +60,9 @@ issuer: optional requiredScopes: string[]; ``` -存取權杖 (Access token) 必須具備的權限範圍 (Scopes) 陣列。如果權杖未包含所有這些權限範圍,將拋出錯誤。 +存取權杖必須具備的權限範圍 (Scopes) 陣列。如果權杖未包含所有這些權限範圍,將拋出錯誤。 -**注意:** 處理器會檢查權杖中的 `scope` 宣告 (claim),其內容可能為以空格分隔的字串或字串陣列,取決於授權伺服器的實作方式。如果 `scope` 宣告不存在,則會檢查 `scopes` 宣告(若有)。 +**注意:** 處理器會檢查權杖中的 `scope` 宣告 (claim),其值可能是以空格分隔的字串或字串陣列,取決於授權伺服器的實作。如果 `scope` 宣告不存在,則會檢查 `scopes` 宣告(若有)。 *** @@ -72,7 +72,7 @@ optional requiredScopes: string[]; optional resource: string; ``` -受保護資源的識別符。若提供此欄位,處理器將使用針對該資源所設定的授權伺服器來驗證收到的權杖。當與 `protectedResources` 設定搭配使用時,此欄位為必填。 +受保護資源的識別符。若提供此欄位,處理器將使用為該資源設定的授權伺服器來驗證收到的權杖。當搭配 `protectedResources` 設定使用時,此欄位為必填。 *** @@ -82,9 +82,9 @@ optional resource: string; optional showErrorDetails: boolean; ``` -是否在回應中顯示詳細錯誤資訊。這對於開發階段除錯很有幫助,但在生產環境中應關閉,以避免洩漏敏感資訊。 +是否在回應中顯示詳細錯誤資訊。這對於開發期間除錯很有幫助,但在生產環境中應關閉,以避免洩漏敏感資訊。 -#### 預設值 (Default) {#default} +#### 預設值 {#default} ```ts false @@ -98,10 +98,10 @@ false verifyAccessToken: VerifyAccessTokenFunction; ``` -用於驗證存取權杖 (Access token) 的函式型別。 +用於驗證存取權杖的函式型別。 此函式若權杖無效應拋出 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md),若權杖有效則回傳 AuthInfo 物件。 #### 參考 {#see} -更多細節請見 [VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md)。 +[VerifyAccessTokenFunction](/references/js/type-aliases/VerifyAccessTokenFunction.md) 以取得更多細節。 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 index b903332..8c48216 100644 --- 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 @@ -5,175 +5,11 @@ sidebar_label: CamelCaseAuthorizationServerMetadata # 型別別名:CamelCaseAuthorizationServerMetadata ```ts -type CamelCaseAuthorizationServerMetadata = { - authorizationEndpoint: string; - codeChallengeMethodsSupported?: string[]; - grantTypesSupported?: string[]; - introspectionEndpoint?: string; - introspectionEndpointAuthMethodsSupported?: string[]; - introspectionEndpointAuthSigningAlgValuesSupported?: string[]; - issuer: string; - jwksUri?: string; - opPolicyUri?: string; - opTosUri?: string; - registrationEndpoint?: string; - responseModesSupported?: string[]; - responseTypesSupported: string[]; - revocationEndpoint?: string; - revocationEndpointAuthMethodsSupported?: string[]; - revocationEndpointAuthSigningAlgValuesSupported?: string[]; - scopesSupported?: string[]; - serviceDocumentation?: string; - tokenEndpoint: string; - tokenEndpointAuthMethodsSupported?: string[]; - tokenEndpointAuthSigningAlgValuesSupported?: string[]; - uiLocalesSupported?: string[]; - userinfoEndpoint?: string; -}; +type CamelCaseAuthorizationServerMetadata = z.infer; ``` -OAuth 2.0 授權伺服器中繼資料(Authorization Server Metadata)型別的 camelCase 版本。 - -## 型別宣告 {#type-declaration} - -### authorizationEndpoint {#authorizationendpoint} - -```ts -authorizationEndpoint: string; -``` - -### codeChallengeMethodsSupported? {#codechallengemethodssupported} - -```ts -optional codeChallengeMethodsSupported: string[]; -``` - -### grantTypesSupported? {#granttypessupported} - -```ts -optional grantTypesSupported: string[]; -``` - -### introspectionEndpoint? {#introspectionendpoint} - -```ts -optional introspectionEndpoint: string; -``` - -### introspectionEndpointAuthMethodsSupported? {#introspectionendpointauthmethodssupported} - -```ts -optional introspectionEndpointAuthMethodsSupported: string[]; -``` - -### introspectionEndpointAuthSigningAlgValuesSupported? {#introspectionendpointauthsigningalgvaluessupported} - -```ts -optional introspectionEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### issuer {#issuer} - -```ts -issuer: string; -``` - -### jwksUri? {#jwksuri} - -```ts -optional jwksUri: string; -``` - -### opPolicyUri? {#oppolicyuri} - -```ts -optional opPolicyUri: string; -``` - -### opTosUri? {#optosuri} - -```ts -optional opTosUri: string; -``` - -### registrationEndpoint? {#registrationendpoint} - -```ts -optional registrationEndpoint: string; -``` - -### responseModesSupported? {#responsemodessupported} - -```ts -optional responseModesSupported: string[]; -``` - -### responseTypesSupported {#responsetypessupported} - -```ts -responseTypesSupported: string[]; -``` - -### revocationEndpoint? {#revocationendpoint} - -```ts -optional revocationEndpoint: string; -``` - -### revocationEndpointAuthMethodsSupported? {#revocationendpointauthmethodssupported} - -```ts -optional revocationEndpointAuthMethodsSupported: string[]; -``` - -### revocationEndpointAuthSigningAlgValuesSupported? {#revocationendpointauthsigningalgvaluessupported} - -```ts -optional revocationEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### scopesSupported? {#scopessupported} - -```ts -optional scopesSupported: string[]; -``` - -### serviceDocumentation? {#servicedocumentation} - -```ts -optional serviceDocumentation: string; -``` - -### tokenEndpoint {#tokenendpoint} - -```ts -tokenEndpoint: string; -``` - -### tokenEndpointAuthMethodsSupported? {#tokenendpointauthmethodssupported} - -```ts -optional tokenEndpointAuthMethodsSupported: string[]; -``` - -### tokenEndpointAuthSigningAlgValuesSupported? {#tokenendpointauthsigningalgvaluessupported} - -```ts -optional tokenEndpointAuthSigningAlgValuesSupported: string[]; -``` - -### uiLocalesSupported? {#uilocalessupported} - -```ts -optional uiLocalesSupported: string[]; -``` - -### userinfoEndpoint? {#userinfoendpoint} - -```ts -optional userinfoEndpoint: string; -``` +OAuth 2.0 授權伺服器中繼資料 (Authorization Server Metadata) 型別的 camelCase 版本。 ## 參見 {#see} -[AuthorizationServerMetadata](/references/js/type-aliases/AuthorizationServerMetadata.md) 以取得原始型別與欄位資訊。 +[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 index 913b073..d127b63 100644 --- 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 @@ -5,119 +5,11 @@ sidebar_label: CamelCaseProtectedResourceMetadata # 型別別名:CamelCaseProtectedResourceMetadata ```ts -type CamelCaseProtectedResourceMetadata = { - authorizationDetailsTypesSupported?: string[]; - authorizationServers?: string[]; - bearerMethodsSupported?: string[]; - dpopBoundAccessTokensRequired?: boolean; - dpopSigningAlgValuesSupported?: string[]; - jwksUri?: string; - resource: string; - resourceDocumentation?: string; - resourceName?: string; - resourcePolicyUri?: string; - resourceSigningAlgValuesSupported?: string[]; - resourceTosUri?: string; - scopesSupported?: string[]; - signedMetadata?: string; - tlsClientCertificateBoundAccessTokens?: boolean; -}; +type CamelCaseProtectedResourceMetadata = z.infer; ``` -OAuth 2.0 Protected Resource Metadata 型別的 camelCase 版本。 - -## 型別宣告 {#type-declaration} - -### authorizationDetailsTypesSupported? {#authorizationdetailstypessupported} - -```ts -optional authorizationDetailsTypesSupported: string[]; -``` - -### authorizationServers? {#authorizationservers} - -```ts -optional authorizationServers: string[]; -``` - -### bearerMethodsSupported? {#bearermethodssupported} - -```ts -optional bearerMethodsSupported: string[]; -``` - -### dpopBoundAccessTokensRequired? {#dpopboundaccesstokensrequired} - -```ts -optional dpopBoundAccessTokensRequired: boolean; -``` - -### dpopSigningAlgValuesSupported? {#dpopsigningalgvaluessupported} - -```ts -optional dpopSigningAlgValuesSupported: string[]; -``` - -### jwksUri? {#jwksuri} - -```ts -optional jwksUri: string; -``` - -### resource {#resource} - -```ts -resource: string; -``` - -### resourceDocumentation? {#resourcedocumentation} - -```ts -optional resourceDocumentation: string; -``` - -### resourceName? {#resourcename} - -```ts -optional resourceName: string; -``` - -### resourcePolicyUri? {#resourcepolicyuri} - -```ts -optional resourcePolicyUri: string; -``` - -### resourceSigningAlgValuesSupported? {#resourcesigningalgvaluessupported} - -```ts -optional resourceSigningAlgValuesSupported: string[]; -``` - -### resourceTosUri? {#resourcetosuri} - -```ts -optional resourceTosUri: string; -``` - -### scopesSupported? {#scopessupported} - -```ts -optional scopesSupported: string[]; -``` - -### signedMetadata? {#signedmetadata} - -```ts -optional signedMetadata: string; -``` - -### tlsClientCertificateBoundAccessTokens? {#tlsclientcertificateboundaccesstokens} - -```ts -optional tlsClientCertificateBoundAccessTokens: boolean; -``` +OAuth 2.0 不透明權杖 (Opaque token) 保護資源中,欄位名稱為 camelCase 版本的型別。 ## 參見 {#see} -[ProtectedResourceMetadata](/references/js/type-aliases/ProtectedResourceMetadata.md) 以取得原始型別與欄位資訊。 \ No newline at end of file +[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 index 7f65917..9ac67d2 100644 --- 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 @@ -2,7 +2,7 @@ sidebar_label: MCPAuthBearerAuthErrorDetails --- -# 型別別名:MCPAuthBearerAuthErrorDetails +# 型別別名:MCPAuthBearerAuthErrorDetails (Type Alias: MCPAuthBearerAuthErrorDetails) ```ts type MCPAuthBearerAuthErrorDetails = { @@ -14,7 +14,7 @@ type MCPAuthBearerAuthErrorDetails = { }; ``` -## 屬性 {#properties} +## 屬性 (Properties) {#properties} ### actual? {#actual} 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 index 00da031..a493929 100644 --- 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 @@ -5,145 +5,7 @@ sidebar_label: ProtectedResourceMetadata # 型別別名:ProtectedResourceMetadata ```ts -type ProtectedResourceMetadata = { - authorization_details_types_supported?: string[]; - authorization_servers?: string[]; - bearer_methods_supported?: string[]; - dpop_bound_access_tokens_required?: boolean; - dpop_signing_alg_values_supported?: string[]; - jwks_uri?: string; - resource: string; - resource_documentation?: string; - resource_name?: string; - resource_policy_uri?: string; - resource_signing_alg_values_supported?: string[]; - resource_tos_uri?: string; - scopes_supported?: string[]; - signed_metadata?: string; - tls_client_certificate_bound_access_tokens?: boolean; -}; +type ProtectedResourceMetadata = z.infer; ``` -OAuth 2.0 受保護資源中繼資料的結構描述。 - -## 型別宣告 {#type-declaration} - -### authorization\_details\_types\_supported? {#authorization-details-types-supported} - -```ts -optional authorization_details_types_supported: string[]; -``` - -在使用 authorization_details 請求參數時支援的授權細節類型值。 - -### authorization\_servers? {#authorization-servers} - -```ts -optional authorization_servers: string[]; -``` - -可與此受保護資源搭配使用的 OAuth 授權伺服器簽發者 (Issuer) 識別碼清單。 - -### bearer\_methods\_supported? {#bearer-methods-supported} - -```ts -optional bearer_methods_supported: string[]; -``` - -支援的 OAuth 2.0 bearer 權杖 (Access token) 傳遞方式。可選值:["header", "body", "query"]。 - -### dpop\_bound\_access\_tokens\_required? {#dpop-bound-access-tokens-required} - -```ts -optional dpop_bound_access_tokens_required: boolean; -``` - -此受保護資源是否始終要求 DPoP 綁定的存取權杖 (Access token)。 - -### dpop\_signing\_alg\_values\_supported? {#dpop-signing-alg-values-supported} - -```ts -optional dpop_signing_alg_values_supported: string[]; -``` - -用於驗證 DPoP 證明 JWT 的支援 JWS 演算法。 - -### jwks\_uri? {#jwks-uri} - -```ts -optional jwks_uri: string; -``` - -受保護資源的 JSON Web Key (JWK) Set 文件的 URL。此文件包含可用於驗證此受保護資源回應或資料數位簽章的公鑰。這與授權伺服器的 jwks_uri 不同,後者用於權杖驗證。當受保護資源對回應進行簽章時,客戶端可透過此 URL 取得公鑰,以驗證收到資料的真實性與完整性。 - -### resource {#resource} - -```ts -resource: string; -``` - -受保護資源的資源標示符 (Resource identifier)。 - -### resource\_documentation? {#resource-documentation} - -```ts -optional resource_documentation: string; -``` - -包含使用此受保護資源開發者文件的 URL。 - -### resource\_name? {#resource-name} - -```ts -optional resource_name: string; -``` - -用於顯示給終端使用者的人類可讀受保護資源名稱。 - -### resource\_policy\_uri? {#resource-policy-uri} - -```ts -optional resource_policy_uri: string; -``` - -包含受保護資源資料使用需求相關資訊的 URL。 - -### resource\_signing\_alg\_values\_supported? {#resource-signing-alg-values-supported} - -```ts -optional resource_signing_alg_values_supported: string[]; -``` - -受保護資源用於簽署資源回應的支援 JWS 簽章演算法。 - -### resource\_tos\_uri? {#resource-tos-uri} - -```ts -optional resource_tos_uri: string; -``` - -包含受保護資源服務條款的 URL。 - -### scopes\_supported? {#scopes-supported} - -```ts -optional scopes_supported: string[]; -``` - -在授權請求中用於存取此受保護資源的權限範圍 (Scope) 值清單。 - -### signed\_metadata? {#signed-metadata} - -```ts -optional signed_metadata: string; -``` - -包含中繼資料參數作為宣告 (Claim) 的已簽署 JWT。此 JWT 必須使用 JWS 簽署,並包含 'iss' 宣告。此欄位提供一種密碼學方式驗證中繼資料本身的真實性。可使用 `jwks_uri` 端點提供的公鑰驗證簽章。若存在,已簽署中繼資料中的值優先於本文件中對應的純 JSON 值,有助於防止資源中繼資料被竄改。 - -### tls\_client\_certificate\_bound\_access\_tokens? {#tls-client-certificate-bound-access-tokens} - -```ts -optional tls_client_certificate_bound_access_tokens: boolean; -``` - -此受保護資源是否支援 mutual-TLS 用戶端憑證綁定的存取權杖 (Access token)。 +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 new file mode 100644 index 0000000..2c9b817 --- /dev/null +++ b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/type-aliases/ResolvedAuthServerConfig.md @@ -0,0 +1,49 @@ +--- +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 index a551dad..3c4671a 100644 --- 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 @@ -2,7 +2,7 @@ sidebar_label: ResourceServerModeConfig --- -# 型別別名:ResourceServerModeConfig (Type Alias: ResourceServerModeConfig) +# 型別別名:ResourceServerModeConfig ```ts type ResourceServerModeConfig = { @@ -12,7 +12,7 @@ type ResourceServerModeConfig = { MCP 伺服器作為資源伺服器模式的設定。 -## 屬性 (Properties) {#properties} +## 屬性 {#properties} ### protectedResources {#protectedresources} 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 index 05e66bd..d5bb3c0 100644 --- 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 @@ -10,7 +10,7 @@ type ValidateIssuerFunction = (tokenIssuer: string) => void; 用於驗證存取權杖 (Access token) 簽發者 (Issuer) 的函式型別。 -當簽發者 (Issuer) 無效時,此函式應拋出帶有 'invalid_issuer' 代碼的 [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md)。簽發者應根據以下條件進行驗證: +當簽發者無效時,此函式應拋出帶有 'invalid_issuer' 代碼的 [MCPAuthBearerAuthError](/references/js/classes/MCPAuthBearerAuthError.md)。簽發者應根據以下條件進行驗證: 1. MCP-Auth 的授權伺服器 (Authorization server) 中設定的授權伺服器元資料 2. 受保護資源 (Protected resource) 元資料中列出的授權伺服器 @@ -21,10 +21,10 @@ type ValidateIssuerFunction = (tokenIssuer: string) => void; `string` -## 回傳值 {#returns} +## 回傳 {#returns} `void` -## 拋出例外 {#throws} +## 拋出 {#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 index 1b1252a..a314b85 100644 --- 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 @@ -10,10 +10,10 @@ type VerifyAccessTokenFunction = (token: string) => MaybePromise; 用於驗證存取權杖 (Access token) 的函式型別。 -此函式若權杖無效,應拋出 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md); -若權杖有效,則回傳 AuthInfo 物件。 +當權杖無效時,此函式應拋出 [MCPAuthTokenVerificationError](/references/js/classes/MCPAuthTokenVerificationError.md); +若權杖有效,則回傳一個 AuthInfo 物件。 -舉例來說,若你有一個 JWT 驗證函式,至少應檢查權杖的簽章、驗證其過期時間,並擷取必要的宣告 (Claims) 以回傳 `AuthInfo` 物件。 +例如,若你有一個 JWT 驗證函式,至少應檢查權杖的簽章、驗證其過期時間,並擷取必要的宣告 (Claims) 以回傳 `AuthInfo` 物件。 **注意:** 權杖中的下列欄位無需自行驗證,因為這些會由處理器自動檢查: @@ -33,4 +33,4 @@ type VerifyAccessTokenFunction = (token: string) => MaybePromise; `MaybePromise`\<`AuthInfo`\> -一個 Promise,當權杖有效時解析為 AuthInfo 物件,或同步回傳值。 \ No newline at end of file +一個 Promise,若權杖有效則解析為 AuthInfo 物件,或同步回傳該物件。 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 index 01b8d5c..7bf29d6 100644 --- 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 @@ -5,10 +5,34 @@ sidebar_label: authorizationServerMetadataSchema # 變數:authorizationServerMetadataSchema ```ts -const authorizationServerMetadataSchema: ZodObject; +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,對應 RFC 8414 中定義的 OAuth 2.0 授權伺服器中繼資料(Authorization Server Metadata)。 +用於 OAuth 2.0 授權伺服器中繼資料(Authorization Server Metadata)的 Zod schema,依據 RFC 8414 定義。 ## 參考 {#see} 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 index a7112c2..9ef2b7c 100644 --- 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 @@ -5,11 +5,35 @@ sidebar_label: camelCaseAuthorizationServerMetadataSchema # 變數:camelCaseAuthorizationServerMetadataSchema ```ts -const camelCaseAuthorizationServerMetadataSchema: ZodObject; +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 及欄位資訊。 \ No newline at end of file +[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 index a8fbb01..929f49d 100644 --- 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 @@ -5,11 +5,27 @@ sidebar_label: camelCaseProtectedResourceMetadataSchema # 變數:camelCaseProtectedResourceMetadataSchema ```ts -const camelCaseProtectedResourceMetadataSchema: ZodObject; +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 版本。 +OAuth 2.0 不透明權杖 (Opaque token) 受保護資源中繼資料 Zod schema 的 camelCase 版本。 ## 參見 {#see} -[protectedResourceMetadataSchema](/references/js/variables/protectedResourceMetadataSchema.md) 以瞭解原始 schema 與欄位資訊。 \ No newline at end of file +[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/protectedResourceMetadataSchema.md b/i18n/zh-TW/docusaurus-plugin-content-docs/current/references/js/variables/protectedResourceMetadataSchema.md index fcd8799..d5ee951 100644 --- 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 @@ -5,7 +5,23 @@ sidebar_label: protectedResourceMetadataSchema # 變數:protectedResourceMetadataSchema ```ts -const protectedResourceMetadataSchema: ZodObject; +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 受保護資源中繼資料(Protected Resource Metadata)的 Zod schema。 +OAuth 2.0 受保護資源中繼資料的 Zod schema(Zod schema for OAuth 2.0 Protected Resource Metadata)。