Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
/**
* RFC 8693 grant type for OAuth token exchange.
*/
export
const
GRANT_TYPE_TOKEN_EXCHANGE
=
'urn:ietf:params:oauth:grant-type:token-exchange'
;
/**
* RFC 8693 token type for an OAuth 2.0 access token used as the `subject_token`
* during a token exchange.
*/
export
const
TOKEN_TYPE_ACCESS_TOKEN
=
'urn:ietf:params:oauth:token-type:access_token'
;
/**
* Token type for an OpenID Connect ID Token. Used as the `subject_token_type` in
* the IdP-side token exchange that mints an ID-JAG.
*/
export
const
TOKEN_TYPE_ID_TOKEN
=
'urn:ietf:params:oauth:token-type:id_token'
;
/**
* Token type for an Identity Assertion Authorization Grant (ID-JAG) used in
* Cross App Access (XAA) flows.
*/
export
const
TOKEN_TYPE_ID_JAG
=
'urn:ietf:params:oauth:token-type:id-jag'
;
/**
* RFC 7523 grant type used to exchange a JWT assertion (e.g. an ID-JAG) for an
* access token at the resource's authorization server.
*/
export
const
GRANT_TYPE_JWT_BEARER
=
'urn:ietf:params:oauth:grant-type:jwt-bearer'
;
/**
* Build the request body for the IdP-side token exchange that mints an ID-JAG
* for the requested audience. See draft-ietf-oauth-identity-assertion-authz-grant.
*
* @paramclientId the requesting app's client_id at the IdP.
* @paramclientSecret the requesting app's client_secret at the IdP, if applicable.
* Omit (or pass `undefined`) for public clients (`token_endpoint_auth_method=none`).
* @paramidToken the OpenID Connect `id_token` previously issued by the IdP to
* the requesting app. Per the spec the subject token MUST be an ID Token
* (not an access token).
* @paramaudience the *authorization server* URL of the resource (the issuer
* that will redeem the ID-JAG). Required.
* @paramresource the resource indicator (RFC 8707) — the URL of the actual
* protected resource (e.g. the MCP server URL). Optional but typically required
* in practice.
* @paramscopes scopes the requesting app wants granted at the resource.
*/
export
function
buildIdJagExchangeBody
(
:
string
,
:
string
|
undefined
,
:
string
,
:
string
,
:
string
|
undefined
,
:
readonly
string
[
]
)
:
{
const
=
new
URLSearchParams
(
)
;
.
append
(
'client_id'
,
)
;
if
(
)
{
.
append
(
'client_secret'
,
)
;
}
.
append
(
'grant_type'
,
GRANT_TYPE_TOKEN_EXCHANGE
)
;
.
append
(
'subject_token'
,
)
;
.
append
(
'subject_token_type'
,
TOKEN_TYPE_ID_TOKEN
)
;
.
append
(
'requested_token_type'
,
TOKEN_TYPE_ID_JAG
)
;
.
append
(
'audience'
,
)
;
if
(
)
{
.
append
(
'resource'
,
)
;
}
if
(
.
)
{
.
append
(
'scope'
,
.
join
(
AUTH_SCOPE_SEPARATOR
)
)
;
}
return
;
}
/**
* Build the request body sent to a resource server's authorization server to
* redeem an ID-JAG for a resource-scoped access token (RFC 7523 JWT-bearer grant).
*/
export
function
buildResourceRedemptionBody
(
:
string
,
:
string
|
undefined
,
:
string
,
:
string
|
undefined
,
:
readonly
string
[
]
)
:
{
const
=
new
URLSearchParams
(
)
;
.
append
(
'client_id'
,
)
;
if
(
)
{
.
append
(
'client_secret'
,
)
;
}
.
append
(
'grant_type'
,
GRANT_TYPE_JWT_BEARER
)
;
.
append
(
'assertion'
,
)
;
if
(
)
{
.
append
(
'resource'
,
)
;
}
if
(
.
)
{
.
append
(
'scope'
,
.
join
(
AUTH_SCOPE_SEPARATOR
)
)
;
}
return
;
}
//#region types
/**
* Base OAuth 2.0 error codes as specified in RFC 6749.
*/
export
const
enum
{
=
'invalid_request'
,
=
'invalid_client'
,
=
'invalid_grant'
,
=
'unauthorized_client'
,
=
'unsupported_grant_type'
,
=
'invalid_scope'
}
/**
* Device authorization grant specific error codes as specified in RFC 8628 section 3.5.
*/
export
const
enum
{
/**
* The authorization request is still pending as the end user hasn't completed the user interaction steps.
*/
=
'authorization_pending'
,
/**
* A variant of "authorization_pending", polling should continue but interval must be increased by 5 seconds.
*/
=
'slow_down'
,
/**
* The authorization request was denied.
*/
=
'access_denied'
,
/**
* The "device_code" has expired and the device authorization session has concluded.
*/
=
'expired_token'
}
/**
* Dynamic client registration specific error codes as specified in RFC 7591.
*/
export
const
enum
{
/**
* The value of one or more redirection URIs is invalid.
*/
=
'invalid_redirect_uri'
,
/**
* The value of one of the client metadata fields is invalid and the server has rejected this request.
*/
=
'invalid_client_metadata'
,
/**
* The software statement presented is invalid.
*/
=
'invalid_software_statement'
,
/**
* The software statement presented is not approved for use by this authorization server.
*/
=
'unapproved_software_statement'
}
/**
* Metadata about a protected resource.
*/
export
interface
IAuthorizationProtectedResourceMetadata
{
/**
* REQUIRED. The protected resource's resource identifier URL that uses https scheme and has no fragment components.
*/
:
string
;
/**
* OPTIONAL. Human-readable name of the protected resource intended for display to the end user.
*/
?
:
string
;
/**
* OPTIONAL. JSON array containing a list of OAuth authorization server identifiers.
*/
?
:
string
[
]
;
/**
* OPTIONAL. URL of the protected resource's JWK Set document.
*/
?
:
string
;
/**
* RECOMMENDED. JSON array containing a list of the OAuth 2.0 scope values used in authorization requests.
*/
?
:
string
[
]
;
/**
* OPTIONAL. JSON array containing a list of the OAuth 2.0 Bearer Token presentation methods supported.
*/
?
:
string
[
]
;
/**
* OPTIONAL. JSON array containing a list of the JWS signing algorithms supported.
*/
?
:
string
[
]
;
/**
* OPTIONAL. JSON array containing a list of the JWE encryption algorithms supported.
*/
?
:
string
[
]
;
/**
* OPTIONAL. JSON array containing a list of the JWE encryption algorithms supported.
*/
?
:
string
[
]
;
/**
* OPTIONAL. URL of a page containing human-readable documentation.
*/
?
:
string
;
/**
* OPTIONAL. URL that provides the resource's requirements on how clients can use the data.
*/
?
:
string
;
/**
* OPTIONAL. URL that provides the resource's terms of service.
*/
?
:
string
;
}
/**
* Metadata about an OAuth 2.0 Authorization Server.
*/
export
interface
IAuthorizationServerMetadata
{
/**
* REQUIRED. The authorization server's issuer identifier URL that uses https scheme and has no query or fragment components.
*/
:
string
;
/**
* URL of the authorization server's authorization endpoint.
* This is REQUIRED unless no grant types are supported that use the authorization endpoint.
*/
?
:
string
;
/**
* URL of the authorization server's token endpoint.
* This is REQUIRED unless only the implicit grant type is supported.
*/
?
:
string
;
/**
* OPTIONAL. URL of the authorization server's device code endpoint.
*/
?
:
string
;
/**
* OPTIONAL. URL of the authorization server's JWK Set document containing signing keys.
*/
?
:
string
;
/**
* OPTIONAL. URL of the authorization server's OAuth 2.0 Dynamic Client Registration endpoint.
*/
?
:
string
;
/**
* RECOMMENDED. JSON array containing a list of the OAuth 2.0 scope values supported.
*/
?
:
string
[
]
;
/**
* REQUIRED. JSON array containing a list of the OAuth 2.0 response_type values supported.
*/
:
string
[
]
;
/**
* OPTIONAL. JSON array containing a list of the OAuth 2.0 response_mode values supported.
* Default is ["query", "fragment"].
*/
?
:
string
[
]
;
/**
* OPTIONAL. JSON array containing a list of OAuth 2.0 grant type values supported.
* Default is ["authorization_code", "implicit"].
*/
?
:
string
[
]
;
/**
* OPTIONAL. JSON array containing a list of client authentication methods supported by the token endpoint.
* Default is "client_secret_basic".
*/
?
:
string
[
]
;
/**
* OPTIONAL. JSON array containing a list of JWS signing algorithms supported by the token endpoint.
*/
?
:
string
[
]
;
/**
* OPTIONAL. URL of a page containing human-readable documentation for developers.
*/
?
:
string
;
/**
* OPTIONAL. Languages and scripts supported for the user interface, as a JSON array of BCP 47 language tags.
*/
?
:
string
[
]
;
/**
* OPTIONAL. URL that the authorization server provides to read about the authorization server's requirements.
*/
?
:
string
;
/**
* OPTIONAL. URL that the authorization server provides to read about the authorization server's terms of service.
*/
?
:
string
;
/**
* OPTIONAL. URL of the authorization server's OAuth 2.0 revocation endpoint.
*/
?
:
string
;
/**
* OPTIONAL. JSON array containing a list of client authentication methods supported by the revocation endpoint.
*/
?
:
string
[
]
;
/**
* OPTIONAL. JSON array containing a list of JWS signing algorithms supported by the revocation endpoint.
*/
?
:
string
[
]
;
/**
* OPTIONAL. URL of the authorization server's OAuth 2.0 introspection endpoint.
*/
?
:
string
;
/**
* OPTIONAL. JSON array containing a list of client authentication methods supported by the introspection endpoint.
*/
?
:
string
[
]
;
/**
* OPTIONAL. JSON array containing a list of JWS signing algorithms supported by the introspection endpoint.
*/
?
:
string
[
]
;
/**
* OPTIONAL. JSON array containing a list of PKCE code challenge methods supported.
*/
?
:
string
[
]
;
/**
* OPTIONAL. Boolean flag indicating whether the authorization server supports the
* client_id_metadata document.
* ref https://datatracker.ietf.org/doc/html/draft-parecki-oauth-client-id-metadata-document-03
*/
?
:
boolean
;
}
/**
* Request for the dynamic client registration endpoint.
* @see https://datatracker.ietf.org/doc/html/rfc7591#section-2
*/
export
interface
IAuthorizationDynamicClientRegistrationRequest
{
/**
* OPTIONAL. Array of redirection URI strings for use in redirect-based flows
* such as the authorization code and implicit flows.
*/
?
:
string
[
]
;
/**
* OPTIONAL. String indicator of the requested authentication method for the token endpoint.
* Values: "none", "client_secret_post", "client_secret_basic".
* Default is "client_secret_basic".
*/
?
:
string
;
/**
* OPTIONAL. Array of OAuth 2.0 grant type strings that the client can use at the token endpoint.
* Default is ["authorization_code"].
*/
?
:
string
[
]
;
/**
* OPTIONAL. Array of the OAuth 2.0 response type strings that the client can use at the authorization endpoint.
* Default is ["code"].
*/
?
:
string
[
]
;
/**
* OPTIONAL. Human-readable string name of the client to be presented to the end-user during authorization.
*/
?
:
string
;
/**
* OPTIONAL. URL string of a web page providing information about the client.
*/
?
:
string
;
/**
* OPTIONAL. URL string that references a logo for the client.
*/
?
:
string
;
/**
* OPTIONAL. String containing a space-separated list of scope values that the client can use when requesting access tokens.
*/
?
:
string
;
/**
* OPTIONAL. Array of strings representing ways to contact people responsible for this client, typically email addresses.
*/
?
:
string
[
]
;
/**
* OPTIONAL. URL string that points to a human-readable terms of service document for the client.
*/
?
:
string
;
/**
* OPTIONAL. URL string that points to a human-readable privacy policy document.
*/
?
:
string
;
/**
* OPTIONAL. URL string referencing the client's JSON Web Key (JWK) Set document.
*/
?
:
string
;
/**
* OPTIONAL. Client's JSON Web Key Set document value.
*/
?
:
;
/**
* OPTIONAL. A unique identifier string assigned by the client developer or software publisher.
*/
?
:
string
;
/**
* OPTIONAL. A version identifier string for the client software.
*/
?
:
string
;
/**
* OPTIONAL. A software statement containing client metadata values about the client software as claims.
*/
?
:
string
;
/**
* OPTIONAL. Application type. Usually "native" for OAuth clients.
* https://openid.net/specs/openid-connect-registration-1_0.html
*/
?
:
'native'
|
'web'
|
string
;
/**
* OPTIONAL. Additional metadata fields as defined by extensions.
*/
[
:
string
]
:
unknown
;
}
/**
* Response from the dynamic client registration endpoint.
*/
export
interface
IAuthorizationDynamicClientRegistrationResponse
{
/**
* REQUIRED. The client identifier issued by the authorization server.
*/
:
string
;
/**
* OPTIONAL. The client secret issued by the authorization server.
* Not returned for public clients.
*/
?
:
string
;
/**
* OPTIONAL. Time at which the client secret will expire in seconds since the Unix Epoch.
*/
?
:
number
;
/**
* OPTIONAL. Client name as provided during registration.
*/
?
:
string
;
/**
* OPTIONAL. Client URI as provided during registration.
*/
?
:
string
;
/**
* OPTIONAL. Array of redirection URIs as provided during registration.
*/
?
:
string
[
]
;
/**
* OPTIONAL. Array of grant types allowed for the client.
*/
?
:
string
[
]
;
/**
* OPTIONAL. Array of response types allowed for the client.
*/
?
:
string
[
]
;
/**
* OPTIONAL. Type of authentication method used by the client.
*/
?
:
string
;
}
/**
* Response from the authorization endpoint.
* Typically returned as query parameters in a redirect.
*/
export
interface
IAuthorizationAuthorizeResponse
{
/**
* REQUIRED. The authorization code generated by the authorization server.
*/
:
string
;
/**
* REQUIRED. The state value that was sent in the authorization request.
* Used to prevent CSRF attacks.
*/
:
string
;
}
/**
* Error response from the authorization endpoint.
*/
export
interface
IAuthorizationAuthorizeErrorResponse
{
/**
* REQUIRED. Error code as specified in OAuth 2.0.
*/
:
string
;
/**
* OPTIONAL. Human-readable description of the error.
*/
?
:
string
;
/**
* OPTIONAL. URI to a human-readable web page with more information about the error.
*/
?
:
string
;
/**
* REQUIRED. The state value that was sent in the authorization request.
*/
:
string
;
}
/**
* Response from the token endpoint.
*/
export
interface
IAuthorizationTokenResponse
{
/**
* REQUIRED. The access token issued by the authorization server.
*/
:
string
;
/**
* REQUIRED. The type of the token issued. Usually "Bearer".
*/
:
string
;
/**
* RECOMMENDED. The lifetime in seconds of the access token.
*/
?
:
number
;
/**
* OPTIONAL. The refresh token, which can be used to obtain new access tokens.
*/
?
:
string
;
/**
* OPTIONAL. The scope of the access token as a space-delimited list of strings.
*/
?
:
string
;
/**
* OPTIONAL. ID Token value associated with the authenticated session for OpenID Connect flows.
*/
?
:
string
;
}
/**
* Error response from the token endpoint.
*/
export
interface
IAuthorizationTokenErrorResponse
{
/**
* REQUIRED. Error code as specified in OAuth 2.0.
*/
:
string
;
/**
* OPTIONAL. Human-readable description of the error.
*/
?
:
string
;
/**
* OPTIONAL. URI to a human-readable web page with more information about the error.
*/
?
:
string
;
}
/**
* Response from the device authorization endpoint as per RFC 8628 section 3.2.
*/
export
interface
IAuthorizationDeviceResponse
{
/**
* REQUIRED. The device verification code.
*/
:
string
;
/**
* REQUIRED. The end-user verification code.
*/
:
string
;
/**
* REQUIRED. The end-user verification URI on the authorization server.
*/
:
string
;
/**
* OPTIONAL. A verification URI that includes the user_code, designed for non-textual transmission.
*/
?
:
string
;
/**
* REQUIRED. The lifetime in seconds of the device_code and user_code.
*/
:
number
;
/**
* OPTIONAL. The minimum amount of time in seconds that the client should wait between polling requests.
* If no value is provided, clients must use 5 as the default.
*/
?
:
number
;
}
/**
* Error response from the token endpoint when using device authorization grant.
* As defined in RFC 8628 section 3.5.
*/
export
interface
IAuthorizationErrorResponse
{
/**
* REQUIRED. Error code as specified in OAuth 2.0 or in RFC 8628 section 3.5.
*/
:
|
string
;
/**
* OPTIONAL. Human-readable description of the error.
*/
?
:
string
;
/**
* OPTIONAL. URI to a human-readable web page with more information about the error.
*/
?
:
string
;
}
/**
* Error response from the token endpoint when using device authorization grant.
* As defined in RFC 8628 section 3.5.
*/
export
interface
IAuthorizationDeviceTokenErrorResponse
extends
IAuthorizationErrorResponse
{
/**
* REQUIRED. Error code as specified in OAuth 2.0 or in RFC 8628 section 3.5.
*/
:
|
|
string
;
}
export
interface
IAuthorizationRegistrationErrorResponse
{
/**
* REQUIRED. Error code as specified in OAuth 2.0 or Dynamic Client Registration.
*/
:
|
string
;
/**
* OPTIONAL. Human-readable description of the error.
*/
?
:
string
;
}
export
interface
IAuthorizationJWTClaims
{
/**
* REQUIRED. JWT ID. Unique identifier for the token.
*/
:
string
;
/**
* REQUIRED. Subject. Principal about which the token asserts information.
*/
:
string
;
/**
* REQUIRED. Issuer. Entity that issued the token.
*/
:
string
;
/**
* OPTIONAL. Audience. Recipients that the token is intended for.
*/
?
:
string
|
string
[
]
;
/**
* OPTIONAL. Expiration time. Time after which the token is invalid (seconds since Unix epoch).
*/
?
:
number
;
/**
* OPTIONAL. Not before time. Time before which the token is not valid (seconds since Unix epoch).
*/
?
:
number
;
/**
* OPTIONAL. Issued at time when the token was issued (seconds since Unix epoch).
*/
?
:
number
;
/**
* OPTIONAL. Authorized party. The party to which the token was issued.
*/
?
:
string
;
/**
* OPTIONAL. Scope values for which the token is valid.
*/
?
:
string
;
/**
* OPTIONAL. Full name of the user.
*/
?
:
string
;
/**
* OPTIONAL. Given or first name of the user.
*/
?
:
string
;
/**
* OPTIONAL. Family name or last name of the user.
*/
?
:
string
;
/**
* OPTIONAL. Middle name of the user.
*/
?
:
string
;
/**
* OPTIONAL. Preferred username or email the user wishes to be referred to.
*/
?
:
string
;
/**
* OPTIONAL. Email address of the user.
*/
?
:
string
;
/**
* OPTIONAL. True if the user's email has been verified.
*/
?
:
boolean
;
/**
* OPTIONAL. User's profile picture URL.
*/
?
:
string
;
/**
* OPTIONAL. Authentication time. Time when the user authentication occurred.
*/
?
:
number
;
/**
* OPTIONAL. Authentication context class reference.
*/
/**
* Default port for the authorization flow. We try to use this port so that
* the redirect URI does not change when running on localhost. This is useful
* for servers that only allow exact matches on the redirect URI. The spec
* says that the port should not matter, but some servers do not follow
* the spec and require an exact match.
*/
// According to RFC 7235, multiple challenges are separated by commas
// But parameters within a challenge can also be separated by commas
// We need to identify scheme names to know where challenges start
// First, split by commas while respecting quoted strings
const
:
string
[
]
=
[
]
;
let
=
''
;
let
=
false
;
for
(
let
=
0
;
<
.
;
++
)
{
const
=
[
]
;
if
(
===
'"'
)
{
=
!
;
+=
;
}
else
if
(
===
','
&&
!
)
{
if
(
.
trim
(
)
)
{
.
push
(
.
trim
(
)
)
;
}
=
''
;
}
else
{
+=
;
}
}
if
(
.
trim
(
)
)
{
.
push
(
.
trim
(
)
)
;
}
// Now process tokens to identify challenges
// A challenge starts with a scheme name (a token that doesn't contain '=' and is followed by parameters or is standalone)
let
:
{
:
string
;
:
<
string
,
string
>
}
|
undefined
;
for
(
const
of
)
{
const
=
.
includes
(
'='
)
;
if
(
!
)
{
// This token doesn't have '=', so it's likely a scheme name
if
(
)
{
.
push
(
)
;
}
=
{
:
.
trim
(
)
,
:
{
}
}
;
}
else
{
// This token has '=', it could be:
// 1. A parameter for the current challenge
// 2. A new challenge that starts with "Scheme param=value"
const
=
.
indexOf
(
' '
)
;
if
(
>
0
)
{
const
=
.
substring
(
0
,
)
;
const
=
.
substring
(
+
1
)
;
// Check if what's before the space looks like a scheme name (no '=')
if
(
!
.
includes
(
'='
)
&&
.
includes
(
'='
)
)
{
// This is a new challenge starting with "Scheme param=value"
if
(
)
{
.
push
(
)
;
}
=
{
:
.
trim
(
)
,
:
{
}
}
;
// Parse the parameter part
const
=
.
indexOf
(
'='
)
;
if
(
>
0
)
{
const
=
.
substring
(
0
,
)
.
trim
(
)
;
const
=
.
substring
(
+
1
)
.
trim
(
)
.
replace
(
/^"|"$/g
,
''
)
;
if
(
&&
!==
undefined
)
{
.
[
]
=
;
}
}
continue
;
}
}
// This is a parameter for the current challenge
if
(
)
{
const
=
.
indexOf
(
'='
)
;
if
(
>
0
)
{
const
=
.
substring
(
0
,
)
.
trim
(
)
;
const
=
.
substring
(
+
1
)
.
trim
(
)
.
replace
(
/^"|"$/g
,
''
)
;
if
(
&&
!==
undefined
)
{
.
[
]
=
;
}
}
}
}
}
// Don't forget the last challenge
if
(
)
{
.
push
(
)
;
}
return
;
}
export
function
getClaimsFromJWT
(
:
string
)
:
{
const
=
.
split
(
'.'
)
;
if
(
.
!==
3
)
{
throw
new
Error
(
'Invalid JWT token format: token must have three parts separated by dots'
)
;
}
const
[
,
,
]
=
;
try
{
const
=
JSON
.
parse
(
decodeBase64
(
)
.
toString
(
)
)
;
if
(
typeof
!==
'object'
)
{
throw
new
Error
(
'Invalid JWT token format: header is not a JSON object'
)
;
}
const
=
JSON
.
parse
(
decodeBase64
(
)
.
toString
(
)
)
;
if
(
typeof
!==
'object'
)
{
throw
new
Error
(
'Invalid JWT token format: payload is not a JSON object'
)
;
}
return
;
}
catch
(
)
{
if
(
instanceof
Error
)
{
throw
new
Error
(
`Failed to parse JWT token: ${e.message}`
)
;
}
throw
new
Error
(
'Failed to parse JWT token'
)
;
}
}
/**
* Checks if two scope lists are equivalent, regardless of order.
* This is useful for comparing OAuth scopes where the order should not matter.
*
* @paramscopes1 First list of scopes to compare (can be undefined)
* @paramscopes2 Second list of scopes to compare (can be undefined)
* @returns true if the scope lists contain the same scopes (order-independent), false otherwise
*
* @example
* ```typescript
* scopesMatch(['read', 'write'], ['write', 'read']) // Returns: true
* scopesMatch(['read'], ['write']) // Returns: false
* scopesMatch(undefined, undefined) // Returns: true
* scopesMatch(['read'], undefined) // Returns: false
* ```
*/
export
function
scopesMatch
(
:
readonly
string
[
]
|
undefined
,
:
readonly
string
[
]
|
undefined
)
:
boolean
{
if
(
===
)
{
return
true
;
}
if
(
!
||
!
)
{
return
false
;
}
if
(
.
!==
.
)
{
return
false
;
}
// Sort both arrays for comparison to handle different orderings
const
=
[
...
]
.
sort
(
)
;
const
=
[
...
]
.
sort
(
)
;
return
.
every
(
(
,
)
=>
===
[
]
)
;
}
interface
CommonResponse
{
:
number
;
:
string
;
json
(
)
:
Promise
<
unknown
>
;
text
(
)
:
Promise
<
string
>
;
}
interface
IFetcher
{
(
:
string
,
:
{
:
string
;
:
<
string
,
string
>
}
)
:
Promise
<
>
;
}
export
interface
IFetchResourceMetadataOptions
{
/**
* Headers to include only when the resource metadata URL has the same origin as the target resource
*/
?
:
<
string
,
string
>
;
/**
* Optional custom fetch implementation (defaults to global fetch)
*/
?
:
;
}
/**
* Fetches and validates OAuth 2.0 protected resource metadata from the given URL.
*
* @paramtargetResource The target resource URL to compare origins with (e.g., the MCP server URL)
* @paramresourceMetadataUrl Optional URL to fetch the resource metadata from. If not provided, will try well-known URIs.
* @paramoptions Configuration options for the fetch operation
* @returns Promise that resolves to an object containing the validated resource metadata and any errors encountered during discovery
* @throws Error if the fetch fails, returns non-200 status, or the response is invalid on all attempted URLs
*/
export
async
function
fetchResourceMetadata
(
:
string
,
:
string
|
undefined
,
:
=
{
}
)
:
Promise
<
{
:
;
:
string
;
:
[
]
}
>
{
const
{
=
{
}
,
:
=
}
=
;
const
=
new
URL
(
)
;
const
fetchPrm
=
async
(
:
string
,
:
string
)
=>
{
// Determine if we should include same-origin headers
let
:
<
string
,
string
>
=
{
'Accept'
:
'application/json'
}
;
const
=
new
URL
(
)
;
if
(
.
===
.
)
{
=
{
...
,
...
}
;
}
const
=
await
fetchImpl
(
,
{
:
'GET'
,
}
)
;
if
(
.
!==
200
)
{
let
:
string
;
try
{
=
await
.
text
(
)
;
}
catch
{
=
.
;
}
throw
new
Error
(
`Failed to fetch resource metadata from ${prmUrl}: ${response.status}${errorText}`
)
;
}
const
=
await
.
json
(
)
;
if
(
isAuthorizationProtectedResourceMetadata
(
)
)
{
// Validate that the resource matches the target resource
// Use URL constructor for normalization - it handles hostname case and trailing slashes
const
=
new
URL
(
.
)
.
toString
(
)
;
const
=
new
URL
(
)
.
toString
(
)
;
if
(
!==
)
{
throw
new
Error
(
`Protected Resource Metadata 'resource' property value "${prmValue}" does not match expected value "${expectedResource}" for URL ${prmUrl}. Per RFC 9728, these MUST match. See https://datatracker.ietf.org/doc/html/rfc9728#PRConfigurationValidation`
)
;
}
return
;
}
else
{
throw
new
Error
(
`Invalid resource metadata from ${prmUrl}. Expected to follow shape of https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata (Hints: is scopes_supported an array? Is resource a string?). Current payload: ${JSON.stringify(body)}`
)
;
}
}
;
const
:
[
]
=
[
]
;
if
(
)
{
try
{
const
=
await
fetchPrm
(
,
)
;
return
{
,
:
,
}
;
}
catch
(
)
{
.
push
(
instanceof
Error
?
:
new
Error
(
String
(
)
)
)
;
}
}
// Try well-known URIs starting with path-appended, then root
// If we've tried all methods and none worked, throw the error(s)
if
(
.
===
1
)
{
throw
[
0
]
;
}
else
{
throw
new
AggregateError
(
,
'Failed to fetch resource metadata from all attempted URLs'
)
;
}
}
export
interface
IFetchAuthorizationServerMetadataOptions
{
/**
* Headers to include in the requests
*/
?
:
<
string
,
string
>
;
/**
* Optional custom fetch implementation (defaults to global fetch)
*/
?
:
;
}
/** Helper to try parsing the response as authorization server metadata */
async
function
tryParseAuthServerMetadata
(
:
)
:
Promise
<
|
undefined
>
{
if
(
.
!==
200
)
{
return
undefined
;
}
try
{
const
=
await
.
json
(
)
;
if
(
isAuthorizationServerMetadata
(
)
)
{
return
;
}
}
catch
{
// Failed to parse as JSON or not valid metadata
}
return
undefined
;
}
/** Helper to get error text from response */
async
function
getErrText
(
:
)
:
Promise
<
string
>
{
try
{
return
await
.
text
(
)
;
}
catch
{
return
.
;
}
}
/**
* Fetches and validates OAuth 2.0 authorization server metadata from the given authorization server URL.
*
* This function tries multiple discovery endpoints in the following order:
* 1. OAuth 2.0 Authorization Server Metadata with path insertion (RFC 8414)
* 2. OpenID Connect Discovery with path insertion
* 3. OpenID Connect Discovery with path addition
*
* Path insertion: For issuer URLs with path components (e.g., https://example.com/tenant),
* the well-known path is inserted after the origin and before the path:
* https://example.com/.well-known/oauth-authorization-server/tenant
*
* Path addition: The well-known path is simply appended to the existing path:
* https://example.com/tenant/.well-known/openid-configuration
*
* @paramauthorizationServer The authorization server URL (issuer identifier)
* @paramoptions Configuration options for the fetch operation
* @returns Promise that resolves to the validated authorization server metadata
* @throws Error if all discovery attempts fail or the response is invalid
*
* @see https://datatracker.ietf.org/doc/html/rfc8414#section-3
*/
export
async
function
fetchAuthorizationServerMetadata
(
:
string
,
:
=
{
}
)
:
Promise
<
{
:
;
:
string
;
:
[
]
}
>
{
const
{
=
{
}
,
:
=
}
=
;
const
=
new
URL
(
)
;
const
=
.
===
'/'
?
''
:
.
;
const
:
[
]
=
[
]
;
const
=
async
(
:
string
)
:
Promise
<
|
undefined
>
=>
{
try
{
const
=
await
fetchImpl
(
,
{
:
'GET'
,
:
{
...
,
'Accept'
:
'application/json'
}
}
)
;
const
=
await
tryParseAuthServerMetadata
(
)
;
if
(
)
{
return
;
}
// No metadata found, collect error from response
.
push
(
new
Error
(
`Failed to fetch authorization server metadata from ${url}: ${rawResponse.status}${awaitgetErrText(rawResponse)}`
)
)
;
return
undefined
;
}
catch
(
)
{
// Collect error from fetch failure
.
push
(
instanceof
Error
?
:
new
Error
(
String
(
)
)
)
;
return
undefined
;
}
}
;
// For the oauth server metadata discovery path, we _INSERT_
// the well known path after the origin and before the path.