@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
3 lines (2 loc) • 33.3 kB
JavaScript
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
import{fetchWithinOrigin,unfollowedRedirect}from"./chunk-YP72RYUP.js";import{LATEST_PROTOCOL_VERSION}from"./chunk-PM3CCDYH.js";import{ZodIssueCode,any,array,boolean,coerce_exports,literal,looseObject,number,object,string,url}from"./chunk-36BLGKRO.js";import{NEVER}from"./chunk-FKX6EWFV.js";var crypto;crypto=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then(m=>m.webcrypto);async function getRandomValues(size){return(await crypto).getRandomValues(new Uint8Array(size))}async function random(size){let mask="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",evenDistCutoff=Math.pow(2,8)-Math.pow(2,8)%mask.length,result="";for(;result.length<size;){let randomBytes=await getRandomValues(size-result.length);for(let randomByte of randomBytes)randomByte<evenDistCutoff&&(result+=mask[randomByte%mask.length])}return result}async function generateVerifier(length){return await random(length)}async function generateChallenge(code_verifier){let buffer=await(await crypto).subtle.digest("SHA-256",new TextEncoder().encode(code_verifier));return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function pkceChallenge(length){if(length||(length=43),length<43||length>128)throw`Expected a length between 43 and 128. Received ${length}.`;let verifier=await generateVerifier(length),challenge=await generateChallenge(verifier);return{code_verifier:verifier,code_challenge:challenge}}var SafeUrlSchema=url().superRefine((val,ctx)=>{if(!URL.canParse(val))return ctx.addIssue({code:ZodIssueCode.custom,message:"URL must be parseable",fatal:!0}),NEVER}).refine(url2=>{let u=new URL(url2);return u.protocol!=="javascript:"&&u.protocol!=="data:"&&u.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),OAuthProtectedResourceMetadataSchema=looseObject({resource:string().url(),authorization_servers:array(SafeUrlSchema).optional(),jwks_uri:string().url().optional(),scopes_supported:array(string()).optional(),bearer_methods_supported:array(string()).optional(),resource_signing_alg_values_supported:array(string()).optional(),resource_name:string().optional(),resource_documentation:string().optional(),resource_policy_uri:string().url().optional(),resource_tos_uri:string().url().optional(),tls_client_certificate_bound_access_tokens:boolean().optional(),authorization_details_types_supported:array(string()).optional(),dpop_signing_alg_values_supported:array(string()).optional(),dpop_bound_access_tokens_required:boolean().optional()}),OAuthMetadataSchema=looseObject({issuer:string(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:array(string()).optional(),response_types_supported:array(string()),response_modes_supported:array(string()).optional(),grant_types_supported:array(string()).optional(),token_endpoint_auth_methods_supported:array(string()).optional(),token_endpoint_auth_signing_alg_values_supported:array(string()).optional(),service_documentation:SafeUrlSchema.optional(),revocation_endpoint:SafeUrlSchema.optional(),revocation_endpoint_auth_methods_supported:array(string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:array(string()).optional(),introspection_endpoint:string().optional(),introspection_endpoint_auth_methods_supported:array(string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:array(string()).optional(),code_challenge_methods_supported:array(string()).optional(),client_id_metadata_document_supported:boolean().optional()}),OpenIdProviderMetadataSchema=looseObject({issuer:string(),authorization_endpoint:SafeUrlSchema,token_endpoint:SafeUrlSchema,userinfo_endpoint:SafeUrlSchema.optional(),jwks_uri:SafeUrlSchema,registration_endpoint:SafeUrlSchema.optional(),scopes_supported:array(string()).optional(),response_types_supported:array(string()),response_modes_supported:array(string()).optional(),grant_types_supported:array(string()).optional(),acr_values_supported:array(string()).optional(),subject_types_supported:array(string()),id_token_signing_alg_values_supported:array(string()),id_token_encryption_alg_values_supported:array(string()).optional(),id_token_encryption_enc_values_supported:array(string()).optional(),userinfo_signing_alg_values_supported:array(string()).optional(),userinfo_encryption_alg_values_supported:array(string()).optional(),userinfo_encryption_enc_values_supported:array(string()).optional(),request_object_signing_alg_values_supported:array(string()).optional(),request_object_encryption_alg_values_supported:array(string()).optional(),request_object_encryption_enc_values_supported:array(string()).optional(),token_endpoint_auth_methods_supported:array(string()).optional(),token_endpoint_auth_signing_alg_values_supported:array(string()).optional(),display_values_supported:array(string()).optional(),claim_types_supported:array(string()).optional(),claims_supported:array(string()).optional(),service_documentation:string().optional(),claims_locales_supported:array(string()).optional(),ui_locales_supported:array(string()).optional(),claims_parameter_supported:boolean().optional(),request_parameter_supported:boolean().optional(),request_uri_parameter_supported:boolean().optional(),require_request_uri_registration:boolean().optional(),op_policy_uri:SafeUrlSchema.optional(),op_tos_uri:SafeUrlSchema.optional(),client_id_metadata_document_supported:boolean().optional()}),OpenIdProviderDiscoveryMetadataSchema=object({...OpenIdProviderMetadataSchema.shape,...OAuthMetadataSchema.pick({code_challenge_methods_supported:!0}).shape}),OAuthTokensSchema=object({access_token:string(),id_token:string().optional(),token_type:string(),expires_in:coerce_exports.number().optional(),scope:string().optional(),refresh_token:string().optional(),issuer:string().optional().catch(void 0)}).strip(),OAuthErrorResponseSchema=object({error:string(),error_description:string().optional(),error_uri:string().optional()}),OptionalSafeUrlSchema=SafeUrlSchema.optional().or(literal("").transform(()=>{})),OAuthClientMetadataSchema=object({redirect_uris:array(SafeUrlSchema),token_endpoint_auth_method:string().optional(),grant_types:array(string()).optional(),response_types:array(string()).optional(),client_name:string().optional(),client_uri:SafeUrlSchema.optional(),logo_uri:OptionalSafeUrlSchema,scope:string().optional(),contacts:array(string()).optional(),tos_uri:OptionalSafeUrlSchema,policy_uri:string().optional(),jwks_uri:SafeUrlSchema.optional(),jwks:any().optional(),software_id:string().optional(),software_version:string().optional(),software_statement:string().optional()}).strip(),OAuthClientInformationSchema=object({client_id:string(),client_secret:string().optional(),client_id_issued_at:number().optional(),client_secret_expires_at:number().optional(),issuer:string().optional().catch(void 0)}).strip(),OAuthClientInformationFullSchema=OAuthClientMetadataSchema.merge(OAuthClientInformationSchema),OAuthClientRegistrationErrorSchema=object({error:string(),error_description:string().optional()}).strip(),OAuthTokenRevocationRequestSchema=object({token:string(),token_type_hint:string().optional()}).strip();function resourceUrlFromServerUrl(url2){let resourceURL=typeof url2=="string"?new URL(url2):new URL(url2.href);return resourceURL.hash="",resourceURL}function checkResourceAllowed({requestedResource,configuredResource}){let requested=typeof requestedResource=="string"?new URL(requestedResource):new URL(requestedResource.href),configured=typeof configuredResource=="string"?new URL(configuredResource):new URL(configuredResource.href);if(requested.origin!==configured.origin||requested.pathname.length<configured.pathname.length)return!1;let requestedPath=requested.pathname.endsWith("/")?requested.pathname:requested.pathname+"/",configuredPath=configured.pathname.endsWith("/")?configured.pathname:configured.pathname+"/";return requestedPath.startsWith(configuredPath)}var OAuthError=class extends Error{constructor(message,errorUri){super(message),this.errorUri=errorUri,this.name=this.constructor.name}toResponseObject(){let response={error:this.errorCode,error_description:this.message};return this.errorUri&&(response.error_uri=this.errorUri),response}get errorCode(){return this.constructor.errorCode}},InvalidRequestError=class extends OAuthError{};InvalidRequestError.errorCode="invalid_request";var InvalidClientError=class extends OAuthError{};InvalidClientError.errorCode="invalid_client";var InvalidGrantError=class extends OAuthError{};InvalidGrantError.errorCode="invalid_grant";var UnauthorizedClientError=class extends OAuthError{};UnauthorizedClientError.errorCode="unauthorized_client";var UnsupportedGrantTypeError=class extends OAuthError{};UnsupportedGrantTypeError.errorCode="unsupported_grant_type";var InvalidScopeError=class extends OAuthError{};InvalidScopeError.errorCode="invalid_scope";var AccessDeniedError=class extends OAuthError{};AccessDeniedError.errorCode="access_denied";var ServerError=class extends OAuthError{};ServerError.errorCode="server_error";var TemporarilyUnavailableError=class extends OAuthError{};TemporarilyUnavailableError.errorCode="temporarily_unavailable";var UnsupportedResponseTypeError=class extends OAuthError{};UnsupportedResponseTypeError.errorCode="unsupported_response_type";var UnsupportedTokenTypeError=class extends OAuthError{};UnsupportedTokenTypeError.errorCode="unsupported_token_type";var InvalidTokenError=class extends OAuthError{};InvalidTokenError.errorCode="invalid_token";var MethodNotAllowedError=class extends OAuthError{};MethodNotAllowedError.errorCode="method_not_allowed";var TooManyRequestsError=class extends OAuthError{};TooManyRequestsError.errorCode="too_many_requests";var InvalidClientMetadataError=class extends OAuthError{};InvalidClientMetadataError.errorCode="invalid_client_metadata";var InsufficientScopeError=class extends OAuthError{};InsufficientScopeError.errorCode="insufficient_scope";var InvalidTargetError=class extends OAuthError{};InvalidTargetError.errorCode="invalid_target";var OAUTH_ERRORS={[InvalidRequestError.errorCode]:InvalidRequestError,[InvalidClientError.errorCode]:InvalidClientError,[InvalidGrantError.errorCode]:InvalidGrantError,[UnauthorizedClientError.errorCode]:UnauthorizedClientError,[UnsupportedGrantTypeError.errorCode]:UnsupportedGrantTypeError,[InvalidScopeError.errorCode]:InvalidScopeError,[AccessDeniedError.errorCode]:AccessDeniedError,[ServerError.errorCode]:ServerError,[TemporarilyUnavailableError.errorCode]:TemporarilyUnavailableError,[UnsupportedResponseTypeError.errorCode]:UnsupportedResponseTypeError,[UnsupportedTokenTypeError.errorCode]:UnsupportedTokenTypeError,[InvalidTokenError.errorCode]:InvalidTokenError,[MethodNotAllowedError.errorCode]:MethodNotAllowedError,[TooManyRequestsError.errorCode]:TooManyRequestsError,[InvalidClientMetadataError.errorCode]:InvalidClientMetadataError,[InsufficientScopeError.errorCode]:InsufficientScopeError,[InvalidTargetError.errorCode]:InvalidTargetError};var UnauthorizedError=class extends Error{constructor(message){super(message??"Unauthorized")}};function isClientAuthMethod(method){return["client_secret_basic","client_secret_post","none"].includes(method)}var AUTHORIZATION_CODE_RESPONSE_TYPE="code",AUTHORIZATION_CODE_CHALLENGE_METHOD="S256";function selectClientAuthMethod(clientInformation,supportedMethods){let hasClientSecret=clientInformation.client_secret!==void 0;return"token_endpoint_auth_method"in clientInformation&&clientInformation.token_endpoint_auth_method&&isClientAuthMethod(clientInformation.token_endpoint_auth_method)&&(supportedMethods.length===0||supportedMethods.includes(clientInformation.token_endpoint_auth_method))?clientInformation.token_endpoint_auth_method:supportedMethods.length===0?hasClientSecret?"client_secret_basic":"none":hasClientSecret&&supportedMethods.includes("client_secret_basic")?"client_secret_basic":hasClientSecret&&supportedMethods.includes("client_secret_post")?"client_secret_post":supportedMethods.includes("none")?"none":hasClientSecret?"client_secret_post":"none"}function applyClientAuthentication(method,clientInformation,headers,params){let{client_id,client_secret}=clientInformation;switch(method){case"client_secret_basic":applyBasicAuth(client_id,client_secret,headers);return;case"client_secret_post":applyPostAuth(client_id,client_secret,params);return;case"none":applyPublicAuth(client_id,params);return;default:throw new Error(`Unsupported client authentication method: ${method}`)}}function applyBasicAuth(clientId,clientSecret,headers){if(!clientSecret)throw new Error("client_secret_basic authentication requires a client_secret");let credentials=btoa(`${clientId}:${clientSecret}`);headers.set("Authorization",`Basic ${credentials}`)}function applyPostAuth(clientId,clientSecret,params){params.set("client_id",clientId),clientSecret&¶ms.set("client_secret",clientSecret)}function applyPublicAuth(clientId,params){params.set("client_id",clientId)}async function parseErrorResponse(input){let statusCode=input instanceof Response?input.status:void 0,body=input instanceof Response?await input.text():input;try{let result=OAuthErrorResponseSchema.parse(JSON.parse(body)),{error,error_description,error_uri}=result,errorClass=OAUTH_ERRORS[error]||ServerError;return new errorClass(error_description||"",error_uri)}catch(error){let redirect=input instanceof Response?unfollowedRedirect(input,input.url):void 0,errorMessage=`${statusCode?`HTTP ${statusCode}: `:""}${redirect??`Invalid OAuth error response: ${error}. Raw body: ${body}`}`;return new ServerError(errorMessage)}}function issuersMatch(a,b){let[x,y]=[a,b];try{[x,y]=[new URL(a).href,new URL(b).href]}catch{}return x===y||x.endsWith("/")&&x.slice(0,-1)===y||y.endsWith("/")&&y.slice(0,-1)===x}function discardIfIssuerMismatch(stored,issuer){if(stored)return typeof stored.issuer!="string"?stored.issuer==null?stored:{...stored,issuer:void 0}:issuersMatch(stored.issuer,issuer)?stored:void 0}var TokenResponseSchema=OAuthTokensSchema.omit({issuer:!0}),RegistrationResponseSchema=OAuthClientInformationFullSchema.omit({issuer:!0});function boundElsewhereError(stored,issuer){return new Error(`OAuth client information is bound to authorization server ${stored.issuer} and is not presented to ${issuer}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`)}async function auth(provider,options){try{return await authInternal(provider,options)}catch(error){if(error instanceof InvalidClientError||error instanceof UnauthorizedClientError)return await provider.invalidateCredentials?.("all"),await authInternal(provider,options);if(error instanceof InvalidGrantError)return await provider.invalidateCredentials?.("tokens"),await authInternal(provider,options);throw error}}async function authInternal(provider,{serverUrl,authorizationCode,scope,resourceMetadataUrl,fetchFn}){let cachedState=await provider.discoveryState?.(),resourceMetadata,authorizationServerUrl,metadata,effectiveResourceMetadataUrl=resourceMetadataUrl;if(!effectiveResourceMetadataUrl&&cachedState?.resourceMetadataUrl&&(effectiveResourceMetadataUrl=new URL(cachedState.resourceMetadataUrl)),cachedState?.authorizationServerUrl){if(authorizationServerUrl=cachedState.authorizationServerUrl,resourceMetadata=cachedState.resourceMetadata,metadata=cachedState.authorizationServerMetadata??await discoverAuthorizationServerMetadata(authorizationServerUrl,{fetchFn}),!resourceMetadata)try{resourceMetadata=await discoverOAuthProtectedResourceMetadata(serverUrl,{resourceMetadataUrl:effectiveResourceMetadataUrl},fetchFn)}catch{}(metadata!==cachedState.authorizationServerMetadata||resourceMetadata!==cachedState.resourceMetadata)&&await provider.saveDiscoveryState?.({authorizationServerUrl:String(authorizationServerUrl),resourceMetadataUrl:effectiveResourceMetadataUrl?.toString(),resourceMetadata,authorizationServerMetadata:metadata})}else{let serverInfo=await discoverOAuthServerInfo(serverUrl,{resourceMetadataUrl:effectiveResourceMetadataUrl,fetchFn});authorizationServerUrl=serverInfo.authorizationServerUrl,metadata=serverInfo.authorizationServerMetadata,resourceMetadata=serverInfo.resourceMetadata,await provider.saveDiscoveryState?.({authorizationServerUrl:String(authorizationServerUrl),resourceMetadataUrl:effectiveResourceMetadataUrl?.toString(),resourceMetadata,authorizationServerMetadata:metadata})}let issuer=String(authorizationServerUrl),selectedResource=await selectResourceURL(serverUrl,provider,resourceMetadata),resource=selectedResource&&resourceMetadata&&!provider.validateResourceURL?resourceMetadata.resource:selectedResource,resolvedScope=scope||resourceMetadata?.scopes_supported?.join(" ")||provider.clientMetadata.scope,storedClientInformation=await Promise.resolve(provider.clientInformation()),clientInformation=discardIfIssuerMismatch(storedClientInformation,issuer),canRegisterAgain=provider.saveClientInformation!==void 0&&!!provider.redirectUrl;if(storedClientInformation&&!clientInformation&&!canRegisterAgain)throw boundElsewhereError(storedClientInformation,issuer);let unstampedClientInformation=clientInformation?.issuer==null?clientInformation:void 0,bindClientInformation=async()=>{try{unstampedClientInformation&&await provider.saveClientInformation?.({...unstampedClientInformation,issuer})}catch{}};if(!clientInformation){if(authorizationCode!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let supportsUrlBasedClientId=metadata?.client_id_metadata_document_supported===!0,clientMetadataUrl=provider.clientMetadataUrl;if(clientMetadataUrl&&!isHttpsUrl(clientMetadataUrl))throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);if(supportsUrlBasedClientId&&clientMetadataUrl)clientInformation={client_id:clientMetadataUrl,issuer},await provider.saveClientInformation?.(clientInformation);else{if(!provider.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");clientInformation={...await registerClient(authorizationServerUrl,{metadata,clientMetadata:provider.clientMetadata,scope:resolvedScope,fetchFn}),issuer},await provider.saveClientInformation(clientInformation)}}let nonInteractiveFlow=!provider.redirectUrl;if(authorizationCode!==void 0||nonInteractiveFlow){let tokens2=await fetchToken(provider,authorizationServerUrl,{metadata,resource,authorizationCode,fetchFn});return await bindClientInformation(),await provider.saveTokens({...tokens2,issuer}),"AUTHORIZED"}let tokens=discardIfIssuerMismatch(await provider.tokens(),issuer);if(tokens?.refresh_token&&tokens.issuer==null&&console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged."),tokens?.refresh_token)try{let newTokens=await refreshAuthorization(authorizationServerUrl,{metadata,clientInformation,refreshToken:tokens.refresh_token,resource,addClientAuthentication:provider.addClientAuthentication,fetchFn});return await bindClientInformation(),await provider.saveTokens({...newTokens,issuer}),"AUTHORIZED"}catch(error){if(!(!(error instanceof OAuthError)||error instanceof ServerError))throw error}let state=provider.state?await provider.state():void 0,{authorizationUrl,codeVerifier}=await startAuthorization(authorizationServerUrl,{metadata,clientInformation,state,redirectUrl:provider.redirectUrl,scope:resolvedScope,resource});return await provider.saveCodeVerifier(codeVerifier),await provider.redirectToAuthorization(authorizationUrl),"REDIRECT"}function isHttpsUrl(value){if(!value)return!1;try{let url2=new URL(value);return url2.protocol==="https:"&&url2.pathname!=="/"}catch{return!1}}async function selectResourceURL(serverUrl,provider,resourceMetadata){let defaultResource=resourceUrlFromServerUrl(serverUrl);if(provider.validateResourceURL)return await provider.validateResourceURL(defaultResource,resourceMetadata?.resource);if(resourceMetadata){if(!checkResourceAllowed({requestedResource:defaultResource,configuredResource:resourceMetadata.resource}))throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);return new URL(resourceMetadata.resource)}}function extractWWWAuthenticateParams(res){let authenticateHeader=res.headers.get("WWW-Authenticate");if(!authenticateHeader)return{};let[type,scheme]=authenticateHeader.split(" ");if(type.toLowerCase()!=="bearer"||!scheme)return{};let resourceMetadataMatch=extractFieldFromWwwAuth(res,"resource_metadata")||void 0,resourceMetadataUrl;if(resourceMetadataMatch)try{resourceMetadataUrl=new URL(resourceMetadataMatch)}catch{}let scope=extractFieldFromWwwAuth(res,"scope")||void 0,error=extractFieldFromWwwAuth(res,"error")||void 0;return{resourceMetadataUrl,scope,error}}function extractFieldFromWwwAuth(response,fieldName){let wwwAuthHeader=response.headers.get("WWW-Authenticate");if(!wwwAuthHeader)return null;let pattern=new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`),match=wwwAuthHeader.match(pattern);return match?match[1]||match[2]:null}function extractResourceMetadataUrl(res){let authenticateHeader=res.headers.get("WWW-Authenticate");if(!authenticateHeader)return;let[type,scheme]=authenticateHeader.split(" ");if(type.toLowerCase()!=="bearer"||!scheme)return;let match=/resource_metadata="([^"]*)"/.exec(authenticateHeader);if(match)try{return new URL(match[1])}catch{return}}async function discoverOAuthProtectedResourceMetadata(serverUrl,opts,fetchFn=fetch){let response=await discoverMetadataWithFallback(serverUrl,"oauth-protected-resource",fetchFn,{protocolVersion:opts?.protocolVersion,metadataUrl:opts?.resourceMetadataUrl});if(!response||response.status===404)throw await response?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!response.ok)throw await response.body?.cancel(),new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);return OAuthProtectedResourceMetadataSchema.parse(await response.json())}async function fetchWithCorsRetry(url2,headers,fetchFn=fetch){try{return await fetchWithinOrigin(fetchFn)(url2,{headers})}catch(error){if(error instanceof TypeError)return headers?fetchWithCorsRetry(url2,void 0,fetchFn):void 0;throw error}}function buildWellKnownPath(wellKnownPrefix,pathname="",options={}){return pathname.endsWith("/")&&(pathname=pathname.slice(0,-1)),options.prependPathname?`${pathname}/.well-known/${wellKnownPrefix}`:`/.well-known/${wellKnownPrefix}${pathname}`}async function tryMetadataDiscovery(url2,protocolVersion,fetchFn=fetch){return await fetchWithCorsRetry(url2,{"MCP-Protocol-Version":protocolVersion},fetchFn)}function shouldAttemptFallback(response,pathname){return!response||!response.ok&&response.status<500&&pathname!=="/"}async function discoverMetadataWithFallback(serverUrl,wellKnownType,fetchFn,opts){let issuer=new URL(serverUrl),protocolVersion=opts?.protocolVersion??LATEST_PROTOCOL_VERSION,url2;if(opts?.metadataUrl)url2=new URL(opts.metadataUrl);else{let wellKnownPath=buildWellKnownPath(wellKnownType,issuer.pathname);url2=new URL(wellKnownPath,opts?.metadataServerUrl??issuer),url2.search=issuer.search}let response=await tryMetadataDiscovery(url2,protocolVersion,fetchFn);if(!opts?.metadataUrl&&shouldAttemptFallback(response,issuer.pathname)){let rootUrl=new URL(`/.well-known/${wellKnownType}`,issuer);response=await tryMetadataDiscovery(rootUrl,protocolVersion,fetchFn)}return response}async function discoverOAuthMetadata(issuer,{authorizationServerUrl,protocolVersion}={},fetchFn=fetch){typeof issuer=="string"&&(issuer=new URL(issuer)),authorizationServerUrl||(authorizationServerUrl=issuer),typeof authorizationServerUrl=="string"&&(authorizationServerUrl=new URL(authorizationServerUrl)),protocolVersion??(protocolVersion=LATEST_PROTOCOL_VERSION);let response=await discoverMetadataWithFallback(authorizationServerUrl,"oauth-authorization-server",fetchFn,{protocolVersion,metadataServerUrl:authorizationServerUrl});if(!response||response.status===404){await response?.body?.cancel();return}if(!response.ok)throw await response.body?.cancel(),new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`);return OAuthMetadataSchema.parse(await response.json())}function buildDiscoveryUrls(authorizationServerUrl){let url2=typeof authorizationServerUrl=="string"?new URL(authorizationServerUrl):authorizationServerUrl,hasPath=url2.pathname!=="/",urlsToTry=[];if(!hasPath)return urlsToTry.push({url:new URL("/.well-known/oauth-authorization-server",url2.origin),type:"oauth"}),urlsToTry.push({url:new URL("/.well-known/openid-configuration",url2.origin),type:"oidc"}),urlsToTry;let pathname=url2.pathname;return pathname.endsWith("/")&&(pathname=pathname.slice(0,-1)),urlsToTry.push({url:new URL(`/.well-known/oauth-authorization-server${pathname}`,url2.origin),type:"oauth"}),urlsToTry.push({url:new URL(`/.well-known/openid-configuration${pathname}`,url2.origin),type:"oidc"}),urlsToTry.push({url:new URL(`${pathname}/.well-known/openid-configuration`,url2.origin),type:"oidc"}),urlsToTry}async function discoverAuthorizationServerMetadata(authorizationServerUrl,{fetchFn=fetch,protocolVersion=LATEST_PROTOCOL_VERSION}={}){let headers={"MCP-Protocol-Version":protocolVersion,Accept:"application/json"},urlsToTry=buildDiscoveryUrls(authorizationServerUrl);for(let{url:endpointUrl,type}of urlsToTry){let response=await fetchWithCorsRetry(endpointUrl,headers,fetchFn);if(response){if(!response.ok){if(await response.body?.cancel(),response.status<500)continue;throw new Error(`HTTP ${response.status} trying to load ${type==="oauth"?"OAuth":"OpenID provider"} metadata from ${endpointUrl}`)}return type==="oauth"?OAuthMetadataSchema.parse(await response.json()):OpenIdProviderDiscoveryMetadataSchema.parse(await response.json())}}}async function discoverOAuthServerInfo(serverUrl,opts){let resourceMetadata,authorizationServerUrl;try{resourceMetadata=await discoverOAuthProtectedResourceMetadata(serverUrl,{resourceMetadataUrl:opts?.resourceMetadataUrl},opts?.fetchFn),resourceMetadata.authorization_servers&&resourceMetadata.authorization_servers.length>0&&(authorizationServerUrl=resourceMetadata.authorization_servers[0])}catch{}authorizationServerUrl||(authorizationServerUrl=String(new URL("/",serverUrl)));let authorizationServerMetadata=await discoverAuthorizationServerMetadata(authorizationServerUrl,{fetchFn:opts?.fetchFn});return{authorizationServerUrl,authorizationServerMetadata,resourceMetadata}}function resourceIndicatorToString(resource){return typeof resource=="string"?resource:resource.href}async function startAuthorization(authorizationServerUrl,{metadata,clientInformation,redirectUrl,scope,state,resource}){let authorizationUrl;if(metadata){if(authorizationUrl=new URL(metadata.authorization_endpoint),!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE))throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);if(metadata.code_challenge_methods_supported&&!metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD))throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`)}else authorizationUrl=new URL("/authorize",authorizationServerUrl);let challenge=await pkceChallenge(),codeVerifier=challenge.code_verifier,codeChallenge=challenge.code_challenge;return authorizationUrl.searchParams.set("response_type",AUTHORIZATION_CODE_RESPONSE_TYPE),authorizationUrl.searchParams.set("client_id",clientInformation.client_id),authorizationUrl.searchParams.set("code_challenge",codeChallenge),authorizationUrl.searchParams.set("code_challenge_method",AUTHORIZATION_CODE_CHALLENGE_METHOD),authorizationUrl.searchParams.set("redirect_uri",String(redirectUrl)),state&&authorizationUrl.searchParams.set("state",state),scope&&authorizationUrl.searchParams.set("scope",scope),scope?.includes("offline_access")&&authorizationUrl.searchParams.append("prompt","consent"),resource&&authorizationUrl.searchParams.set("resource",resourceIndicatorToString(resource)),{authorizationUrl,codeVerifier}}function prepareAuthorizationCodeRequest(authorizationCode,codeVerifier,redirectUri){return new URLSearchParams({grant_type:"authorization_code",code:authorizationCode,code_verifier:codeVerifier,redirect_uri:String(redirectUri)})}async function executeTokenRequest(authorizationServerUrl,{metadata,tokenRequestParams,clientInformation,addClientAuthentication,resource,fetchFn}){let tokenUrl=metadata?.token_endpoint?new URL(metadata.token_endpoint):new URL("/token",authorizationServerUrl),headers=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(resource&&tokenRequestParams.set("resource",resourceIndicatorToString(resource)),addClientAuthentication)await addClientAuthentication(headers,tokenRequestParams,tokenUrl,metadata);else if(clientInformation){let supportedMethods=metadata?.token_endpoint_auth_methods_supported??[],authMethod=selectClientAuthMethod(clientInformation,supportedMethods);applyClientAuthentication(authMethod,clientInformation,headers,tokenRequestParams)}let response=await fetchWithinOrigin(fetchFn??fetch)(tokenUrl,{method:"POST",headers,body:tokenRequestParams});if(!response.ok)throw await parseErrorResponse(response);return TokenResponseSchema.parse(await response.json())}async function exchangeAuthorization(authorizationServerUrl,{metadata,clientInformation,authorizationCode,codeVerifier,redirectUri,resource,addClientAuthentication,fetchFn}){let tokenRequestParams=prepareAuthorizationCodeRequest(authorizationCode,codeVerifier,redirectUri);return executeTokenRequest(authorizationServerUrl,{metadata,tokenRequestParams,clientInformation,addClientAuthentication,resource,fetchFn})}async function refreshAuthorization(authorizationServerUrl,{metadata,clientInformation,refreshToken,resource,addClientAuthentication,fetchFn}){let tokenRequestParams=new URLSearchParams({grant_type:"refresh_token",refresh_token:refreshToken}),tokens=await executeTokenRequest(authorizationServerUrl,{metadata,tokenRequestParams,clientInformation,addClientAuthentication,resource,fetchFn});return{refresh_token:refreshToken,...tokens}}async function fetchToken(provider,authorizationServerUrl,{metadata,resource,authorizationCode,fetchFn}={}){let readClientInformation=async()=>{let storedClientInformation=await provider.clientInformation(),checked=discardIfIssuerMismatch(storedClientInformation,String(authorizationServerUrl));if(storedClientInformation&&!checked)throw boundElsewhereError(storedClientInformation,String(authorizationServerUrl));return checked},clientInformation=await readClientInformation(),scope=provider.clientMetadata.scope,tokenRequestParams;if(provider.prepareTokenRequest&&(tokenRequestParams=await provider.prepareTokenRequest(scope)),!tokenRequestParams){if(!authorizationCode)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!provider.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let codeVerifier=await provider.codeVerifier();tokenRequestParams=prepareAuthorizationCodeRequest(authorizationCode,codeVerifier,provider.redirectUrl)}return clientInformation??(clientInformation=await readClientInformation()),executeTokenRequest(authorizationServerUrl,{metadata,tokenRequestParams,clientInformation,addClientAuthentication:provider.addClientAuthentication,resource,fetchFn})}async function registerClient(authorizationServerUrl,{metadata,clientMetadata,scope,fetchFn}){let registrationUrl;if(metadata){if(!metadata.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");registrationUrl=new URL(metadata.registration_endpoint)}else registrationUrl=new URL("/register",authorizationServerUrl);let response=await fetchWithinOrigin(fetchFn??fetch)(registrationUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...clientMetadata,...scope!==void 0?{scope}:{}})});if(!response.ok)throw await parseErrorResponse(response);return RegistrationResponseSchema.parse(await response.json())}export{UnauthorizedError,selectClientAuthMethod,parseErrorResponse,auth,isHttpsUrl,selectResourceURL,extractWWWAuthenticateParams,extractResourceMetadataUrl,discoverOAuthProtectedResourceMetadata,discoverOAuthMetadata,buildDiscoveryUrls,discoverAuthorizationServerMetadata,discoverOAuthServerInfo,startAuthorization,prepareAuthorizationCodeRequest,exchangeAuthorization,refreshAuthorization,fetchToken,registerClient};