@zuplo/runtime 6.70.39 → 6.70.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,8 +22,8 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$ as xn,A as pn,Aa as A,B as mn,Ba as W,C as fn,Ca as C,D as hn,Da as jn,E as gn,Ea as Ha,F as j,Fa as Nn,G as yn,Ga as Gn,H as _,Ha as $n,I as F,Ia as Zn,J as I,K as wn,Ka as Fn,L as K,La as Kn,Ma as lt,N as _n,O as ce,P as g,Q as Rn,R as bn,S as Cn,T as at,U as ee,V as Mt,W as zt,X as Sn,Y as vn,Z as Dt,_ as Ht,a as Vr,aa as P,b as se,ba as In,c as Yr,ca as An,d as D,da as Un,e as Xr,ea as kn,f as Da,fa as Bt,g as Qr,ga as Pn,h as en,ha as Lt,i as tn,ia as jt,j as w,ja as st,k as rn,ka as ct,l as nn,la as Tn,m as H,ma as On,n as on,na as dt,o as an,oa as En,p as rt,pa as Nt,q as sn,qa as qn,r as qt,ra as Te,s as nt,sa as ut,t as ot,ta as Mn,u as Pe,ua as zn,v as cn,va as Dn,w as dn,wa as Hn,x as un,xa as Bn,y as it,ya as Ln,z as ln,za as R}from"../chunk-FYGTTP3G.js";import{B as Nr,J as Gr,L as u,M as $r,N as Et,O as Z,Q as Zr,S as f,T as Q,U as tt,_ as Fr,a as Qe,ca as Kr,da as Wr,ea as d,fa as z,j as ae,k as Br,m as Lr,ma as Jr,q as jr,s as et}from"../chunk-2GVPMQ7M.js";import"../chunk-JRXZBVXH.js";import{a as x}from"../chunk-4SACVMDH.js";import{$ as E,a as n,aa as y,ba as k,ca as Hr,da as Xe}from"../chunk-ZIKV2LUM.js";z();function Ba(e){let t=ot.safeParse(e);return t.success?t.data.id:void 0}n(Ba,"parseJsonRpcRequestId");function Wn(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Ba(t)}catch{return}}n(Wn,"readJsonRpcRequestIdFromBody");function pt(e){return cn.parse({jsonrpc:nt,...e.id===void 0?{}:{id:e.id},error:{code:e.error.code,message:e.error.message,...e.error.data===void 0?{}:{data:e.error.data}}})}n(pt,"jsonRpcErrorResponse");function Jn(e){return new un([dn.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Jn,"urlElicitationRequiredError");var mt=d.array(d.string()),La=d.object({tools:mt.optional(),prompts:mt.optional(),resources:mt.optional(),resourceTemplates:mt.optional()}).strict(),$t=[{option:"tools",listMethod:"tools/list",resultProperty:"tools",itemProperty:"name",directMethods:[{method:"tools/call",paramProperty:"name"}]},{option:"prompts",listMethod:"prompts/list",resultProperty:"prompts",itemProperty:"name",directMethods:[{method:"prompts/get",paramProperty:"name"}]},{option:"resources",listMethod:"resources/list",resultProperty:"resources",itemProperty:"uri",directMethods:[{method:"resources/read",paramProperty:"uri"}]},{option:"resourceTemplates",listMethod:"resources/templates/list",resultProperty:"resourceTemplates",itemProperty:"uriTemplate",directMethods:[]}];function ja(e,t){return Xr(La,e,`MCP capability filter policy "${t}"`)}n(ja,"parseMcpCapabilityFilterOptions");function B(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(B,"isRecord");function Na(e,t){if(!B(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(Na,"readParamString");function Zt(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(Zt,"readRequestId");function Xn(e){return e===void 0?void 0:JSON.stringify(e)}n(Xn,"requestIdKey");function Ga(e){let t={};for(let r of $t){let o=e[r.option];o!==void 0&&(t[r.option]=new Set(o))}return t}n(Ga,"buildAllowSets");function Ft(e){return $t.find(t=>t.listMethod===e)}n(Ft,"findListRule");function $a(e){return e.requests.some(t=>{if(!B(t))return!1;let r=Ft(t.method);return r!==void 0&&e.allowSets[r.option]!==void 0})}n($a,"shouldFilterListResponses");function Za(e){for(let t of $t){let r=e.allowSets[t.option];if(r!==void 0)for(let o of t.directMethods){if(e.request.method!==o.method)continue;let i=Na(e.request.params,o.paramProperty);if(i!==void 0&&!r.has(i))return{id:Zt(e.request)}}}}n(Za,"findDisallowedDirectAccess");function Fa(e){return Response.json(pt({id:e,error:{code:Pe.MethodNotFound,message:"Method not found"}}))}n(Fa,"methodNotFoundResponse");function Vn(e,t,r){if(!B(e))return e;let o=e.result;if(!B(o))return e;let i=o[t.resultProperty];return!Array.isArray(i)||!i.every(a=>B(a)&&typeof a[t.itemProperty]=="string")?e:{...e,result:{...o,[t.resultProperty]:i.filter(a=>{if(!B(a))return!1;let s=a[t.itemProperty];return typeof s=="string"&&r.has(s)})}}}n(Vn,"filterItems");function Ka(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!B(r))continue;let o=Ft(r.method),i=Zt(r),a=Xn(i);o!==void 0&&a!==void 0&&t.set(a,o)}return t}n(Ka,"buildListRulesByResponseId");function Wa(e){if(Array.isArray(e.responseBody)){let o=Ka(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(i=>{if(!B(i)||"error"in i)return i;let a=Xn(Zt(i)),s=a===void 0?void 0:o.get(a),c=s===void 0?void 0:e.allowSets[s.option];return s===void 0||c===void 0?i:Vn(i,s,c)})}if(!B(e.requestBody)||!B(e.responseBody)||"error"in e.responseBody)return e.responseBody;let t=Ft(e.requestBody.method),r=t===void 0?void 0:e.allowSets[t.option];return t===void 0||r===void 0?e.responseBody:Vn(e.responseBody,t,r)}n(Wa,"filterJsonRpcResponse");async function Yn(e){return e.clone().json()}n(Yn,"readJson");function Ja(e){return e.headers.get("content-type")?.includes("json")??!1}n(Ja,"isJsonResponse");var Gt=class extends et{static{n(this,"McpCapabilityFilterInboundPolicy")}#e;constructor(t,r){let o=ja(t,r);super(o,r),this.#e=Ga(o)}async handler(t,r){Qe("policy.inbound.mcp-capability-filter");let o;try{o=await Yn(t)}catch{return t}let i=Array.isArray(o)?o:[o];for(let a of i){if(!B(a))continue;let s=Za({request:a,allowSets:this.#e});if(s!==void 0)return Fa(s.id)}return $a({requests:i,allowSets:this.#e})&&r.addResponseSendingHook(async a=>{if(!Ja(a))return a;let s;try{s=await Yn(a)}catch{return a}let c=Wa({requestBody:o,responseBody:s,allowSets:this.#e});if(c===s)return a;let l=new Headers(a.headers);return l.delete("content-length"),new Response(JSON.stringify(c),{status:a.status,statusText:a.statusText,headers:l})}),t}};function te(e){let t=j().connectionsById.get(e);if(!t)throw new k(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,...t.description===void 0?{}:{description:t.description},...t.serverInfo===void 0?{}:{serverInfo:t.serverInfo},transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}n(te,"getUpstreamServerConfig");function Va(e){let t=j().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new k(`Unknown auth profile "${String(e.authProfileId)}" for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares a matching auth mode for that upstream connection.`);return t.authProfileId}n(Va,"resolveUpstreamAuthProfileId");function Kt(e){Va(e);let t=j().connectionsById.get(e.upstreamServerId);if(!t)throw new k(`Auth profile could not be resolved for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares the upstream connection before this handler runs.`);return t.authConfig}n(Kt,"getUpstreamAuthConfig");function de(e,t){let r=Kt({upstreamServerId:e,authProfileId:t});if(!pn(r))throw new k(`Upstream server "${e}" does not use upstream OAuth. Select an auth mode that supports the requested upstream connect flow or remove the upstream OAuth route for this server.`);return r.oauth}n(de,"requireUpstreamOAuthConfig");var Ya={"shared-oauth":{authMode:"shared-oauth",ownerMode:"shared",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"},"user-oauth":{authMode:"user-oauth",ownerMode:"user",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"}};function N(e){return Ya[e]}n(N,"describeUpstreamAuthMode");function ft(e){return N(e).ownerMode}n(ft,"resolveOwnerModeForUpstreamAuthMode");var Wt;Wt=globalThis.crypto;async function Xa(e){return(await Wt).getRandomValues(new Uint8Array(e))}n(Xa,"getRandomValues");async function Qa(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await Xa(e-o.length);for(let a of i)a<r&&(o+=t[a%t.length])}return o}n(Qa,"random");async function es(e){return await Qa(e)}n(es,"generateVerifier");async function ts(e){let t=await(await Wt).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(ts,"generateChallenge");async function Jt(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await es(e),r=await ts(t);return{code_verifier:t,code_challenge:r}}n(Jt,"pkceChallenge");z();var U=$r().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Kr.custom,message:"URL must be parseable",fatal:!0}),Gr}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),ht=tt({resource:u().url(),authorization_servers:f(U).optional(),jwks_uri:u().url().optional(),scopes_supported:f(u()).optional(),bearer_methods_supported:f(u()).optional(),resource_signing_alg_values_supported:f(u()).optional(),resource_name:u().optional(),resource_documentation:u().optional(),resource_policy_uri:u().url().optional(),resource_tos_uri:u().url().optional(),tls_client_certificate_bound_access_tokens:Z().optional(),authorization_details_types_supported:f(u()).optional(),dpop_signing_alg_values_supported:f(u()).optional(),dpop_bound_access_tokens_required:Z().optional()}),Oe=tt({issuer:u(),authorization_endpoint:U,token_endpoint:U,registration_endpoint:U.optional(),scopes_supported:f(u()).optional(),response_types_supported:f(u()),response_modes_supported:f(u()).optional(),grant_types_supported:f(u()).optional(),token_endpoint_auth_methods_supported:f(u()).optional(),token_endpoint_auth_signing_alg_values_supported:f(u()).optional(),service_documentation:U.optional(),revocation_endpoint:U.optional(),revocation_endpoint_auth_methods_supported:f(u()).optional(),revocation_endpoint_auth_signing_alg_values_supported:f(u()).optional(),introspection_endpoint:u().optional(),introspection_endpoint_auth_methods_supported:f(u()).optional(),introspection_endpoint_auth_signing_alg_values_supported:f(u()).optional(),code_challenge_methods_supported:f(u()).optional(),client_id_metadata_document_supported:Z().optional()}),rs=tt({issuer:u(),authorization_endpoint:U,token_endpoint:U,userinfo_endpoint:U.optional(),jwks_uri:U,registration_endpoint:U.optional(),scopes_supported:f(u()).optional(),response_types_supported:f(u()),response_modes_supported:f(u()).optional(),grant_types_supported:f(u()).optional(),acr_values_supported:f(u()).optional(),subject_types_supported:f(u()),id_token_signing_alg_values_supported:f(u()),id_token_encryption_alg_values_supported:f(u()).optional(),id_token_encryption_enc_values_supported:f(u()).optional(),userinfo_signing_alg_values_supported:f(u()).optional(),userinfo_encryption_alg_values_supported:f(u()).optional(),userinfo_encryption_enc_values_supported:f(u()).optional(),request_object_signing_alg_values_supported:f(u()).optional(),request_object_encryption_alg_values_supported:f(u()).optional(),request_object_encryption_enc_values_supported:f(u()).optional(),token_endpoint_auth_methods_supported:f(u()).optional(),token_endpoint_auth_signing_alg_values_supported:f(u()).optional(),display_values_supported:f(u()).optional(),claim_types_supported:f(u()).optional(),claims_supported:f(u()).optional(),service_documentation:u().optional(),claims_locales_supported:f(u()).optional(),ui_locales_supported:f(u()).optional(),claims_parameter_supported:Z().optional(),request_parameter_supported:Z().optional(),request_uri_parameter_supported:Z().optional(),require_request_uri_registration:Z().optional(),op_policy_uri:U.optional(),op_tos_uri:U.optional(),client_id_metadata_document_supported:Z().optional()}),gt=Q({...rs.shape,...Oe.pick({code_challenge_methods_supported:!0}).shape}),ye=Q({access_token:u(),id_token:u().optional(),token_type:u(),expires_in:Wr.number().optional(),scope:u().optional(),refresh_token:u().optional()}).strip(),eo=Q({error:u(),error_description:u().optional(),error_uri:u().optional()}),Qn=U.optional().or(Fr("").transform(()=>{})),ns=Q({redirect_uris:f(U),token_endpoint_auth_method:u().optional(),grant_types:f(u()).optional(),response_types:f(u()).optional(),client_name:u().optional(),client_uri:U.optional(),logo_uri:Qn,scope:u().optional(),contacts:f(u()).optional(),tos_uri:Qn,policy_uri:u().optional(),jwks_uri:U.optional(),jwks:Zr().optional(),software_id:u().optional(),software_version:u().optional(),software_statement:u().optional()}).strip(),Vt=Q({client_id:u(),client_secret:u().optional(),client_id_issued_at:Et().optional(),client_secret_expires_at:Et().optional()}).strip(),Ee=ns.merge(Vt),Zl=Q({error:u(),error_description:u().optional()}).strip(),Fl=Q({token:u(),token_type_hint:u().optional()}).strip();function to(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(to,"resourceUrlFromServerUrl");function ro({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",a=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return i.startsWith(a)}n(ro,"checkResourceAllowed");var S=class extends Error{static{n(this,"OAuthError")}constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},qe=class extends S{static{n(this,"InvalidRequestError")}};qe.errorCode="invalid_request";var ue=class extends S{static{n(this,"InvalidClientError")}};ue.errorCode="invalid_client";var le=class extends S{static{n(this,"InvalidGrantError")}};le.errorCode="invalid_grant";var pe=class extends S{static{n(this,"UnauthorizedClientError")}};pe.errorCode="unauthorized_client";var Me=class extends S{static{n(this,"UnsupportedGrantTypeError")}};Me.errorCode="unsupported_grant_type";var ze=class extends S{static{n(this,"InvalidScopeError")}};ze.errorCode="invalid_scope";var De=class extends S{static{n(this,"AccessDeniedError")}};De.errorCode="access_denied";var J=class extends S{static{n(this,"ServerError")}};J.errorCode="server_error";var He=class extends S{static{n(this,"TemporarilyUnavailableError")}};He.errorCode="temporarily_unavailable";var Be=class extends S{static{n(this,"UnsupportedResponseTypeError")}};Be.errorCode="unsupported_response_type";var Le=class extends S{static{n(this,"UnsupportedTokenTypeError")}};Le.errorCode="unsupported_token_type";var je=class extends S{static{n(this,"InvalidTokenError")}};je.errorCode="invalid_token";var Ne=class extends S{static{n(this,"MethodNotAllowedError")}};Ne.errorCode="method_not_allowed";var Ge=class extends S{static{n(this,"TooManyRequestsError")}};Ge.errorCode="too_many_requests";var me=class extends S{static{n(this,"InvalidClientMetadataError")}};me.errorCode="invalid_client_metadata";var $e=class extends S{static{n(this,"InsufficientScopeError")}};$e.errorCode="insufficient_scope";var Ze=class extends S{static{n(this,"InvalidTargetError")}};Ze.errorCode="invalid_target";var no={[qe.errorCode]:qe,[ue.errorCode]:ue,[le.errorCode]:le,[pe.errorCode]:pe,[Me.errorCode]:Me,[ze.errorCode]:ze,[De.errorCode]:De,[J.errorCode]:J,[He.errorCode]:He,[Be.errorCode]:Be,[Le.errorCode]:Le,[je.errorCode]:je,[Ne.errorCode]:Ne,[Ge.errorCode]:Ge,[me.errorCode]:me,[$e.errorCode]:$e,[Ze.errorCode]:Ze};function os(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(os,"isClientAuthMethod");var Yt="code",Xt="S256";function is(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&os(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}n(is,"selectClientAuthMethod");function as(e,t,r,o){let{client_id:i,client_secret:a}=t;switch(e){case"client_secret_basic":ss(i,a,r);return;case"client_secret_post":cs(i,a,o);return;case"none":ds(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(as,"applyClientAuthentication");function ss(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}n(ss,"applyBasicAuth");function cs(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(cs,"applyPostAuth");function ds(e,t){t.set("client_id",e)}n(ds,"applyPublicAuth");async function io(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=eo.parse(JSON.parse(r)),{error:i,error_description:a,error_uri:s}=o,c=no[i]||J;return new c(a||"",s)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new J(i)}}n(io,"parseErrorResponse");async function er(e,t){try{return await Qt(e,t)}catch(r){if(r instanceof ue||r instanceof pe)return await e.invalidateCredentials?.("all"),await Qt(e,t);if(r instanceof le)return await e.invalidateCredentials?.("tokens"),await Qt(e,t);throw r}}n(er,"auth");async function Qt(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:i,fetchFn:a}){let s=await e.discoveryState?.(),c,l,h,m=i;if(!m&&s?.resourceMetadataUrl&&(m=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(l=s.authorizationServerUrl,c=s.resourceMetadata,h=s.authorizationServerMetadata??await so(l,{fetchFn:a}),!c)try{c=await ao(t,{resourceMetadataUrl:m},a)}catch{}(h!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:m?.toString(),resourceMetadata:c,authorizationServerMetadata:h})}else{let O=await hs(t,{resourceMetadataUrl:m,fetchFn:a});l=O.authorizationServerUrl,h=O.authorizationServerMetadata,c=O.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:m?.toString(),resourceMetadata:c,authorizationServerMetadata:h})}let v=await us(t,e,c),L=o||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,X=await Promise.resolve(e.clientInformation());if(!X){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let O=h?.client_id_metadata_document_supported===!0,ke=e.clientMetadataUrl;if(ke&&!tr(ke))throw new me(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ke}`);if(O&&ke)X={client_id:ke},await e.saveClientInformation?.(X);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Dr=await Rs(l,{metadata:h,clientMetadata:e.clientMetadata,scope:L,fetchFn:a});await e.saveClientInformation(Dr),X=Dr}}let Ye=!e.redirectUrl;if(r!==void 0||Ye){let O=await _s(e,l,{metadata:h,resource:v,authorizationCode:r,fetchFn:a});return await e.saveTokens(O),"AUTHORIZED"}let zr=await e.tokens();if(zr?.refresh_token)try{let O=await ws(l,{metadata:h,clientInformation:X,refreshToken:zr.refresh_token,resource:v,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(O),"AUTHORIZED"}catch(O){if(!(!(O instanceof S)||O instanceof J))throw O}let qa=e.state?await e.state():void 0,{authorizationUrl:Ma,codeVerifier:za}=await gs(l,{metadata:h,clientInformation:X,state:qa,redirectUrl:e.redirectUrl,scope:L,resource:v});return await e.saveCodeVerifier(za),await e.redirectToAuthorization(Ma),"REDIRECT"}n(Qt,"authInternal");function tr(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(tr,"isHttpsUrl");async function us(e,t,r){let o=to(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!ro({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}n(us,"selectResourceURL");async function ao(e,t,r=fetch){let o=await ms(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.body?.cancel(),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return ht.parse(await o.json())}n(ao,"discoverOAuthProtectedResourceMetadata");async function rr(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?rr(e,void 0,r):void 0;throw o}}n(rr,"fetchWithCorsRetry");function ls(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(ls,"buildWellKnownPath");async function oo(e,t,r=fetch){return await rr(e,{"MCP-Protocol-Version":t},r)}n(oo,"tryMetadataDiscovery");function ps(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(ps,"shouldAttemptFallback");async function ms(e,t,r,o){let i=new URL(e),a=o?.protocolVersion??qt,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let l=ls(t,i.pathname);s=new URL(l,o?.metadataServerUrl??i),s.search=i.search}let c=await oo(s,a,r);if(!o?.metadataUrl&&ps(c,i.pathname)){let l=new URL(`/.well-known/${t}`,i);c=await oo(l,a,r)}return c}n(ms,"discoverMetadataWithFallback");function fs(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let i=t.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:"oidc"}),o.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(fs,"buildDiscoveryUrls");async function so(e,{fetchFn:t=fetch,protocolVersion:r=qt}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=fs(e);for(let{url:a,type:s}of i){let c=await rr(a,o,t);if(c){if(!c.ok){if(await c.body?.cancel(),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}return s==="oauth"?Oe.parse(await c.json()):gt.parse(await c.json())}}}n(so,"discoverAuthorizationServerMetadata");async function hs(e,t){let r,o;try{r=await ao(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch{}o||(o=String(new URL("/",e)));let i=await so(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(hs,"discoverOAuthServerInfo");async function gs(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:i,state:a,resource:s}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Yt))throw new Error(`Incompatible auth server: does not support response type ${Yt}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Xt))throw new Error(`Incompatible auth server: does not support code challenge method ${Xt}`)}else c=new URL("/authorize",e);let l=await Jt(),h=l.code_verifier,m=l.code_challenge;return c.searchParams.set("response_type",Yt),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",m),c.searchParams.set("code_challenge_method",Xt),c.searchParams.set("redirect_uri",String(o)),a&&c.searchParams.set("state",a),i&&c.searchParams.set("scope",i),i?.includes("offline_access")&&c.searchParams.append("prompt","consent"),s&&c.searchParams.set("resource",s.href),{authorizationUrl:c,codeVerifier:h}}n(gs,"startAuthorization");function ys(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(ys,"prepareAuthorizationCodeRequest");async function co(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:i,resource:a,fetchFn:s}){let c=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(a&&r.set("resource",a.href),i)await i(l,r,c,t);else if(o){let m=t?.token_endpoint_auth_methods_supported??[],v=is(o,m);as(v,o,l,r)}let h=await(s??fetch)(c,{method:"POST",headers:l,body:r});if(!h.ok)throw await io(h);return ye.parse(await h.json())}n(co,"executeTokenRequest");async function ws(e,{metadata:t,clientInformation:r,refreshToken:o,resource:i,addClientAuthentication:a,fetchFn:s}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),l=await co(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:a,resource:i,fetchFn:s});return{refresh_token:o,...l}}n(ws,"refreshAuthorization");async function _s(e,t,{metadata:r,resource:o,authorizationCode:i,fetchFn:a}={}){let s=e.clientMetadata.scope,c;if(e.prepareTokenRequest&&(c=await e.prepareTokenRequest(s)),!c){if(!i)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let h=await e.codeVerifier();c=ys(i,h,e.redirectUrl)}let l=await e.clientInformation();return co(t,{metadata:r,tokenRequestParams:c,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(_s,"fetchToken");async function Rs(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");a=new URL(t.registration_endpoint)}else a=new URL("/register",e);let s=await(i??fetch)(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!s.ok)throw await io(s);return Ee.parse(await s.json())}n(Rs,"registerClient");z();import{errors as yo,jwtVerify as wo,SignJWT as _o}from"jose";var T="zuplo-mcp-gateway",q=T,M="HS256";import{base64url as bs}from"jose";var Cs=new TextEncoder,Ss="MCP gateway could not initialize secure key material.",vs=32,uo=new Map,lo=new Map,xs;function Is(){return xs??Hr.instance.authPrivateKey}n(Is,"readAuthPrivateKey");function po(e){return new E(Ss,e===void 0?void 0:{cause:e})}n(po,"createGeneratedKeyMaterialError");function mo(e,t){let r=bs.decode(t);if(r.byteLength!==vs)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(mo,"decodeJwkKeyField");function As(e){let t=Is();if(!t)throw po();try{let r=JSON.parse(t);if(r.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.d!="string"||typeof r.x!="string")throw new Error("Generated deployment auth key is not an Ed25519 JWK.");let o=mo("d",r.d);mo("x",r.x);let i=Cs.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),a=new Uint8Array(i.byteLength+o.byteLength);return a.set(i),a.set(o,i.byteLength),a}catch(r){throw po(r)}}n(As,"decodeGeneratedKeyMaterial");function Us(e){let t=uo.get(e);return t||(t=As(e),uo.set(e,t)),t}n(Us,"getMasterKeyMaterial");async function G(e){let t=lo.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Us(e.keyMaterialPurpose));return lo.set(e.purpose,r),r}n(G,"readCachedDerivedKey");var ks="SHA-256";var Ps="zuplo-mcp-gateway:",Ts=new TextEncoder,fo=new WeakMap;async function re(e,t){let r=fo.get(e);r||(r=new Map,fo.set(e,r));let o=r.get(t);if(o)return o;let i=await Os(e,t);return r.set(t,i),i}n(re,"deriveGatewaySigningKey");async function Os(e,t){let r=ho(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=Ts.encode(`${Ps}${t}`),a=await crypto.subtle.deriveBits({name:"HKDF",hash:ks,salt:new Uint8Array,info:ho(i)},o,32*8);return new Uint8Array(a)}n(Os,"hkdfExpand");function ho(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(ho,"copyToArrayBuffer");var Ro=15*60,Es=15*60,qs=qn.extend({id:Mn}),Ms=qs.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),bo=Nt.extend({id:zn,purpose:d.literal("browser_connect")}),zs=Nt.extend({purpose:d.literal("browser_connect")}),Ds=bo.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),Co=Ro*1e3;async function So(){return G({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>re(e,"oauth-state"),"derive")})}n(So,"getOAuthStateKey");async function vo(){return G({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>re(e,"browser-connect"),"derive")})}n(vo,"getBrowserConnectKey");async function xo(e){let t=Math.floor(Date.now()/1e3)+Ro;return new _o(e).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(t).sign(await So())}n(xo,"signOAuthState");async function yt(e){try{let{payload:t}=await wo(e,await So(),{algorithms:[M],issuer:T,audience:q});return Ms.parse(t)}catch(t){throw t instanceof yo.JWTExpired?new y({message:"OAuth state has expired",extensionMembers:{[w]:"oauth_state_expired"}},{cause:t}):new y({message:"OAuth state could not be verified",extensionMembers:{[w]:"oauth_state_invalid"}},{cause:t})}}n(yt,"verifyOAuthState");async function Io(e){let t=Math.floor(Date.now()/1e3)+Es,r=zs.parse(e),o=bo.parse({...r,id:Ln()});return new _o(o).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(t).sign(await vo())}n(Io,"signBrowserConnectTicket");async function Ao(e){try{let{payload:t}=await wo(e,await vo(),{algorithms:[M],issuer:T,audience:q});return Ds.parse(t)}catch(t){throw t instanceof yo.JWTExpired?new y({message:"Browser connect ticket has expired",extensionMembers:{[w]:"oauth_state_expired"}},{cause:t}):new y({message:"Browser connect ticket could not be verified",extensionMembers:{[w]:"oauth_state_invalid"}},{cause:t})}}n(Ao,"verifyBrowserConnectTicket");async function Uo(e){if((await R().consumeBrowserConnectTicket({id:e.id,expiresAt:_(new Date(e.exp*1e3)),now:_(new Date)})).kind==="consumed")throw new y({message:"Browser connect ticket has already been used",extensionMembers:{[w]:"oauth_state_reused"}})}n(Uo,"consumeBrowserConnectTicket");function Hs(e,t,r=!1){return r?`${e} authorization must be renewed before this ${t} can be used.`:`${e} authorization is required before this ${t} can be used.`}n(Hs,"buildConnectRequiredMessage");async function Bs(e){let t=I(e.requestUrl),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("operationId",e.operationId),r.searchParams.set("browserTicket",await Io({...Te(e),purpose:"browser_connect"})),r.toString()}n(Bs,"buildGatewayBrowserTicketUrl");function Ls(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}n(Ls,"buildGatewayConnectPath");async function nr(e){return Bs({...e,path:Ls(e.upstreamServerId),redirect:!0})}n(nr,"buildGatewayConnectUrl");async function wt(e){let t={requestUrl:e.requestUrl,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await nr(t),message:Hs(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(wt,"buildRedirectConnectRequiredResponse");function ko(e){return js({...e,message:e.requiresReconsent?`An administrator must reconnect ${e.upstreamDisplayName} before this tool can be used.`:`An administrator must connect ${e.upstreamDisplayName} before this tool can be used.`})}n(ko,"buildAdminConnectRequiredResponse");function js(e){return{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},message:e.message,nextAction:"admin_setup_required"}}n(js,"buildAdminSetupRequiredResponse");z();function or(e){return`Zuplo MCP Gateway - ${e}`}n(or,"buildGatewayOAuthClientName");function Po(e,t){let r=new URL(e,I(t));return se(r)&&Vr(r.hostname)!=="localhost"&&(r.hostname="localhost"),r.toString()}n(Po,"buildGatewayOAuthRedirectUri");function ir(e){let t=new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin);return t.searchParams.set("authProfileId",e.authProfileId),t.toString()}n(ir,"buildOAuthClientMetadataDocumentUrl");function To(e){return I(e)}n(To,"requireOAuthClientMetadataOrigin");function Oo(e,t,r){let o=te(t),i=de(t,r);return{client_id:ir({origin:e,upstreamServerId:t,authProfileId:r}),client_name:or(o.displayName),client_uri:new URL("/",e).toString(),redirect_uris:[new URL(i.redirectPath,e).toString()],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",token_endpoint_auth_method:"none"}}n(Oo,"buildOAuthClientMetadataDocument");z();import{base64url as ne}from"jose";var Ns="SHA-256",_e="AES-GCM",Gs=12,sr="zuplo-secret",cr=1,Eo="generated:auth_private_key:token-encryption",$s=d.object({version:d.literal(cr),keyId:d.literal(Eo),algorithm:d.literal(_e),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();function we(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(we,"copyToArrayBuffer");async function ar(){return G({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(Ns,we(e));return crypto.subtle.importKey("raw",t,{name:_e},!1,["encrypt","decrypt"])},"derive")})}n(ar,"getEncryptionKey");function qo(e){return we(new TextEncoder().encode(`${sr}:v${e.version}:${e.keyId}`))}n(qo,"getAssociatedData");function Zs(e){return`${sr}:v${e.version}:${ne.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(Zs,"encodeEnvelope");function Fs(e){let t=`${sr}:v${cr}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(ne.decode(r));return $s.parse(JSON.parse(o))}n(Fs,"decodeEnvelope");async function _t(e){let t=await ar(),r=crypto.getRandomValues(new Uint8Array(Gs)),o={version:cr,keyId:Eo},i=await crypto.subtle.encrypt({name:_e,iv:r,additionalData:qo(o)},t,new TextEncoder().encode(e));return Zs({...o,algorithm:_e,iv:ne.encode(r),ciphertext:ne.encode(new Uint8Array(i))})}n(_t,"encryptSecret");async function Fe(e){let t=Fs(e);if(t){let s=await ar(),c=await crypto.subtle.decrypt({name:_e,iv:we(ne.decode(t.iv)),additionalData:qo(t)},s,we(ne.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,o]=e.split(".");if(!r||!o)throw new E("Encrypted payload is malformed");let i=await ar(),a=await crypto.subtle.decrypt({name:_e,iv:we(ne.decode(r))},i,we(ne.decode(o)));return new TextDecoder().decode(a)}n(Fe,"decryptSecret");var Ks=d.union([Ee,Vt]),Ws=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:ht.optional(),authorizationServerMetadata:d.union([Oe,gt]).optional()}).passthrough(),Js="Bearer",Vs="__zuplo_refresh_only_upstream_access_token__";function Ys(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Ys,"splitScopes");function Xs(e){return at.parse(e)}n(Xs,"parsePkceCodeVerifier");function Qs(e){if(typeof e.expires_in=="number")return _(new Date(Date.now()+e.expires_in*1e3))}n(Qs,"readTokenExpiry");async function Mo(e){if(e!==void 0)return _t(JSON.stringify(e))}n(Mo,"encryptJson");async function zo(e,t){if(!e)return;let r=await Fe(e);try{return t.parse(JSON.parse(r))}catch(o){throw new y({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[w]:"oauth_state_invalid"}},{cause:o})}}n(zo,"decryptJson");function ec(e){if(e===void 0)return;let t={authorizationServerUrl:e.authorizationServerUrl};return e.resourceMetadataUrl!==void 0&&(t.resourceMetadataUrl=e.resourceMetadataUrl),e.resourceMetadata!==void 0&&(t.resourceMetadata=e.resourceMetadata),e.authorizationServerMetadata!==void 0&&(t.authorizationServerMetadata=e.authorizationServerMetadata),t}n(ec,"toOAuthDiscoveryState");function tc(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(tc,"clientInformationAllowsRedirectUri");function rc(e,t,r){let o=te(e),i=de(e,t),a;return i.scopes.length>0&&(a=i.scopes.join(i.scopeDelimiter)),{client_name:or(o.displayName),client_uri:new URL("/",new URL(r).origin).toString(),redirect_uris:[r],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",scope:a,token_endpoint_auth_method:"none"}}n(rc,"buildOAuthClientMetadata");function nc(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new k(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return Ee.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(nc,"buildManualOAuthClientInformation");function oc(e,t,r){let o=ir({origin:new URL(r).origin,upstreamServerId:e,authProfileId:t});return tr(o)?o:void 0}n(oc,"buildClientMetadataUrl");function Do(e){for(let t of e)if(t!==void 0)return t}n(Do,"firstDefined");function ic(e){let t=de(e.target.upstreamServerId,e.target.authProfileId),r=rc(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);if(t.clientRegistration.mode==="manual")return{clientMetadata:r,configuredClientInformation:nc({clientMetadata:r,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let o=oc(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);return o===void 0?{clientMetadata:r}:{clientMetadata:r,clientMetadataUrl:o}}n(ic,"buildInitialOAuthClientSetup");function ac(e,t){if(t===void 0)return Do([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(ac,"readEncryptedClientInformation");function sc(e){return Do([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}n(sc,"readEncryptedDiscoveryState");var fe=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredClientInformation;authorizationUrlValue;connection;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;constructor(t){let r=ic({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.clientMetadataValue=r.clientMetadata,this.configuredClientInformation=r.configuredClientInformation,r.clientMetadataUrl!==void 0&&(this.clientMetadataUrl=r.clientMetadataUrl),this.connection=t.connection,this.pendingState=t.pendingState?{...t.pendingState}:void 0,this.encryptedClientInformation=ac(t,this.configuredClientInformation),this.encryptedDiscoveryState=sc(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return this.clientMetadataValue}async state(){let t=await this.createPendingState();return xo({id:t.id,...Te({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId})})}async clientInformation(){return this.configuredClientInformation?this.configuredClientInformation:this.loadPersistedClientInformation()}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.encryptedClientInformation=await Mo(t),await this.syncPendingState(!1))}async discoveryState(){return this.loadPersistedDiscoveryState()}async saveDiscoveryState(t){this.cachedDiscoveryState=t,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await Mo(t),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=ye.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=r.refresh_token?await _t(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:ye.parse({...r,refresh_token:await Fe(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let a={id:this.connection?.id??Hn(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await _t(r.access_token),encryptedRefreshToken:i,scopes:Ys(r.scope??this.clientMetadataValue.scope),expiresAt:Qs(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await R().upsertUpstreamConnection(a)}async redirectToAuthorization(t){this.authorizationUrlValue=t.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:Xs(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new y({message:"OAuth code verifier is missing",extensionMembers:{[w]:"oauth_state_invalid"}});return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",o=t==="all"||t==="client",i=t==="all"||t==="discovery",a=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),i&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(a),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:Bn(),...Te({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,operationId:this.target.operationId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:_(new Date(Date.now()+Co)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await R().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await zo(this.encryptedClientInformation,Ks)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&!tc(t,this.redirectUriValue)){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1);return}return this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async loadPersistedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;try{this.cachedDiscoveryState=ec(await zo(this.encryptedDiscoveryState,Ws))}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1)}return this.discoveryStateLoaded=!0,this.cachedDiscoveryState}async loadStoredTokens(){if(this.tokensLoaded)return this.cachedTokens;if(this.tokensLoaded=!0,!this.connection||this.connection.status!=="active")return;let t=this.connection.encryptedAccessToken?await Fe(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await Fe(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=ye.parse({access_token:t??Vs,token_type:Js,refresh_token:r,scope:this.connection.scopes.length>0?this.connection.scopes.join(" "):void 0});return this.cachedTokens=o,o}async persistCredentialInvalidation(t){if(!this.connection)return;let r={id:this.connection.id,ownerMode:this.connection.ownerMode,subjectId:this.connection.subjectId,upstreamServerId:this.connection.upstreamServerId,authProfileId:this.connection.authProfileId,status:this.connection.status,encryptedAccessToken:this.connection.encryptedAccessToken,encryptedRefreshToken:this.connection.encryptedRefreshToken,scopes:[...this.connection.scopes],expiresAt:this.connection.expiresAt,metadata:this.connection.metadata?{...this.connection.metadata}:void 0};t&&(r.status="reconsent_required",r.encryptedAccessToken=void 0,r.encryptedRefreshToken=void 0,r.scopes=[],r.expiresAt=void 0),r.metadata=this.readStoredOAuthPersistence(this.connection.metadata?.connectedBySubjectId),this.connection=await R().upsertUpstreamConnection(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var cc=3e4,dc=256*1024,uc=2;function lc(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(lc,"hasUsableAccessToken");var pc="does not support dynamic client registration";function mc(e){return e instanceof Error&&e.message.includes(pc)}n(mc,"isDynamicClientRegistrationUnsupported");function fc(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(fc,"readOAuthFetchRequest");function hc(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(hc,"responseLooksJson");function Ho(e){return async(t,r)=>{let o=fc(t),i=await Zn(t,r,{maxRedirects:uc,maxResponseBytes:dc,problemCode:"upstream_token_exchange_failed",timeoutMs:cc}),a=await i.clone().text();if(!hc(i,a))return i;try{JSON.parse(a)}catch(s){throw new y({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[w]:"upstream_token_exchange_failed"}},{cause:s})}return i}}n(Ho,"createUpstreamOAuthFetch");async function Bo(e,t){try{return await er(e,{serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Ho(t.upstreamServerId)})}catch(r){throw mc(r)?new y({message:`The authorization server for ${t.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register a client for the gateway manually before retrying.`,extensionMembers:{[w]:"upstream_client_registration_required"}},{cause:r}):r}}n(Bo,"runUpstreamOAuth");async function gc(e,t){return er(e,{serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Ho(t.upstreamServerId)})}n(gc,"exchangeUpstreamAuthorizationCode");async function Lo(e,t){let r=await Bo(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new y({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}}):new y({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}})}n(Lo,"requireUpstreamAuthorizationRedirect");async function jo(e){if(!e.forceRefresh&&lc(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await Bo(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl});if(t==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(t!=="REDIRECT")throw new y({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new y({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}});return{kind:"connect_required",payload:await bc({requestUrl:e.target.request.url,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}n(jo,"authorizeUpstreamOAuthSession");async function yc(e){let t=await yt(e.stateToken),r=await R().consumeUpstreamOAuthState({id:t.id,now:_(new Date)}),o=wc(r);return _c({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),Rc(o),o}n(yc,"consumeStoredCallbackState");function wc(e){switch(e.kind){case"consumed":throw new y({message:"OAuth state has already been used",extensionMembers:{[w]:"oauth_state_reused"}});case"missing":throw new y({message:"OAuth state is missing or expired",extensionMembers:{[w]:"oauth_state_expired"}});case"available":return e.record}}n(wc,"readConsumedCallbackState");function _c(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.operationId===e.signedState.operationId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw new y({message:"OAuth callback did not match the initiating request",extensionMembers:{[w]:"oauth_callback_mismatch"}})}n(_c,"assertStoredCallbackStateMatches");function Rc(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new y({message:"OAuth state has expired",extensionMembers:{[w]:"oauth_state_expired"}})}n(Rc,"assertStoredCallbackStateFresh");async function bc(e){if(e.owner.mode==="shared"){let r={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,requiresReconsent:!!e.connection};return e.connection!==void 0&&(r.connectionId=e.connection.id),ko(r)}let t={requestUrl:e.requestUrl,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,subject:"tool",requiresReconsent:!!e.connection,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return e.connection!==void 0&&(t.connectionId=e.connection.id),wt(t)}n(bc,"buildOAuthConnectRequiredResponse");async function No(e){let t=await yc({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=ut(t),[o]=await R().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),i={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};o!==void 0&&(i.connection=o);let a=new fe(i),s=await gc(a,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(s==="AUTHORIZED")return t;throw s!=="REDIRECT"?new y({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${s}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}}):new y({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}})}n(No,"finishUpstreamOAuthCallback");async function Go(e){let t=te(e.upstreamServerId),r=de(e.upstreamServerId,e.authProfileId),o=Po(r.redirectPath,e.request.url),i="preloadedConnection"in e?e.preloadedConnection:(await R().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:i,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}},redirectUri:o,returnOrigin:I(e.request.url)}}}n(Go,"prepareUpstreamOAuthRequest");async function $o(e){let t=await Go(e),r=new fe({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Lo(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n($o,"startUpstreamConnect");async function Zo(e){let t=await Go(e),r=new fe({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return jo({target:e,provider:r,connection:t.connection,forceRefresh:e.forceRefresh,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Zo,"authorizeUpstreamRequest");async function Re(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return Zo({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,forceRefresh:e.forceRefresh,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},...t.returnTo===void 0?{}:{returnTo:t.returnTo}})}let r=t;throw new E(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(Re,"resolveUpstreamCredentialForRoute");async function Fo(e){let t,r={request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,operationId:e.connectRequest.operationId,...e.connectRequest.returnTo===void 0?{}:{returnTo:e.connectRequest.returnTo}},o=N(e.connectRequest.authMode);switch(o.connectSupport){case"oauth_authorization":t=await $o(r);break;case"none":throw new E(o.connectUnsupportedDetail??`Upstream server ${e.connectRequest.upstreamServerId} does not support browser connection flows.`)}return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}n(Fo,"startUpstreamConnectForRequest");async function Ko(e){let r=(await yt(e.callbackRequest.state)).authProfileId,o=Kt({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r});if(N(o.mode).callbackSupport!=="authorization_code")throw new E(`Upstream server ${e.callbackRequest.upstreamServerId} does not support OAuth callbacks.`);return No({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:te(e.callbackRequest.upstreamServerId)})}n(Ko,"finishUpstreamCallbackForRequest");function Cc(e){let t=N(e.connection.authMode);return{upstreamServerId:e.connection.upstreamServerId,operationId:e.operationId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:t.ownerMode}}n(Cc,"buildRouteAuthBaseFromConnection");function Jo(e){let t=N(e.connection.authMode);return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:it(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:t.ownerMode}}n(Jo,"buildRouteAuthBaseFromPolicyOptions");function Rt(e,t){let o=j().byOperationId.get(t);if(!o)throw new k(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new k(`MCP route "${t}" does not declare an MCP token exchange policy. Add one before starting an upstream connection flow.`);if(o.connection.upstreamServerId!==e)throw new k(`MCP route "${t}" does not bind upstream "${e}". Check the route's MCP upstream policies and bind the upstream before starting an upstream connection flow.`);return Cc({connection:o.connection,operationId:t})}n(Rt,"resolveRouteAuthBase");function Wo(e,t){switch(e){case"user":return dt(t.subjectId);case"shared":return En()}}n(Wo,"buildOwnerForPrincipal");function be(e,t){switch(e.ownerMode){case"shared":return{...e,owner:Wo(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"user":return{...e,owner:Wo(e.ownerMode,t),initiatedBySubjectId:t.subjectId}}}n(be,"resolveRouteAuthForPrincipal");var Sc=Pe.InvalidRequest,vc=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function xc(e){let t=e.route.raw();return rt.parse(t?.operationId)}n(xc,"readOperationId");async function Ic(e,t,r,o){let i=await Re({request:e,routeAuth:t});if(i.kind==="connect_required")return o.log.info({event:"mcp_upstream_connect_required",upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId},"MCP upstream proxy: upstream connection required"),{kind:"connect_required",payload:i.payload};let a=i.credential;switch(a.type){case"none":return{kind:"headers",headers:[]};case"bearer_token":return{kind:"headers",headers:[["authorization",`Bearer ${a.token}`]]};case"headers":return{kind:"headers",headers:Object.entries(a.headers)};case"mcp_oauth_provider":{let s=await a.provider.tokens();return s?{kind:"headers",headers:[["authorization",`${s.token_type??"Bearer"} ${s.access_token}`]]}:(o.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:t.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),Response.json({error:"no_upstream_tokens"},{status:401}))}}}n(Ic,"buildCredentialHeaders");var Ac=new Set(["authorization","cookie","cookie2"]);function Uc(e,t){let r=new Headers(e.headers);for(let o of Ac)r.delete(o);for(let[o,i]of t)r.set(o,i);return new Lr(e,{headers:r})}n(Uc,"applyUpstreamHeaders");function kc(e){let t=new Headers(e.headers);for(let r of vc)t.delete(r);return t}n(kc,"buildProxyHeaders");async function Pc(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(Pc,"readRetryBody");function Vo(e,t){let r=t.authUrl===void 0?void 0:Jn({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(pt({id:Wn(e),error:{code:r?.code??Sc,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(Vo,"connectRequiredJsonRpcResponse");async function Tc(e){let t=await Re({request:e.request,routeAuth:e.routeAuth,forceRefresh:!0});if(t.kind==="connect_required")return{kind:"connect_required",payload:t.payload};let r=new Headers(e.headers),o=t.credential;switch(o.type){case"none":return r.delete("authorization"),{kind:"headers",headers:r};case"bearer_token":return r.set("authorization",`Bearer ${o.token}`),{kind:"headers",headers:r};case"headers":for(let[i,a]of Object.entries(o.headers))r.set(i,a);return{kind:"headers",headers:r};case"mcp_oauth_provider":{let i=await o.provider.tokens();return i?(r.set("authorization",`${i.token_type??"Bearer"} ${i.access_token}`),{kind:"headers",headers:r}):(e.context.log.warn({event:"mcp_upstream_no_tokens_after_refresh",upstreamServerId:e.routeAuth.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens after refresh"),{kind:"response",response:Response.json({error:"no_upstream_tokens"},{status:401})})}}}n(Tc,"applyRefreshedCredentialHeaders");function Oc(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await Tc({request:e.request,context:e.context,headers:kc(r),routeAuth:e.routeAuth});if(o.kind==="connect_required")return Vo(e.requestBody,o.payload);if(o.kind==="response")return o.response;let i=on({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return Xe.fetch(i.url,i.init)})}n(Oc,"installUpstreamAuthRetryHook");async function dr(e,t,r){let o=xc(t),i=await Pc(e),a=Jo({connection:r,operationId:o}),s=be(a,Tn(e,t)),c=await Ic(e,s,r,t);if(!(c instanceof Response)&&c.kind==="connect_required")return Vo(i,c.payload);if(c instanceof Response)return c;let l=Uc(e,c.headers);return Oc({request:l,context:t,requestBody:i,routeAuth:s}),l}n(dr,"mcpTokenExchangePolicy");var ur=class extends et{static{n(this,"McpTokenExchangeInboundPolicy")}constructor(t,r){let o=ln(t,r);super(o,r)}async handler(t,r){return Qe("policy.inbound.mcp-token-exchange"),dr(t,r,this.options)}};z();var Yo=Symbol("Html");function Ec(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n(Ec,"escapeHtml");function qc(e){return e===null||typeof e!="object"?!1:e[Yo]===!0}n(qc,"isHtml");function Xo(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Xo).join(""):qc(e)?e.value:Ec(String(e))}n(Xo,"renderValue");function V(e){return{[Yo]:!0,value:e}}n(V,"trustedHtml");var he=V("");function b(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=Xo(t[o]),r+=e[o+1]??"";return V(r)}n(b,"html");function Ce(e){return e.value}n(Ce,"renderHtml");function Qo(e){return b`<p data-gateway-error-code="${e.code}">${e.detail}</p>${e.guidance} ${e.action}`}n(Qo,"renderBrowserErrorPage");var Se=V('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;justify-content:center;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;min-height:40px;padding:8px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.reconnect-action{align-items:center;margin-right:auto;display:inline-flex;position:relative}.reconnect-button{gap:7px}.tooltip{width:16px;height:16px;color:var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);cursor:help;border:1.5px solid;border-radius:50%;justify-content:center;align-items:center;font-size:10.5px;font-weight:700;line-height:1;display:inline-flex;position:relative}.tooltip:after{content:attr(aria-label);z-index:10;border-radius:var(--radius-sm);background:var(--accent);width:280px;max-width:min(280px,100vw - 48px);color:var(--accent-text);box-shadow:var(--shadow);text-align:left;white-space:normal;opacity:0;pointer-events:none;padding:12px 14px;font-size:13px;font-weight:600;line-height:1.45;transition:opacity .12s;position:absolute;bottom:calc(100% + 12px);left:50%;transform:translate(-50%)}.tooltip:before{content:"";z-index:11;border-left:7px solid #0000;border-right:7px solid #0000;border-top:8px solid var(--accent);opacity:0;pointer-events:none;transition:opacity .12s;position:absolute;bottom:calc(100% + 5px);left:50%;transform:translate(-50%)}.tooltip:hover:after,.tooltip:hover:before,.tooltip:focus-visible:after,.tooltip:focus-visible:before{opacity:1}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}.reconnect-action{justify-content:center;width:100%;margin-right:0}.reconnect-action .button{flex:1}.tooltip:after{left:auto;right:0;transform:none}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function ve(e){return b`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" href="${e.iconHref}" /><style>
25
+ import{$ as Lt,A as gn,Aa as C,B as yn,Ba as b,C as wn,Ca as J,D as _n,Da as v,E as Rn,Ea as Fn,F as N,Fa as ts,G as Cn,Ga as Kn,H as bn,Ha as Jn,I as R,Ia as Wn,J as F,Ja as Vn,K as I,L as Sn,La as Yn,M as K,Ma as Xn,Na as mt,O as vn,P as de,Q as g,R as xn,S as An,T as In,U as ct,V as te,W as Dt,X as Bt,Y as Un,Z as kn,_ as Ht,a as en,aa as Pn,b as ce,ba as P,c as tn,ca as Tn,d as D,da as On,e as rn,ea as En,f as es,fa as qn,g as nn,ga as Nt,h as on,ha as Mn,i as an,ia as jt,j as w,ja as Gt,k as sn,ka as dt,l as cn,la as ut,m as B,ma as zn,n as dn,na as Dn,o as un,oa as lt,p as ot,pa as Bn,q as ln,qa as $t,r as zt,ra as Hn,s as it,sa as Oe,t as at,ta as pt,u as Te,ua as Ln,v as pn,va as Nn,w as mn,wa as jn,x as fn,xa as Gn,y as st,ya as $n,z as hn,za as Zn}from"../chunk-DLCMRCIL.js";import{B as Fr,J as Kr,L as u,M as Jr,N as Mt,O as Z,Q as Wr,S as f,T as ee,U as nt,_ as Vr,a as tt,ca as Yr,da as Xr,ea as d,fa as z,j as se,k as Gr,m as $r,ma as Qr,q as Zr,s as rt}from"../chunk-A6TMPOZH.js";import"../chunk-JRXZBVXH.js";import{a as _}from"../chunk-4SACVMDH.js";import{$ as E,a as n,aa as y,ba as k,ca as jr,da as et}from"../chunk-ZIKV2LUM.js";z();function rs(e){let t=at.safeParse(e);return t.success?t.data.id:void 0}n(rs,"parseJsonRpcRequestId");function Qn(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return rs(t)}catch{return}}n(Qn,"readJsonRpcRequestIdFromBody");function ft(e){return pn.parse({jsonrpc:it,...e.id===void 0?{}:{id:e.id},error:{code:e.error.code,message:e.error.message,...e.error.data===void 0?{}:{data:e.error.data}}})}n(ft,"jsonRpcErrorResponse");function eo(e){return new fn([mn.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(eo,"urlElicitationRequiredError");var ht=d.array(d.string()),ns=d.object({tools:ht.optional(),prompts:ht.optional(),resources:ht.optional(),resourceTemplates:ht.optional()}).strict(),Ft=[{option:"tools",listMethod:"tools/list",resultProperty:"tools",itemProperty:"name",directMethods:[{method:"tools/call",paramProperty:"name"}]},{option:"prompts",listMethod:"prompts/list",resultProperty:"prompts",itemProperty:"name",directMethods:[{method:"prompts/get",paramProperty:"name"}]},{option:"resources",listMethod:"resources/list",resultProperty:"resources",itemProperty:"uri",directMethods:[{method:"resources/read",paramProperty:"uri"}]},{option:"resourceTemplates",listMethod:"resources/templates/list",resultProperty:"resourceTemplates",itemProperty:"uriTemplate",directMethods:[]}];function os(e,t){return rn(ns,e,`MCP capability filter policy "${t}"`)}n(os,"parseMcpCapabilityFilterOptions");function H(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(H,"isRecord");function is(e,t){if(!H(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(is,"readParamString");function Kt(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(Kt,"readRequestId");function no(e){return e===void 0?void 0:JSON.stringify(e)}n(no,"requestIdKey");function as(e){let t={};for(let r of Ft){let o=e[r.option];o!==void 0&&(t[r.option]=new Set(o))}return t}n(as,"buildAllowSets");function Jt(e){return Ft.find(t=>t.listMethod===e)}n(Jt,"findListRule");function ss(e){return e.requests.some(t=>{if(!H(t))return!1;let r=Jt(t.method);return r!==void 0&&e.allowSets[r.option]!==void 0})}n(ss,"shouldFilterListResponses");function cs(e){for(let t of Ft){let r=e.allowSets[t.option];if(r!==void 0)for(let o of t.directMethods){if(e.request.method!==o.method)continue;let i=is(e.request.params,o.paramProperty);if(i!==void 0&&!r.has(i))return{id:Kt(e.request)}}}}n(cs,"findDisallowedDirectAccess");function ds(e){return Response.json(ft({id:e,error:{code:Te.MethodNotFound,message:"Method not found"}}))}n(ds,"methodNotFoundResponse");function to(e,t,r){if(!H(e))return e;let o=e.result;if(!H(o))return e;let i=o[t.resultProperty];return!Array.isArray(i)||!i.every(a=>H(a)&&typeof a[t.itemProperty]=="string")?e:{...e,result:{...o,[t.resultProperty]:i.filter(a=>{if(!H(a))return!1;let s=a[t.itemProperty];return typeof s=="string"&&r.has(s)})}}}n(to,"filterItems");function us(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!H(r))continue;let o=Jt(r.method),i=Kt(r),a=no(i);o!==void 0&&a!==void 0&&t.set(a,o)}return t}n(us,"buildListRulesByResponseId");function ls(e){if(Array.isArray(e.responseBody)){let o=us(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(i=>{if(!H(i)||"error"in i)return i;let a=no(Kt(i)),s=a===void 0?void 0:o.get(a),c=s===void 0?void 0:e.allowSets[s.option];return s===void 0||c===void 0?i:to(i,s,c)})}if(!H(e.requestBody)||!H(e.responseBody)||"error"in e.responseBody)return e.responseBody;let t=Jt(e.requestBody.method),r=t===void 0?void 0:e.allowSets[t.option];return t===void 0||r===void 0?e.responseBody:to(e.responseBody,t,r)}n(ls,"filterJsonRpcResponse");async function ro(e){return e.clone().json()}n(ro,"readJson");function ps(e){return e.headers.get("content-type")?.includes("json")??!1}n(ps,"isJsonResponse");var Zt=class extends rt{static{n(this,"McpCapabilityFilterInboundPolicy")}#e;constructor(t,r){let o=os(t,r);super(o,r),this.#e=as(o)}async handler(t,r){tt("policy.inbound.mcp-capability-filter");let o;try{o=await ro(t)}catch{return t}let i=Array.isArray(o)?o:[o];for(let a of i){if(!H(a))continue;let s=cs({request:a,allowSets:this.#e});if(s!==void 0)return ds(s.id)}return ss({requests:i,allowSets:this.#e})&&r.addResponseSendingHook(async a=>{if(!ps(a))return a;let s;try{s=await ro(a)}catch{return a}let c=ls({requestBody:o,responseBody:s,allowSets:this.#e});if(c===s)return a;let l=new Headers(a.headers);return l.delete("content-length"),new Response(JSON.stringify(c),{status:a.status,statusText:a.statusText,headers:l})}),t}};var Wt;Wt=globalThis.crypto;async function ms(e){return(await Wt).getRandomValues(new Uint8Array(e))}n(ms,"getRandomValues");async function fs(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await ms(e-o.length);for(let a of i)a<r&&(o+=t[a%t.length])}return o}n(fs,"random");async function hs(e){return await fs(e)}n(hs,"generateVerifier");async function gs(e){let t=await(await Wt).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(gs,"generateChallenge");async function Vt(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await hs(e),r=await gs(t);return{code_verifier:t,code_challenge:r}}n(Vt,"pkceChallenge");z();var U=Jr().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Yr.custom,message:"URL must be parseable",fatal:!0}),Kr}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),gt=nt({resource:u().url(),authorization_servers:f(U).optional(),jwks_uri:u().url().optional(),scopes_supported:f(u()).optional(),bearer_methods_supported:f(u()).optional(),resource_signing_alg_values_supported:f(u()).optional(),resource_name:u().optional(),resource_documentation:u().optional(),resource_policy_uri:u().url().optional(),resource_tos_uri:u().url().optional(),tls_client_certificate_bound_access_tokens:Z().optional(),authorization_details_types_supported:f(u()).optional(),dpop_signing_alg_values_supported:f(u()).optional(),dpop_bound_access_tokens_required:Z().optional()}),Ee=nt({issuer:u(),authorization_endpoint:U,token_endpoint:U,registration_endpoint:U.optional(),scopes_supported:f(u()).optional(),response_types_supported:f(u()),response_modes_supported:f(u()).optional(),grant_types_supported:f(u()).optional(),token_endpoint_auth_methods_supported:f(u()).optional(),token_endpoint_auth_signing_alg_values_supported:f(u()).optional(),service_documentation:U.optional(),revocation_endpoint:U.optional(),revocation_endpoint_auth_methods_supported:f(u()).optional(),revocation_endpoint_auth_signing_alg_values_supported:f(u()).optional(),introspection_endpoint:u().optional(),introspection_endpoint_auth_methods_supported:f(u()).optional(),introspection_endpoint_auth_signing_alg_values_supported:f(u()).optional(),code_challenge_methods_supported:f(u()).optional(),client_id_metadata_document_supported:Z().optional()}),ys=nt({issuer:u(),authorization_endpoint:U,token_endpoint:U,userinfo_endpoint:U.optional(),jwks_uri:U,registration_endpoint:U.optional(),scopes_supported:f(u()).optional(),response_types_supported:f(u()),response_modes_supported:f(u()).optional(),grant_types_supported:f(u()).optional(),acr_values_supported:f(u()).optional(),subject_types_supported:f(u()),id_token_signing_alg_values_supported:f(u()),id_token_encryption_alg_values_supported:f(u()).optional(),id_token_encryption_enc_values_supported:f(u()).optional(),userinfo_signing_alg_values_supported:f(u()).optional(),userinfo_encryption_alg_values_supported:f(u()).optional(),userinfo_encryption_enc_values_supported:f(u()).optional(),request_object_signing_alg_values_supported:f(u()).optional(),request_object_encryption_alg_values_supported:f(u()).optional(),request_object_encryption_enc_values_supported:f(u()).optional(),token_endpoint_auth_methods_supported:f(u()).optional(),token_endpoint_auth_signing_alg_values_supported:f(u()).optional(),display_values_supported:f(u()).optional(),claim_types_supported:f(u()).optional(),claims_supported:f(u()).optional(),service_documentation:u().optional(),claims_locales_supported:f(u()).optional(),ui_locales_supported:f(u()).optional(),claims_parameter_supported:Z().optional(),request_parameter_supported:Z().optional(),request_uri_parameter_supported:Z().optional(),require_request_uri_registration:Z().optional(),op_policy_uri:U.optional(),op_tos_uri:U.optional(),client_id_metadata_document_supported:Z().optional()}),yt=ee({...ys.shape,...Ee.pick({code_challenge_methods_supported:!0}).shape}),we=ee({access_token:u(),id_token:u().optional(),token_type:u(),expires_in:Xr.number().optional(),scope:u().optional(),refresh_token:u().optional()}).strip(),io=ee({error:u(),error_description:u().optional(),error_uri:u().optional()}),oo=U.optional().or(Vr("").transform(()=>{})),ws=ee({redirect_uris:f(U),token_endpoint_auth_method:u().optional(),grant_types:f(u()).optional(),response_types:f(u()).optional(),client_name:u().optional(),client_uri:U.optional(),logo_uri:oo,scope:u().optional(),contacts:f(u()).optional(),tos_uri:oo,policy_uri:u().optional(),jwks_uri:U.optional(),jwks:Wr().optional(),software_id:u().optional(),software_version:u().optional(),software_statement:u().optional()}).strip(),Yt=ee({client_id:u(),client_secret:u().optional(),client_id_issued_at:Mt().optional(),client_secret_expires_at:Mt().optional()}).strip(),qe=ws.merge(Yt),lp=ee({error:u(),error_description:u().optional()}).strip(),pp=ee({token:u(),token_type_hint:u().optional()}).strip();function ao(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(ao,"resourceUrlFromServerUrl");function so({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",a=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return i.startsWith(a)}n(so,"checkResourceAllowed");var x=class extends Error{static{n(this,"OAuthError")}constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},Me=class extends x{static{n(this,"InvalidRequestError")}};Me.errorCode="invalid_request";var ue=class extends x{static{n(this,"InvalidClientError")}};ue.errorCode="invalid_client";var le=class extends x{static{n(this,"InvalidGrantError")}};le.errorCode="invalid_grant";var pe=class extends x{static{n(this,"UnauthorizedClientError")}};pe.errorCode="unauthorized_client";var ze=class extends x{static{n(this,"UnsupportedGrantTypeError")}};ze.errorCode="unsupported_grant_type";var De=class extends x{static{n(this,"InvalidScopeError")}};De.errorCode="invalid_scope";var Be=class extends x{static{n(this,"AccessDeniedError")}};Be.errorCode="access_denied";var W=class extends x{static{n(this,"ServerError")}};W.errorCode="server_error";var He=class extends x{static{n(this,"TemporarilyUnavailableError")}};He.errorCode="temporarily_unavailable";var Le=class extends x{static{n(this,"UnsupportedResponseTypeError")}};Le.errorCode="unsupported_response_type";var Ne=class extends x{static{n(this,"UnsupportedTokenTypeError")}};Ne.errorCode="unsupported_token_type";var je=class extends x{static{n(this,"InvalidTokenError")}};je.errorCode="invalid_token";var Ge=class extends x{static{n(this,"MethodNotAllowedError")}};Ge.errorCode="method_not_allowed";var $e=class extends x{static{n(this,"TooManyRequestsError")}};$e.errorCode="too_many_requests";var me=class extends x{static{n(this,"InvalidClientMetadataError")}};me.errorCode="invalid_client_metadata";var Ze=class extends x{static{n(this,"InsufficientScopeError")}};Ze.errorCode="insufficient_scope";var Fe=class extends x{static{n(this,"InvalidTargetError")}};Fe.errorCode="invalid_target";var co={[Me.errorCode]:Me,[ue.errorCode]:ue,[le.errorCode]:le,[pe.errorCode]:pe,[ze.errorCode]:ze,[De.errorCode]:De,[Be.errorCode]:Be,[W.errorCode]:W,[He.errorCode]:He,[Le.errorCode]:Le,[Ne.errorCode]:Ne,[je.errorCode]:je,[Ge.errorCode]:Ge,[$e.errorCode]:$e,[me.errorCode]:me,[Ze.errorCode]:Ze,[Fe.errorCode]:Fe};function _s(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(_s,"isClientAuthMethod");var Xt="code",Qt="S256";function Rs(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&_s(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}n(Rs,"selectClientAuthMethod");function Cs(e,t,r,o){let{client_id:i,client_secret:a}=t;switch(e){case"client_secret_basic":bs(i,a,r);return;case"client_secret_post":Ss(i,a,o);return;case"none":vs(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(Cs,"applyClientAuthentication");function bs(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}n(bs,"applyBasicAuth");function Ss(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(Ss,"applyPostAuth");function vs(e,t){t.set("client_id",e)}n(vs,"applyPublicAuth");async function lo(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=io.parse(JSON.parse(r)),{error:i,error_description:a,error_uri:s}=o,c=co[i]||W;return new c(a||"",s)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new W(i)}}n(lo,"parseErrorResponse");async function rr(e,t){try{return await er(e,t)}catch(r){if(r instanceof ue||r instanceof pe)return await e.invalidateCredentials?.("all"),await er(e,t);if(r instanceof le)return await e.invalidateCredentials?.("tokens"),await er(e,t);throw r}}n(rr,"auth");async function er(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:i,fetchFn:a}){let s=await e.discoveryState?.(),c,l,h,m=i;if(!m&&s?.resourceMetadataUrl&&(m=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(l=s.authorizationServerUrl,c=s.resourceMetadata,h=s.authorizationServerMetadata??await fo(l,{fetchFn:a}),!c)try{c=await mo(t,{resourceMetadataUrl:m},a)}catch{}(h!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:m?.toString(),resourceMetadata:c,authorizationServerMetadata:h})}else{let O=await Ps(t,{resourceMetadataUrl:m,fetchFn:a});l=O.authorizationServerUrl,h=O.authorizationServerMetadata,c=O.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:m?.toString(),resourceMetadata:c,authorizationServerMetadata:h})}let A=await xs(t,e,c),L=o||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,Q=await Promise.resolve(e.clientInformation());if(!Q){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let O=h?.client_id_metadata_document_supported===!0,Pe=e.clientMetadataUrl;if(Pe&&!nr(Pe))throw new me(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${Pe}`);if(O&&Pe)Q={client_id:Pe},await e.saveClientInformation?.(Q);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Nr=await Ms(l,{metadata:h,clientMetadata:e.clientMetadata,scope:L,fetchFn:a});await e.saveClientInformation(Nr),Q=Nr}}let Qe=!e.redirectUrl;if(r!==void 0||Qe){let O=await qs(e,l,{metadata:h,resource:A,authorizationCode:r,fetchFn:a});return await e.saveTokens(O),"AUTHORIZED"}let Lr=await e.tokens();if(Lr?.refresh_token)try{let O=await Es(l,{metadata:h,clientInformation:Q,refreshToken:Lr.refresh_token,resource:A,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(O),"AUTHORIZED"}catch(O){if(!(!(O instanceof x)||O instanceof W))throw O}let Ya=e.state?await e.state():void 0,{authorizationUrl:Xa,codeVerifier:Qa}=await Ts(l,{metadata:h,clientInformation:Q,state:Ya,redirectUrl:e.redirectUrl,scope:L,resource:A});return await e.saveCodeVerifier(Qa),await e.redirectToAuthorization(Xa),"REDIRECT"}n(er,"authInternal");function nr(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(nr,"isHttpsUrl");async function xs(e,t,r){let o=ao(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!so({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}n(xs,"selectResourceURL");function po(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let i=tr(e,"resource_metadata")||void 0,a;if(i)try{a=new URL(i)}catch{}let s=tr(e,"scope")||void 0,c=tr(e,"error")||void 0;return{resourceMetadataUrl:a,scope:s,error:c}}n(po,"extractWWWAuthenticateParams");function tr(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=r.match(o);return i?i[1]||i[2]:null}n(tr,"extractFieldFromWwwAuth");async function mo(e,t,r=fetch){let o=await Us(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.body?.cancel(),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return gt.parse(await o.json())}n(mo,"discoverOAuthProtectedResourceMetadata");async function or(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?or(e,void 0,r):void 0;throw o}}n(or,"fetchWithCorsRetry");function As(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(As,"buildWellKnownPath");async function uo(e,t,r=fetch){return await or(e,{"MCP-Protocol-Version":t},r)}n(uo,"tryMetadataDiscovery");function Is(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(Is,"shouldAttemptFallback");async function Us(e,t,r,o){let i=new URL(e),a=o?.protocolVersion??zt,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let l=As(t,i.pathname);s=new URL(l,o?.metadataServerUrl??i),s.search=i.search}let c=await uo(s,a,r);if(!o?.metadataUrl&&Is(c,i.pathname)){let l=new URL(`/.well-known/${t}`,i);c=await uo(l,a,r)}return c}n(Us,"discoverMetadataWithFallback");function ks(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let i=t.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:"oidc"}),o.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(ks,"buildDiscoveryUrls");async function fo(e,{fetchFn:t=fetch,protocolVersion:r=zt}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=ks(e);for(let{url:a,type:s}of i){let c=await or(a,o,t);if(c){if(!c.ok){if(await c.body?.cancel(),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}return s==="oauth"?Ee.parse(await c.json()):yt.parse(await c.json())}}}n(fo,"discoverAuthorizationServerMetadata");async function Ps(e,t){let r,o;try{r=await mo(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch{}o||(o=String(new URL("/",e)));let i=await fo(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(Ps,"discoverOAuthServerInfo");async function Ts(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:i,state:a,resource:s}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Xt))throw new Error(`Incompatible auth server: does not support response type ${Xt}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Qt))throw new Error(`Incompatible auth server: does not support code challenge method ${Qt}`)}else c=new URL("/authorize",e);let l=await Vt(),h=l.code_verifier,m=l.code_challenge;return c.searchParams.set("response_type",Xt),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",m),c.searchParams.set("code_challenge_method",Qt),c.searchParams.set("redirect_uri",String(o)),a&&c.searchParams.set("state",a),i&&c.searchParams.set("scope",i),i?.includes("offline_access")&&c.searchParams.append("prompt","consent"),s&&c.searchParams.set("resource",s.href),{authorizationUrl:c,codeVerifier:h}}n(Ts,"startAuthorization");function Os(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(Os,"prepareAuthorizationCodeRequest");async function ho(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:i,resource:a,fetchFn:s}){let c=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(a&&r.set("resource",a.href),i)await i(l,r,c,t);else if(o){let m=t?.token_endpoint_auth_methods_supported??[],A=Rs(o,m);Cs(A,o,l,r)}let h=await(s??fetch)(c,{method:"POST",headers:l,body:r});if(!h.ok)throw await lo(h);return we.parse(await h.json())}n(ho,"executeTokenRequest");async function Es(e,{metadata:t,clientInformation:r,refreshToken:o,resource:i,addClientAuthentication:a,fetchFn:s}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),l=await ho(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:a,resource:i,fetchFn:s});return{refresh_token:o,...l}}n(Es,"refreshAuthorization");async function qs(e,t,{metadata:r,resource:o,authorizationCode:i,fetchFn:a}={}){let s=e.clientMetadata.scope,c;if(e.prepareTokenRequest&&(c=await e.prepareTokenRequest(s)),!c){if(!i)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let h=await e.codeVerifier();c=Os(i,h,e.redirectUrl)}let l=await e.clientInformation();return ho(t,{metadata:r,tokenRequestParams:c,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(qs,"fetchToken");async function Ms(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");a=new URL(t.registration_endpoint)}else a=new URL("/register",e);let s=await(i??fetch)(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!s.ok)throw await lo(s);return qe.parse(await s.json())}n(Ms,"registerClient");function re(e){let t=N().connectionsById.get(e);if(!t)throw new k(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,...t.description===void 0?{}:{description:t.description},...t.serverInfo===void 0?{}:{serverInfo:t.serverInfo},transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}n(re,"getUpstreamServerConfig");function zs(e){let t=N().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new k(`Unknown auth profile "${String(e.authProfileId)}" for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares a matching auth mode for that upstream connection.`);return t.authProfileId}n(zs,"resolveUpstreamAuthProfileId");function ir(e){zs(e);let t=N().connectionsById.get(e.upstreamServerId);if(!t)throw new k(`Auth profile could not be resolved for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares the upstream connection before this handler runs.`);return t.authConfig}n(ir,"getUpstreamAuthConfig");function fe(e,t){let r=ir({upstreamServerId:e,authProfileId:t});if(!gn(r))throw new k(`Upstream server "${e}" does not use upstream OAuth. Select an auth mode that supports the requested upstream connect flow or remove the upstream OAuth route for this server.`);return r.oauth}n(fe,"requireUpstreamOAuthConfig");var Ds={"shared-oauth":{authMode:"shared-oauth",ownerMode:"shared",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"},"user-oauth":{authMode:"user-oauth",ownerMode:"user",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"}};function j(e){return Ds[e]}n(j,"describeUpstreamAuthMode");function wt(e){return j(e).ownerMode}n(wt,"resolveOwnerModeForUpstreamAuthMode");z();import{errors as So,jwtVerify as vo,SignJWT as xo}from"jose";var T="zuplo-mcp-gateway",q=T,M="HS256";import{base64url as Bs}from"jose";var Hs=new TextEncoder,Ls="MCP gateway could not initialize secure key material.",Ns=32,go=new Map,yo=new Map,js;function Gs(){return js??jr.instance.authPrivateKey}n(Gs,"readAuthPrivateKey");function wo(e){return new E(Ls,e===void 0?void 0:{cause:e})}n(wo,"createGeneratedKeyMaterialError");function _o(e,t){let r=Bs.decode(t);if(r.byteLength!==Ns)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(_o,"decodeJwkKeyField");function $s(e){let t=Gs();if(!t)throw wo();try{let r=JSON.parse(t);if(r.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.d!="string"||typeof r.x!="string")throw new Error("Generated deployment auth key is not an Ed25519 JWK.");let o=_o("d",r.d);_o("x",r.x);let i=Hs.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),a=new Uint8Array(i.byteLength+o.byteLength);return a.set(i),a.set(o,i.byteLength),a}catch(r){throw wo(r)}}n($s,"decodeGeneratedKeyMaterial");function Zs(e){let t=go.get(e);return t||(t=$s(e),go.set(e,t)),t}n(Zs,"getMasterKeyMaterial");async function G(e){let t=yo.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Zs(e.keyMaterialPurpose));return yo.set(e.purpose,r),r}n(G,"readCachedDerivedKey");var Fs="SHA-256";var Ks="zuplo-mcp-gateway:",Js=new TextEncoder,Ro=new WeakMap;async function ne(e,t){let r=Ro.get(e);r||(r=new Map,Ro.set(e,r));let o=r.get(t);if(o)return o;let i=await Ws(e,t);return r.set(t,i),i}n(ne,"deriveGatewaySigningKey");async function Ws(e,t){let r=Co(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=Js.encode(`${Ks}${t}`),a=await crypto.subtle.deriveBits({name:"HKDF",hash:Fs,salt:new Uint8Array,info:Co(i)},o,32*8);return new Uint8Array(a)}n(Ws,"hkdfExpand");function Co(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(Co,"copyToArrayBuffer");var Ao=15*60,Vs=15*60,Ys=Hn.extend({id:Ln}),Xs=Ys.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),Io=$t.extend({id:Nn,purpose:d.literal("browser_connect")}),Qs=$t.extend({purpose:d.literal("browser_connect")}),ec=Io.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),Uo=Ao*1e3;async function ko(){return G({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>ne(e,"oauth-state"),"derive")})}n(ko,"getOAuthStateKey");async function Po(){return G({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>ne(e,"browser-connect"),"derive")})}n(Po,"getBrowserConnectKey");async function To(e){let t=Math.floor(Date.now()/1e3)+Ao;return new xo(e).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(t).sign(await ko())}n(To,"signOAuthState");async function _t(e){try{let{payload:t}=await vo(e,await ko(),{algorithms:[M],issuer:T,audience:q});return Xs.parse(t)}catch(t){throw t instanceof So.JWTExpired?new y({message:"OAuth state has expired",extensionMembers:{[w]:"oauth_state_expired"}},{cause:t}):new y({message:"OAuth state could not be verified",extensionMembers:{[w]:"oauth_state_invalid"}},{cause:t})}}n(_t,"verifyOAuthState");async function Oo(e){let t=Math.floor(Date.now()/1e3)+Vs,r=Qs.parse(e),o=Io.parse({...r,id:Zn()});return new xo(o).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(t).sign(await Po())}n(Oo,"signBrowserConnectTicket");async function Eo(e){try{let{payload:t}=await vo(e,await Po(),{algorithms:[M],issuer:T,audience:q});return ec.parse(t)}catch(t){throw t instanceof So.JWTExpired?new y({message:"Browser connect ticket has expired",extensionMembers:{[w]:"oauth_state_expired"}},{cause:t}):new y({message:"Browser connect ticket could not be verified",extensionMembers:{[w]:"oauth_state_invalid"}},{cause:t})}}n(Eo,"verifyBrowserConnectTicket");async function qo(e){if((await C().consumeBrowserConnectTicket({id:e.id,expiresAt:R(new Date(e.exp*1e3)),now:R(new Date)})).kind==="consumed")throw new y({message:"Browser connect ticket has already been used",extensionMembers:{[w]:"oauth_state_reused"}})}n(qo,"consumeBrowserConnectTicket");function tc(e,t,r=!1){return r?`${e} authorization must be renewed before this ${t} can be used.`:`${e} authorization is required before this ${t} can be used.`}n(tc,"buildConnectRequiredMessage");async function rc(e){let t=I(e.requestUrl),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("operationId",e.operationId),r.searchParams.set("browserTicket",await Oo({...Oe(e),purpose:"browser_connect"})),r.toString()}n(rc,"buildGatewayBrowserTicketUrl");function nc(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}n(nc,"buildGatewayConnectPath");async function ar(e){return rc({...e,path:nc(e.upstreamServerId),redirect:!0})}n(ar,"buildGatewayConnectUrl");async function Rt(e){let t={requestUrl:e.requestUrl,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await ar(t),message:tc(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(Rt,"buildRedirectConnectRequiredResponse");function Mo(e){return oc({...e,message:e.requiresReconsent?`An administrator must reconnect ${e.upstreamDisplayName} before this tool can be used.`:`An administrator must connect ${e.upstreamDisplayName} before this tool can be used.`})}n(Mo,"buildAdminConnectRequiredResponse");function oc(e){return{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},message:e.message,nextAction:"admin_setup_required"}}n(oc,"buildAdminSetupRequiredResponse");z();function sr(e){return`Zuplo MCP Gateway - ${e}`}n(sr,"buildGatewayOAuthClientName");function zo(e,t){let r=new URL(e,I(t));return ce(r)&&en(r.hostname)!=="localhost"&&(r.hostname="localhost"),r.toString()}n(zo,"buildGatewayOAuthRedirectUri");function cr(e){let t=new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin);return t.searchParams.set("authProfileId",e.authProfileId),t.toString()}n(cr,"buildOAuthClientMetadataDocumentUrl");function Do(e){return I(e)}n(Do,"requireOAuthClientMetadataOrigin");function Bo(e,t,r){let o=re(t),i=fe(t,r),a={client_id:cr({origin:e,upstreamServerId:t,authProfileId:r}),client_name:sr(o.displayName),client_uri:new URL("/",e).toString(),redirect_uris:[new URL(i.redirectPath,e).toString()],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",token_endpoint_auth_method:"none"};return i.scopes.length>0&&(a.scope=i.scopes.join(i.scopeDelimiter)),a}n(Bo,"buildOAuthClientMetadataDocument");z();import{base64url as oe}from"jose";var ic="SHA-256",Re="AES-GCM",ac=12,ur="zuplo-secret",lr=1,Ho="generated:auth_private_key:token-encryption",sc=d.object({version:d.literal(lr),keyId:d.literal(Ho),algorithm:d.literal(Re),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();function _e(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(_e,"copyToArrayBuffer");async function dr(){return G({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(ic,_e(e));return crypto.subtle.importKey("raw",t,{name:Re},!1,["encrypt","decrypt"])},"derive")})}n(dr,"getEncryptionKey");function Lo(e){return _e(new TextEncoder().encode(`${ur}:v${e.version}:${e.keyId}`))}n(Lo,"getAssociatedData");function cc(e){return`${ur}:v${e.version}:${oe.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(cc,"encodeEnvelope");function dc(e){let t=`${ur}:v${lr}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(oe.decode(r));return sc.parse(JSON.parse(o))}n(dc,"decodeEnvelope");async function Ct(e){let t=await dr(),r=crypto.getRandomValues(new Uint8Array(ac)),o={version:lr,keyId:Ho},i=await crypto.subtle.encrypt({name:Re,iv:r,additionalData:Lo(o)},t,new TextEncoder().encode(e));return cc({...o,algorithm:Re,iv:oe.encode(r),ciphertext:oe.encode(new Uint8Array(i))})}n(Ct,"encryptSecret");async function Ke(e){let t=dc(e);if(t){let s=await dr(),c=await crypto.subtle.decrypt({name:Re,iv:_e(oe.decode(t.iv)),additionalData:Lo(t)},s,_e(oe.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,o]=e.split(".");if(!r||!o)throw new E("Encrypted payload is malformed");let i=await dr(),a=await crypto.subtle.decrypt({name:Re,iv:_e(oe.decode(r))},i,_e(oe.decode(o)));return new TextDecoder().decode(a)}n(Ke,"decryptSecret");var uc=d.union([qe,Yt]),lc=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:gt.optional(),authorizationServerMetadata:d.union([Ee,yt]).optional()}).passthrough(),pc="Bearer",mc="__zuplo_refresh_only_upstream_access_token__";function fc(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(fc,"splitScopes");function hc(e){return ct.parse(e)}n(hc,"parsePkceCodeVerifier");function gc(e){if(typeof e.expires_in=="number")return R(new Date(Date.now()+e.expires_in*1e3))}n(gc,"readTokenExpiry");async function No(e){if(e!==void 0)return Ct(JSON.stringify(e))}n(No,"encryptJson");async function jo(e,t){if(!e)return;let r=await Ke(e);try{return t.parse(JSON.parse(r))}catch(o){throw new y({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[w]:"oauth_state_invalid"}},{cause:o})}}n(jo,"decryptJson");function yc(e){if(e===void 0)return;let t={authorizationServerUrl:e.authorizationServerUrl};return e.resourceMetadataUrl!==void 0&&(t.resourceMetadataUrl=e.resourceMetadataUrl),e.resourceMetadata!==void 0&&(t.resourceMetadata=e.resourceMetadata),e.authorizationServerMetadata!==void 0&&(t.authorizationServerMetadata=e.authorizationServerMetadata),t}n(yc,"toOAuthDiscoveryState");function wc(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(wc,"clientInformationAllowsRedirectUri");function _c(e,t,r){let o=re(e),i=fe(e,t),a=pr(i.scopes,i.scopeDelimiter);return{client_name:sr(o.displayName),client_uri:new URL("/",new URL(r).origin).toString(),redirect_uris:[r],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",scope:a,token_endpoint_auth_method:"none"}}n(_c,"buildOAuthClientMetadata");function pr(e,t){return e&&e.length>0?e.join(t):void 0}n(pr,"joinOAuthScopes");function Rc(e,t){return t===void 0?e:{...e,scope:t}}n(Rc,"applyOAuthClientMetadataScope");function Go(e,t){return pr(e?.resourceMetadata?.scopes_supported,t)}n(Go,"readResourceMetadataScope");function Cc(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new k(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return qe.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(Cc,"buildManualOAuthClientInformation");function bc(e,t,r){let o=cr({origin:new URL(r).origin,upstreamServerId:e,authProfileId:t});return nr(o)?o:void 0}n(bc,"buildClientMetadataUrl");function $o(e){for(let t of e)if(t!==void 0)return t}n($o,"firstDefined");function Sc(e){let t=fe(e.target.upstreamServerId,e.target.authProfileId),r=_c(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri),o=pr(t.scopes,t.scopeDelimiter);if(t.clientRegistration.mode==="manual")return{clientMetadata:r,configuredScope:o,scopeDelimiter:t.scopeDelimiter,configuredClientInformation:Cc({clientMetadata:r,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let i=bc(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);return i===void 0?{clientMetadata:r,configuredScope:o,scopeDelimiter:t.scopeDelimiter}:{clientMetadata:r,configuredScope:o,scopeDelimiter:t.scopeDelimiter,clientMetadataUrl:i}}n(Sc,"buildInitialOAuthClientSetup");function vc(e,t){if(t===void 0)return $o([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(vc,"readEncryptedClientInformation");function xc(e){return $o([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}n(xc,"readEncryptedDiscoveryState");var he=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredScope;scopeDelimiter;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;connection;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;constructor(t){let r=Sc({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.clientMetadataValue=r.clientMetadata,this.configuredScope=r.configuredScope,this.scopeDelimiter=r.scopeDelimiter,this.configuredClientInformation=r.configuredClientInformation,r.clientMetadataUrl!==void 0&&(this.clientMetadataUrl=r.clientMetadataUrl),this.connection=t.connection,this.pendingState=t.pendingState?{...t.pendingState}:void 0,this.encryptedClientInformation=vc(t,this.configuredClientInformation),this.encryptedDiscoveryState=xc(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return Rc(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return To({id:t.id,...Oe({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId})})}async clientInformation(){return this.configuredClientInformation?this.configuredClientInformation:this.loadPersistedClientInformation()}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.encryptedClientInformation=await No(t),await this.syncPendingState(!1))}async discoveryState(){return this.loadPersistedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){this.cachedDiscoveryState=t,this.discoveryStateLoaded=!0,this.inferredScope=Go(t,this.scopeDelimiter),this.encryptedDiscoveryState=await No(t),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=we.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=r.refresh_token?await Ct(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:we.parse({...r,refresh_token:await Ke(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let a={id:this.connection?.id??Gn(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await Ct(r.access_token),encryptedRefreshToken:i,scopes:fc(r.scope??this.readEffectiveScope()),expiresAt:gc(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await C().upsertUpstreamConnection(a)}async redirectToAuthorization(t){this.authorizationUrlValue=t.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:hc(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new y({message:"OAuth code verifier is missing",extensionMembers:{[w]:"oauth_state_invalid"}});return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",o=t==="all"||t==="client",i=t==="all"||t==="discovery",a=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),i&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0,this.challengeScope=void 0,this.inferredScope=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(a),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:$n(),...Oe({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,operationId:this.target.operationId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:R(new Date(Date.now()+Uo)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await C().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await jo(this.encryptedClientInformation,uc)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&!wc(t,this.redirectUriValue)){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1);return}return this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async loadPersistedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;try{this.cachedDiscoveryState=yc(await jo(this.encryptedDiscoveryState,lc))}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1)}return this.discoveryStateLoaded=!0,this.inferredScope=Go(this.cachedDiscoveryState,this.scopeDelimiter),this.cachedDiscoveryState}readEffectiveScope(){return this.configuredScope??this.challengeScope??this.inferredScope}async loadStoredTokens(){if(this.tokensLoaded)return this.cachedTokens;if(this.tokensLoaded=!0,!this.connection||this.connection.status!=="active")return;let t=this.connection.encryptedAccessToken?await Ke(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await Ke(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=we.parse({access_token:t??mc,token_type:pc,refresh_token:r,scope:this.connection.scopes.length>0?this.connection.scopes.join(" "):void 0});return this.cachedTokens=o,o}async persistCredentialInvalidation(t){if(!this.connection)return;let r={id:this.connection.id,ownerMode:this.connection.ownerMode,subjectId:this.connection.subjectId,upstreamServerId:this.connection.upstreamServerId,authProfileId:this.connection.authProfileId,status:this.connection.status,encryptedAccessToken:this.connection.encryptedAccessToken,encryptedRefreshToken:this.connection.encryptedRefreshToken,scopes:[...this.connection.scopes],expiresAt:this.connection.expiresAt,metadata:this.connection.metadata?{...this.connection.metadata}:void 0};t&&(r.status="reconsent_required",r.encryptedAccessToken=void 0,r.encryptedRefreshToken=void 0,r.scopes=[],r.expiresAt=void 0),r.metadata=this.readStoredOAuthPersistence(this.connection.metadata?.connectedBySubjectId),this.connection=await C().upsertUpstreamConnection(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var Ac=3e4,Ic=256*1024,Uc=2;function kc(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(kc,"hasUsableAccessToken");var Pc="does not support dynamic client registration";function Tc(e){return e instanceof Error&&e.message.includes(Pc)}n(Tc,"isDynamicClientRegistrationUnsupported");function Oc(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(Oc,"readOAuthFetchRequest");function Ec(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(Ec,"responseLooksJson");function Zo(e){return async(t,r)=>{let o=Oc(t),i=await Vn(t,r,{maxRedirects:Uc,maxResponseBytes:Ic,problemCode:"upstream_token_exchange_failed",timeoutMs:Ac}),a=await i.clone().text();if(!Ec(i,a))return i;try{JSON.parse(a)}catch(s){throw new y({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[w]:"upstream_token_exchange_failed"}},{cause:s})}return i}}n(Zo,"createUpstreamOAuthFetch");async function Fo(e,t){e.applyChallengeScope(t.requestedScope);try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Zo(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),await rr(e,r)}catch(r){throw Tc(r)?new y({message:`The authorization server for ${t.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register a client for the gateway manually before retrying.`,extensionMembers:{[w]:"upstream_client_registration_required"}},{cause:r}):r}}n(Fo,"runUpstreamOAuth");async function qc(e,t){e.applyChallengeScope(t.requestedScope);let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Zo(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),rr(e,r)}n(qc,"exchangeUpstreamAuthorizationCode");async function Ko(e,t){let r=await Fo(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new y({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}}):new y({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}})}n(Ko,"requireUpstreamAuthorizationRedirect");async function Jo(e){if(!e.forceRefresh&&kc(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await Fo(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}});if(t==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(t!=="REDIRECT")throw new y({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new y({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}});return{kind:"connect_required",payload:await Hc({requestUrl:e.target.request.url,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}n(Jo,"authorizeUpstreamOAuthSession");async function Mc(e){let t=await _t(e.stateToken),r=await C().consumeUpstreamOAuthState({id:t.id,now:R(new Date)}),o=zc(r);return Dc({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),Bc(o),o}n(Mc,"consumeStoredCallbackState");function zc(e){switch(e.kind){case"consumed":throw new y({message:"OAuth state has already been used",extensionMembers:{[w]:"oauth_state_reused"}});case"missing":throw new y({message:"OAuth state is missing or expired",extensionMembers:{[w]:"oauth_state_expired"}});case"available":return e.record}}n(zc,"readConsumedCallbackState");function Dc(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.operationId===e.signedState.operationId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw new y({message:"OAuth callback did not match the initiating request",extensionMembers:{[w]:"oauth_callback_mismatch"}})}n(Dc,"assertStoredCallbackStateMatches");function Bc(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new y({message:"OAuth state has expired",extensionMembers:{[w]:"oauth_state_expired"}})}n(Bc,"assertStoredCallbackStateFresh");async function Hc(e){if(e.owner.mode==="shared"){let r={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,requiresReconsent:!!e.connection};return e.connection!==void 0&&(r.connectionId=e.connection.id),Mo(r)}let t={requestUrl:e.requestUrl,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,subject:"tool",requiresReconsent:!!e.connection,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return e.connection!==void 0&&(t.connectionId=e.connection.id),Rt(t)}n(Hc,"buildOAuthConnectRequiredResponse");async function Wo(e){let t=await Mc({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=pt(t),[o]=await C().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),i={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};o!==void 0&&(i.connection=o);let a=new he(i),s=await qc(a,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(s==="AUTHORIZED")return t;throw s!=="REDIRECT"?new y({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${s}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}}):new y({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}})}n(Wo,"finishUpstreamOAuthCallback");async function Vo(e){let t=re(e.upstreamServerId),r=fe(e.upstreamServerId,e.authProfileId),o=zo(r.redirectPath,e.request.url),i="preloadedConnection"in e?e.preloadedConnection:(await C().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:i,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}},redirectUri:o,returnOrigin:I(e.request.url)}}}n(Vo,"prepareUpstreamOAuthRequest");async function Yo(e){let t=await Vo(e),r=new he({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Ko(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Yo,"startUpstreamConnect");async function Xo(e){let t=await Vo(e),r=new he({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return Jo({target:e,provider:r,connection:t.connection,forceRefresh:e.forceRefresh,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope},upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Xo,"authorizeUpstreamRequest");async function Ce(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return Xo({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,forceRefresh:e.forceRefresh,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope},...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},...t.returnTo===void 0?{}:{returnTo:t.returnTo}})}let r=t;throw new E(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(Ce,"resolveUpstreamCredentialForRoute");async function Qo(e){let t,r={request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,operationId:e.connectRequest.operationId,...e.connectRequest.returnTo===void 0?{}:{returnTo:e.connectRequest.returnTo}},o=j(e.connectRequest.authMode);switch(o.connectSupport){case"oauth_authorization":t=await Yo(r);break;case"none":throw new E(o.connectUnsupportedDetail??`Upstream server ${e.connectRequest.upstreamServerId} does not support browser connection flows.`)}return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}n(Qo,"startUpstreamConnectForRequest");async function ei(e){let r=(await _t(e.callbackRequest.state)).authProfileId,o=ir({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r});if(j(o.mode).callbackSupport!=="authorization_code")throw new E(`Upstream server ${e.callbackRequest.upstreamServerId} does not support OAuth callbacks.`);return Wo({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:re(e.callbackRequest.upstreamServerId)})}n(ei,"finishUpstreamCallbackForRequest");function Lc(e){let t=j(e.connection.authMode);return{upstreamServerId:e.connection.upstreamServerId,operationId:e.operationId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:t.ownerMode}}n(Lc,"buildRouteAuthBaseFromConnection");function ri(e){let t=j(e.connection.authMode);return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:st(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:t.ownerMode}}n(ri,"buildRouteAuthBaseFromPolicyOptions");function bt(e,t){let o=N().byOperationId.get(t);if(!o)throw new k(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new k(`MCP route "${t}" does not declare an MCP token exchange policy. Add one before starting an upstream connection flow.`);if(o.connection.upstreamServerId!==e)throw new k(`MCP route "${t}" does not bind upstream "${e}". Check the route's MCP upstream policies and bind the upstream before starting an upstream connection flow.`);return Lc({connection:o.connection,operationId:t})}n(bt,"resolveRouteAuthBase");function ti(e,t){switch(e){case"user":return lt(t.subjectId);case"shared":return Bn()}}n(ti,"buildOwnerForPrincipal");function be(e,t){switch(e.ownerMode){case"shared":return{...e,owner:ti(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"user":return{...e,owner:ti(e.ownerMode,t),initiatedBySubjectId:t.subjectId}}}n(be,"resolveRouteAuthForPrincipal");var Nc=Te.InvalidRequest,jc=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function Gc(e,t){return{credentialType:e.type,forceRefresh:t,...e.type==="headers"?{headerNames:Object.keys(e.headers).sort()}:{}}}n(Gc,"buildCredentialResolvedAttributes");function $c(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n($c,"connectRequiredReasonCode");function ni(e){b(e.context,{eventType:_.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:Gc(e.credential,e.forceRefresh===!0)})}n(ni,"emitCredentialResolvedAnalyticsEvent");function oi(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(b(e.context,{eventType:_.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"connect_required",reasonClass:"auth",attributes:t}),e.payload.state==="reconsent_required"){b(e.context,{eventType:_.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}b(e.context,{eventType:_.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:$c(e.payload.state),reasonClass:"auth",attributes:t})}n(oi,"emitCredentialMissingAnalyticsEvents");function Zc(e){let t=e.route.raw();return ot.parse(t?.operationId)}n(Zc,"readOperationId");async function Fc(e,t,r,o){let i=await Ce({request:e,routeAuth:t});if(i.kind==="connect_required")return oi({context:o,payload:i.payload,routeBinding:t}),o.log.info({event:"mcp_upstream_connect_required",upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId},"MCP upstream proxy: upstream connection required"),{kind:"connect_required",payload:i.payload};let a=i.credential;switch(ni({context:o,credential:a,routeBinding:t}),a.type){case"none":return{kind:"headers",headers:[]};case"bearer_token":return{kind:"headers",headers:[["authorization",`Bearer ${a.token}`]]};case"headers":return{kind:"headers",headers:Object.entries(a.headers)};case"mcp_oauth_provider":{let s=await a.provider.tokens();return s?{kind:"headers",headers:[["authorization",`${s.token_type??"Bearer"} ${s.access_token}`]]}:(o.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:t.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),Response.json({error:"no_upstream_tokens"},{status:401}))}}}n(Fc,"buildCredentialHeaders");var Kc=new Set(["authorization","cookie","cookie2"]);function Jc(e,t){let r=new Headers(e.headers);for(let o of Kc)r.delete(o);for(let[o,i]of t)r.set(o,i);return new $r(e,{headers:r})}n(Jc,"applyUpstreamHeaders");function Wc(e){let t=new Headers(e.headers);for(let r of jc)t.delete(r);return t}n(Wc,"buildProxyHeaders");async function Vc(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(Vc,"readRetryBody");function ii(e,t){let r=t.authUrl===void 0?void 0:eo({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(ft({id:Qn(e),error:{code:r?.code??Nc,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(ii,"connectRequiredJsonRpcResponse");async function Yc(e){let{scope:t}=po(e.upstreamResponse),r=await Ce({request:e.request,routeAuth:e.routeAuth,forceRefresh:!0,...t===void 0?{}:{requestedScope:t}});if(r.kind==="connect_required")return oi({context:e.context,payload:r.payload,routeBinding:e.routeAuth,forceRefresh:!0}),{kind:"connect_required",payload:r.payload};let o=new Headers(e.headers),i=r.credential;switch(ni({context:e.context,credential:i,routeBinding:e.routeAuth,forceRefresh:!0}),i.type){case"none":return o.delete("authorization"),{kind:"headers",headers:o};case"bearer_token":return o.set("authorization",`Bearer ${i.token}`),{kind:"headers",headers:o};case"headers":for(let[a,s]of Object.entries(i.headers))o.set(a,s);return{kind:"headers",headers:o};case"mcp_oauth_provider":{let a=await i.provider.tokens();return a?(o.set("authorization",`${a.token_type??"Bearer"} ${a.access_token}`),{kind:"headers",headers:o}):(e.context.log.warn({event:"mcp_upstream_no_tokens_after_refresh",upstreamServerId:e.routeAuth.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens after refresh"),{kind:"response",response:Response.json({error:"no_upstream_tokens"},{status:401})})}}}n(Yc,"applyRefreshedCredentialHeaders");function Xc(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await Yc({request:e.request,context:e.context,headers:Wc(r),routeAuth:e.routeAuth,upstreamResponse:t});if(o.kind==="connect_required")return ii(e.requestBody,o.payload);if(o.kind==="response")return o.response;let i=dn({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return et.fetch(i.url,i.init)})}n(Xc,"installUpstreamAuthRetryHook");async function mr(e,t,r){let o=Zc(t),i=await Vc(e),a=ri({connection:r,operationId:o}),s=be(a,zn(e,t)),c=await Fc(e,s,r,t);if(!(c instanceof Response)&&c.kind==="connect_required")return ii(i,c.payload);if(c instanceof Response)return c;let l=Jc(e,c.headers);return Xc({request:l,context:t,requestBody:i,routeAuth:s}),l}n(mr,"mcpTokenExchangePolicy");var fr=class extends rt{static{n(this,"McpTokenExchangeInboundPolicy")}constructor(t,r){let o=hn(t,r);super(o,r)}async handler(t,r){return tt("policy.inbound.mcp-token-exchange"),mr(t,r,this.options)}};z();var ai=Symbol("Html");function Qc(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n(Qc,"escapeHtml");function ed(e){return e===null||typeof e!="object"?!1:e[ai]===!0}n(ed,"isHtml");function si(e){return e==null||e===!1?"":Array.isArray(e)?e.map(si).join(""):ed(e)?e.value:Qc(String(e))}n(si,"renderValue");function V(e){return{[ai]:!0,value:e}}n(V,"trustedHtml");var ge=V("");function S(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=si(t[o]),r+=e[o+1]??"";return V(r)}n(S,"html");function Se(e){return e.value}n(Se,"renderHtml");function ci(e){return S`<p data-gateway-error-code="${e.code}">${e.detail}</p>${e.guidance} ${e.action}`}n(ci,"renderBrowserErrorPage");var ve=V('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;justify-content:center;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;min-height:40px;padding:8px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.reconnect-action{align-items:center;margin-right:auto;display:inline-flex;position:relative}.reconnect-button{gap:7px}.tooltip{width:16px;height:16px;color:var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);cursor:help;border:1.5px solid;border-radius:50%;justify-content:center;align-items:center;font-size:10.5px;font-weight:700;line-height:1;display:inline-flex;position:relative}.tooltip:after{content:attr(aria-label);z-index:10;border-radius:var(--radius-sm);background:var(--accent);width:280px;max-width:min(280px,100vw - 48px);color:var(--accent-text);box-shadow:var(--shadow);text-align:left;white-space:normal;opacity:0;pointer-events:none;padding:12px 14px;font-size:13px;font-weight:600;line-height:1.45;transition:opacity .12s;position:absolute;bottom:calc(100% + 12px);left:50%;transform:translate(-50%)}.tooltip:before{content:"";z-index:11;border-left:7px solid #0000;border-right:7px solid #0000;border-top:8px solid var(--accent);opacity:0;pointer-events:none;transition:opacity .12s;position:absolute;bottom:calc(100% + 5px);left:50%;transform:translate(-50%)}.tooltip:hover:after,.tooltip:hover:before,.tooltip:focus-visible:after,.tooltip:focus-visible:before{opacity:1}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}.reconnect-action{justify-content:center;width:100%;margin-right:0}.reconnect-action .button{flex:1}.tooltip:after{left:auto;right:0;transform:none}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function xe(e){return S`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" href="${e.iconHref}" /><style>
26
26
  ${e.styles}
27
- </style></head><body><main class="card"><header class="card__head">${e.headerIcon}<h1 class="card__title">${e.heading}</h1>${e.subhead}</header><div class="card__body">${e.body}</div>${e.footer}</main></body></html>`}n(ve,"renderShell");var lr="zuplo.com";function ei(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(ei,"s2FaviconHref");function Mc(e){return`https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&drop_404_icon=true&fallback_opts=TYPE,SIZE,URL&url=http://${e}&size=128`}n(Mc,"strictFaviconHref");var bt=ei(lr);function Ct(e){let t=e.toLowerCase();return t===lr||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?ei(lr):Mc(e)}n(Ct,"resolveIconHref");function St(e){return b`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}n(St,"renderShellIcon");var zc="text/html; charset=utf-8";function xe(e){try{return new URL(e).host}catch{return""}}n(xe,"safeHostFromUrl");function $(e){let t=Ct(e.host),r=Dc(e.kind??"authorization_failed");return new Response(Ce(ve({title:e.title??r.title,iconHref:t,styles:Se,headerIcon:St({iconHref:t,fallbackIconHref:bt}),heading:e.title??r.title,subhead:"",body:Qo({code:e.code??"unknown",detail:e.detail,guidance:b`<p class="card__description">${r.guidance}</p>`,action:Hc(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":zc,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n($,"browserErrorPageResponse");function Dc(e){switch(e){case"session_expired":return{title:"Authorization expired",guidance:"Return to your MCP client and reconnect. Expired authorization requests cannot be resumed."};case"access_denied":return{title:"Authorization canceled",guidance:"Return to your MCP client to retry if you want to grant access."};case"configuration_error":return{title:"Configuration needs attention",guidance:"Contact your workspace admin with this error code. The gateway or upstream configuration must be fixed before retrying."};case"connection_failed":return{title:"Connection failed",guidance:"Return to your MCP client and reconnect this upstream. If this keeps happening, contact your gateway administrator with this error code."};case"invalid_request":return{title:"Authorization request invalid",guidance:"Return to your MCP client and try connecting again. If this keeps happening, the client request may need to be fixed."};case"admin_required":return{title:"Admin setup required",guidance:"Contact your workspace admin with this error code. This connection cannot be completed until setup is finished."};case"internal_error":return{title:"Gateway error",guidance:"Try again later from your MCP client. If this keeps happening, contact your gateway administrator with this error code."};case"authorization_failed":return{title:"Authorization failed",guidance:"Return to your MCP client and start authorization again. If this keeps happening, contact your gateway administrator with this error code."}}}n(Dc,"readBrowserErrorPagePresentation");function Hc(e){return e===void 0?he:b`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(Hc,"renderAction");var ti="application/json",Bc="application/x-www-form-urlencoded";function vt(e,t){return new y({message:e,extensionMembers:{[w]:"invalid_request"}},t===void 0?void 0:{cause:t})}n(vt,"invalidRequestError");function Lc(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}n(Lc,"normalizeContentType");function jc(e,t){return e===t?!0:t===ti&&e.endsWith("+json")}n(jc,"contentTypeMatches");function Nc(e,t){if(!t||t.length===0)return;let r=Lc(e.headers.get("content-type"));if(!t.some(o=>jc(r,o)))throw vt(`Request body must be ${t.join(" or ")}.`)}n(Nc,"assertExpectedContentType");function Gc(e,t,r){let o=e.headers.get("content-length");if(!o)return;let i=Number.parseInt(o,10);if(Number.isFinite(i)&&i>t)throw vt(`${r} exceeded the maximum allowed size.`)}n(Gc,"assertContentLengthWithinLimit");async function ri(e,t){let r=t.label??"Request body";Nc(e,t.expectedContentTypes),Gc(e,t.maxBytes,r);let o=await $n(e.body,{maxBytes:t.maxBytes,createLimitError:n(()=>vt(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(o)}n(ri,"readBoundedTextBody");async function ni(e,t){let r=await ri(e,{...t,expectedContentTypes:[ti]});try{return JSON.parse(r)}catch(o){throw vt("Request body must be valid JSON.",o)}}n(ni,"readBoundedJsonBody");async function oi(e,t){let r=await ri(e,{...t,expectedContentTypes:[Bc]});return new URLSearchParams(r)}n(oi,"readBoundedFormUrlEncodedBody");z();z();import{errors as ui,jwtVerify as li,SignJWT as pi}from"jose";z();import{errors as $c,jwtVerify as Zc,SignJWT as Fc}from"jose";var mr="zuplo_mcp_session",Kc=d.object({purpose:d.literal("gateway_browser_session"),sub:st,browserLoginOrigin:d.string().min(1),roles:d.array(d.string().min(1)).optional(),exp:d.number().int().positive(),iat:d.number().int().positive().optional()});function Wc(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let o=r.indexOf("=");if(o<0)continue;let i=r.slice(0,o).trim(),a=r.slice(o+1).trim();if(i)try{t.set(i,decodeURIComponent(a))}catch{t.set(i,a)}}return t}n(Wc,"parseCookieHeader");async function ii(){return G({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>re(e,"browser-session"),"derive")})}n(ii,"getBrowserSessionKey");function pr(e){let t=new URL(I(e)),r=[`${mr}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(pr,"buildBrowserSessionEvictionCookie");function Jc(e){let t=new URL(I(e.requestUrl)),r=[`${mr}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(Jc,"serializeSessionCookie");function ai(){return new URL(lt("url")).origin}n(ai,"readBrowserLoginOrigin");function fr(){return D().browserLogin.stateTtlSeconds}n(fr,"readBrowserLoginStateTtlSeconds");function si(e){if(!e.user)throw g("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return ct(e.user,e.url)}n(si,"resolveCurrentRequestPrincipal");async function xt(e,t={}){let r=Wc(e.headers.get("cookie")).get(mr);if(!r)return{};try{let{payload:o}=await Zc(r,await ii(),{algorithms:[M],issuer:T,audience:q}),i=Kc.parse(o);if(i.browserLoginOrigin!==ai())return{evictCookie:pr(e.url)};let a={subjectId:i.sub};return i.roles&&i.roles.length>0&&(a.roles=i.roles),{principal:a}}catch(o){return o instanceof $c.JWTExpired?{evictCookie:pr(e.url)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:o instanceof Error?o.name:"unknown",errorMessage:o instanceof Error?o.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:pr(e.url)})}}n(xt,"readBrowserSession");async function It(e){let t=D().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:ai()};e.principal.roles&&(r.roles=e.principal.roles);let o=await new Fc(r).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await ii());return Jc({value:o,requestUrl:e.requestUrl,ttlSeconds:t})}n(It,"createBrowserSessionCookie");async function ci(e){let t={};e.context!==void 0&&(t.context=e.context);let r=await xt(e.request,t);if(r.principal)return r.principal;let o=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(!o)throw g("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.");let{exchangeFederatedAuthorizationCode:i}=await import("../browser-login-idp-HWMCSYMR.js");return i({code:o,nonce:e.stateId,requestUrl:e.request.url,...e.context===void 0?{}:{context:e.context}})}n(ci,"resolveBrowserLoginCallbackPrincipal");function di(e){let t=D().browserLogin,r=new URL(lt("url")),o=new URL("/oauth/callback",wn(e.requestUrl));return An(r)?(r.searchParams.set("redirect_uri",o.toString()),r.searchParams.set("state",e.state),r):(r.searchParams.set("response_type","code"),r.searchParams.set("client_id",lt("clientId")),r.searchParams.set("redirect_uri",o.toString()),r.searchParams.set("scope",t.scope),r.searchParams.set("state",e.state),r.searchParams.set("nonce",e.nonce),t.audience&&r.searchParams.set("audience",t.audience),r)}n(di,"buildBrowserLoginUrl");var Vc={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},p=class extends Error{static{n(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,o=Vc[t],i){super(r,i),this.name="OAuthProtocolError",this.errorCode=t,this.status=o}};var Yc=5*60,Xc=d.object({purpose:d.literal("gateway_browser_login"),transactionId:Mt,stateId:zt,exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),Qc=d.object({purpose:d.literal("gateway_authorization_setup"),transactionId:Mt,stateId:zt,exp:d.number().int().positive(),iat:d.number().int().positive().optional()});async function mi(){return G({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>re(e,"browser-login"),"derive")})}n(mi,"getBrowserLoginKey");async function fi(){return G({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>re(e,"authorization-csrf"),"derive")})}n(fi,"getCsrfKey");function hi(e){return{now:e.now??new Date,ttlSeconds:fr()}}n(hi,"readPendingTransactionDependencies");function ed(e,t){return e.subjectId===t.subjectId}n(ed,"principalsMatch");function gi(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}n(gi,"toPendingPrincipal");function yi(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,operationId:e.transaction.operationId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:_(e.now),expiresAt:_(F(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw g("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:gi(e.principal)}}n(yi,"createTransactionRecord");async function wi(e){let{id:t,...r}=e.record,o=await R().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(o.kind){case"started":return o.transaction;case"already_exists":throw g("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new p("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new p("invalid_request","redirect_uri is not registered for the client.")}}n(wi,"startPendingTransaction");async function td(e){return new pi({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await mi())}n(td,"signBrowserLoginState");async function _i(e){return new pi({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:Ht()}).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await fi())}n(_i,"signCsrfToken");async function hr(e){try{let{payload:t}=await li(e,await mi(),{algorithms:[M],issuer:T,audience:q}),r=Xc.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof ui.JWTExpired?g("oauth_state_expired","Browser login state has expired.",t):g("oauth_state_invalid","Browser login state could not be verified.",t)}}n(hr,"verifyBrowserLoginStateToken");async function At(e){try{let{payload:t}=await li(e,await fi(),{algorithms:[M],issuer:T,audience:q});return{transactionId:Qc.parse(t).transactionId}}catch(t){throw t instanceof ui.JWTExpired?g("oauth_state_expired","Authorization setup state has expired.",t):g("oauth_state_invalid","Authorization setup state could not be verified.",t)}}n(At,"verifyCsrfToken");function gr(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}n(gr,"pendingStateErrorCode");function rd(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}n(rd,"toPendingAuthorizationGetResult");function nd(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}n(nd,"toPendingAuthorizationAdvanceResult");function yr(e){return e==="principal_mismatch"?"oauth_callback_mismatch":gr(e==="consumed_already"?"consumed_already":e)}n(yr,"setupDecisionErrorCode");async function Ri(e){let t=e.now??new Date,r=await At(e.csrfToken),o=await R().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await C(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:_(t)});if(o.kind!=="marked")throw g(yr(o.kind),"Authorization setup state is invalid, expired, or already used.");return bi({kind:"available",record:o.transaction})}n(Ri,"markSetupApproved");function bi(e){if(e.kind!=="available")throw g(gr(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}n(bi,"requireAwaitingSetup");function od(e){if(!ed(e.currentBrowserPrincipal,e.transaction.principal))throw g("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}n(od,"requireCurrentPrincipalMatches");async function Ci(e){let t=e.now??new Date,r=fr(),o=Dt(),i=Ht(),a=await td({transactionId:o,stateId:i,ttlSeconds:r}),s=yi({id:o,transaction:e.transaction,currentStateHash:await C(a),phase:"awaiting_login",now:t,ttlSeconds:r});if(s.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");let c=await wi({record:s,client:e.transaction.client});if(c.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");return{transaction:c,browserLoginStateToken:a,browserLoginUrl:di({state:a,nonce:i,operationId:s.operationId,requestUrl:e.requestUrl})}}n(Ci,"startAwaitingLogin");async function Si(e){let{now:t,ttlSeconds:r}=hi(e),o=Dt(),i=await _i({transactionId:o,ttlSeconds:r}),a=yi({id:o,transaction:e.transaction,currentStateHash:await C(i),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(a.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");let s=await wi({record:a,client:e.transaction.client});if(s.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:s,csrfToken:i}}n(Si,"startAwaitingSetup");async function vi(e){let{now:t,ttlSeconds:r}=hi(e),o=await hr(e.browserLoginStateToken),i=await _i({transactionId:o.transactionId,ttlSeconds:r}),a=nd(await R().advancePendingAuthorization({transactionId:o.transactionId,expectedPhase:"awaiting_login",currentStateHash:await C(e.browserLoginStateToken),nextStateHash:await C(i),nextPhase:"awaiting_setup",principal:gi(e.principal),now:_(t)}));if(a.kind!=="advanced")throw g(gr(a.kind),"Browser login state is invalid, expired, or already used.");if(a.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:a.record,csrfToken:i}}n(vi,"completeLogin");async function xi(e){let t=await wr(e);return od({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}n(xi,"getSetup");async function wr(e){let t=e.now??new Date,r=await At(e.csrfToken);return bi(rd(await R().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await C(e.csrfToken),now:_(t)})))}n(wr,"getSetupTransaction");async function id(e){let t=await At(e.csrfToken),r=W(),o=_(F(e.now,Yc)),i=await R().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await C(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await C(r),authorizationCodeExpiresAt:o,grantId:xn(),now:_(e.now)});if(i.kind!=="approved")throw g(i.kind==="cancelled"?"oauth_state_invalid":yr(i.kind),"Authorization setup state is invalid, expired, or already used.");let a=new URL(i.transaction.redirectUri);return a.searchParams.set("code",r),i.transaction.clientState&&a.searchParams.set("state",i.transaction.clientState),a}n(id,"createAuthorizationCodeRedirectWithDecision");async function ad(e){let t=await At(e.csrfToken),r=await R().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await C(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:_(e.now)});if(r.kind!=="cancelled")throw g(r.kind==="approved"?"oauth_state_invalid":yr(r.kind),"Authorization setup state is invalid, expired, or already used.");return sd({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}n(ad,"createCancelRedirectWithDecision");function sd(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),t}n(sd,"buildClientCancelRedirect");async function Ii(e){let t=e.now??new Date;return id({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Ii,"approve");async function Ai(e){let t=e.now??new Date;return ad({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Ai,"cancel");z();var cd=1e4,dd=5*1024,ud=2,ld=90*24*60*60,_r=["authorization_code","refresh_token"],Rr=["code"],pd=d.object({client_name:d.string().min(1).optional(),redirect_uris:d.array(d.string().min(1)).min(1),grant_types:d.array(d.enum(_r)).min(1).max(2).optional(),response_types:d.array(d.enum(Rr)).min(1).max(1).optional(),scope:d.literal(P).optional(),token_endpoint_auth_method:Sn.default("none")});function md(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&se(t))&&t.pathname!=="/"}catch{return!1}}n(md,"isCimdClientIdCandidate");function Ie(e,t="invalid_request",r="authorize"){if(fd(e))throw new p(t,"redirect_uris must not include raw whitespace or control characters.");let o;try{o=new URL(e)}catch{throw new p(t,"redirect_uris must be absolute URIs.")}if(o.hash||o.username||o.password)throw new p(t,"redirect_uris must not include credentials or fragments.");let i={source:r},a=bn({url:o,context:i});if(a.kind!=="rejected"){a.mode!=="strict"&&void 0;return}throw new p(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}n(Ie,"assertValidRedirectUri");function fd(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}n(fd,"hasForbiddenRawRedirectUriCharacter");async function hd(e){let{response:t,json:r}=await Fn(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:ud,maxResponseBytes:dd,timeoutMs:cd});if(!t.ok)throw g("invalid_request","CIMD metadata could not be fetched.");let o=vn.parse(r);for(let i of o.redirect_uris)Ie(i,"invalid_request","cimd");if(o.client_id!==e.clientId)throw g("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return o}n(hd,"fetchCimdMetadata");async function gd(e){let t=Gn(e),r=await hd({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}n(gd,"resolveCimdClient");async function Ut(e,t){let r=ee.parse(e);if(md(r)){if(!D().gateway.cimdEnabled)throw new p("invalid_client","OAuth client is not registered.");try{return await gd(r)}catch{throw new p("invalid_client","OAuth client is not registered.")}}let o=await R().readClient({clientId:r});if(o.kind==="found"){let i=o.client,a={kind:"dcr",clientId:r,metadata:{client_id:i.clientId,client_name:i.clientName,redirect_uris:i.redirectUris,token_endpoint_auth_method:i.tokenEndpointAuthMethod}};return i.hashedClientSecret&&(a.hashedClientSecret=i.hashedClientSecret),a}throw new p("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}n(Ut,"resolveClient");function Ui(e,t){if(!e.metadata.redirect_uris.some(r=>In(r,t)))throw g("invalid_request","redirect_uri is not registered for the client.")}n(Ui,"assertRedirectRegistered");function yd(e){let t=ki(e.grant_types),r=e.response_types??[...Rr];if(!wd(t))throw new p("invalid_client_metadata","grant_types must be a subset of authorization_code and refresh_token.");if(!_d(r))throw new p("invalid_client_metadata","response_types must be code.");if(!Rd(e.scope))throw new p("invalid_client_metadata",`Only the ${P} scope is supported.`)}n(yd,"assertSupportedDcrRequest");function ki(e){return e===void 0?[..._r]:Array.from(new Set(e))}n(ki,"normalizeGrantTypes");function wd(e){return e.length===0?!1:e.every(t=>_r.includes(t))}n(wd,"isSupportedGrantTypes");function _d(e){return e.length===Rr.length&&e[0]==="code"}n(_d,"isSupportedResponseTypes");function Rd(e){return e===void 0||e===P}n(Rd,"isSupportedDcrScope");function Ke(e){if(e===void 0||e===P)return P;throw new p("invalid_request",`Only the ${P} scope is supported.`)}n(Ke,"assertSupportedOAuthScope");function Ae(e,t){let r;try{r=new URL(t)}catch{throw new p("invalid_target","resource must be an absolute URI.")}if(r.hash)throw new p("invalid_target","resource must not include a fragment.");if(r.protocol!=="https:"&&!se(r))throw new p("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let o=I(e),i=yn(),a=i?[...i.byOperationId.values()].find(s=>new URL(s.routePath,o).toString()===t):void 0;if(!a)throw new p("invalid_target","resource must match a published MCP route.");return a}n(Ae,"resolveResource");async function Pi(e){let t;try{t=pd.parse(e)}catch(m){if(m instanceof d.ZodError){let v=m.issues.some(L=>L.path[0]==="redirect_uris");throw new p(v?"invalid_redirect_uri":"invalid_client_metadata",m.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:m})}throw m}yd(t);for(let m of t.redirect_uris)Ie(m,"invalid_redirect_uri","dcr");let r=new Date,o=ee.parse(`dcr:${crypto.randomUUID()}`),i=F(r,ld),a=Math.floor(r.getTime()/1e3),s=Math.floor(i.getTime()/1e3),c={client_id:o,client_name:t.client_name??"Dynamically registered MCP client",redirect_uris:t.redirect_uris,grant_types:ki(t.grant_types),response_types:["code"],scope:P,token_endpoint_auth_method:t.token_endpoint_auth_method,client_id_issued_at:a},l={clientId:o,clientName:String(c.client_name),redirectUris:t.redirect_uris,tokenEndpointAuthMethod:t.token_endpoint_auth_method,createdAt:_(r),clientExpiresAt:_(i)};if(t.token_endpoint_auth_method!=="none"){let m=W();l.hashedClientSecret=await C(m),l.clientSecretExpiresAt=_(i),c.client_secret=m,c.client_secret_expires_at=s,c.client_secret_issued_at=a}if((await R().registerClient(l)).kind==="already_exists")throw g("invalid_request","OAuth client is already registered.");return c}n(Pi,"registerDownstreamClient");function Ti(e){return b`<form class="actions" method="post" action="/oauth/setup" ${e.submitOnceAttrs}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate >Cancel</button><button class="button button--primary" type="submit" name="decision" value="approve" ${e.authorizeAttrs} >Authorize</button></form>`}n(Ti,"renderActions");var _h=V('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="4.6" x2="8" y2="8.4"/><circle cx="8" cy="11" r=".7" fill="currentColor" stroke="none"/></svg>');var Rh=V('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),bh=V('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>');var Ch=V('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var bd="data:,",Oi=b`data-submit-once="true" onsubmit="if (this.dataset.submitted === 'true') return false; this.dataset.submitted = 'true'; setTimeout(() => this.querySelectorAll('button').forEach((button) => { button.disabled = true; }), 0);"`,Ei=b`data-activate-once="true" onclick="if (this.dataset.activated === 'true') return false; this.dataset.activated = 'true'; this.setAttribute('aria-disabled', 'true'); this.style.pointerEvents = 'none';"`;function Cd(e,t){if(e)try{let r=new URL(t).origin,o=new URL(e,r);return o.origin!==r||!o.pathname.startsWith("/auth/connections/")?void 0:o.toString()}catch{return}}n(Cd,"safeGatewayConnectHref");function Sd(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}n(Sd,"deriveMode");function vd(e){return Ti({state:e.state,submitOnceAttrs:Oi,authorizeAttrs:he})}n(vd,"renderActions");function br(e,t,r){for(let o of e){if(o.ownerMode!=="user"||o.status!==r)continue;let i=Cd(o.connectUrl,t);if(i)return i}}n(br,"firstUserConnectHref");function xd(e){let t=e.connectHref?b`<a class="button button--primary" href="${e.connectHref}" ${Ei}>Connect</a>`:b`<button class="button button--primary" type="button" disabled aria-disabled="true">Connect</button>`;return b`<form class="actions" method="post" action="/oauth/setup" ${Oi}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate>Cancel</button>${t}</form>`}n(xd,"renderSetupActions");function Id(e){return e?b`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${Ei}>Re-connect<span class="tooltip" tabindex="0" aria-label="Reset or change how the gateway connects to the upstream service, including changing scopes.">?</span></a></span>`:he}n(Id,"renderReconnectAction");function Cr(e){let t=Sd(e.upstreams),r=br(e.upstreams,e.gatewayOrigin,"not_connected"),o=br(e.upstreams,e.gatewayOrigin,"reconsent_required"),i=br(e.upstreams,e.gatewayOrigin,"active"),a=t==="setup"?r??o:void 0,s=b`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>`,c=t==="setup"?b`<footer class="card__footer">${xd({state:e.state,connectHref:a})}</footer>`:b`<footer class="card__footer">${Id(i)}${vd({state:e.state})}</footer>`;return Ce(ve({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:bd,styles:Se,headerIcon:he,heading:"MCP Gateway",subhead:he,body:s,footer:c}))}n(Cr,"renderConsentPage");var Ad=1e4,qi="mcp-session-id",Ud,Mi;function Li(){return{tools:[],prompts:[],resources:[]}}n(Li,"emptyCapabilities");function zi(e){let t=new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":Bt});switch(e.type){case"none":return t;case"bearer_token":return t.set("authorization",`Bearer ${e.token}`),t;case"headers":for(let[r,o]of Object.entries(e.headers))t.set(r,o);return t;case"mcp_oauth_provider":throw new Error("MCP OAuth provider credentials require async headers.")}}n(zi,"buildCredentialHeaders");async function Di(e){if(e.type!=="mcp_oauth_provider")return zi(e);let t=await e.provider.tokens();if(!t)return;let r=zi({type:"none"});return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}n(Di,"buildAsyncCredentialHeaders");function Hi(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(ot.parse({jsonrpc:nt,id:1,method:"initialize",params:{protocolVersion:Bt,capabilities:{},clientInfo:{name:"zuplo-mcp-gateway-readiness",version:"0.0.0"}}}))})}n(Hi,"buildInitializePreflight");async function Sr(e){Nn(e.url);let t=new AbortController,r=setTimeout(()=>t.abort(),Ad);try{let o=new Request(e,{redirect:"manual",signal:t.signal});return Mi?await Mi(o):await Xe.fetch(o)}finally{clearTimeout(r)}}n(Sr,"runPreflight");function vr(e){e.body?.cancel().catch(()=>{})}n(vr,"releasePreflightBody");async function kd(e){let t=e.response.headers.get(qi);if(!t)return;let r=new Headers(e.headers);r.set(qi,t),r.delete("content-type");try{let o=await Sr(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));vr(o)}catch{}}n(kd,"terminatePreflightSession");async function ji(e){let{response:t}=e;return vr(t),t.status>=200&&t.status<300?(await kd(e),{kind:"ready",upstreamStatus:t.status,capabilities:Li()}):t.status===401||t.status===403?{kind:"upstream_auth_rejected",status:t.status,message:"Upstream MCP server rejected the configured credential."}:{kind:"upstream_unavailable",status:t.status,message:"Upstream MCP server did not accept the readiness preflight."}}n(ji,"classifyResponse");function Bi(e){let t={status:e.state==="reconsent_required"?"reconsent_required":"not_connected",connected:!1};return e.nextAction==="admin_setup_required"?{kind:"admin_setup_required",payload:e,connectionStatus:t}:{kind:"connect_required",payload:e,connectionStatus:t}}n(Bi,"connectRequiredResult");async function Pd(e){try{return ji({response:await Sr(e.request),upstreamUrl:e.upstreamUrl,headers:e.headers})}catch(t){return{kind:"upstream_unavailable",message:t instanceof Error?t.message:"Upstream MCP server readiness preflight failed."}}}n(Pd,"classifyPreflight");async function Td(e){let t=e.route.connection;if(t===void 0)return{kind:"ready",upstreamStatus:204,capabilities:Li()};let r=Rt(t.upstreamServerId,e.route.operationId),o=be(r,e.principal),i=e.returnTo===void 0?o:{...o,returnTo:e.returnTo},a=await Re({request:new Request(e.requestUrl),routeAuth:i,preloadedConnection:e.preloadedConnection});if(a.kind==="connect_required")return Bi(a.payload);let s=await Di(a.credential);if(s===void 0)return{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens."};let c=Hi({upstreamUrl:t.mcpUrl,headers:s}),l;try{l=await Sr(c)}catch(v){return{kind:"upstream_unavailable",message:v instanceof Error?v.message:"Upstream MCP server readiness preflight failed."}}if(l.status!==401)return ji({response:l,upstreamUrl:t.mcpUrl,headers:s});vr(l);let h=await Re({request:new Request(e.requestUrl),routeAuth:i,forceRefresh:!0,preloadedConnection:e.preloadedConnection});if(h.kind==="connect_required")return Bi(h.payload);let m=await Di(h.credential);return m===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:Pd({request:Hi({upstreamUrl:t.mcpUrl,headers:m}),upstreamUrl:t.mcpUrl,headers:m})}n(Td,"checkUpstreamRouteReadinessImpl");function Ni(e){return(Ud??Td)(e)}n(Ni,"checkUpstreamRouteReadiness");function Od(e){try{return new URL(e).host}catch{return}}n(Od,"safeUrlHost");function Ed(e){if(e.mode==="user-oauth"||e.mode==="shared-oauth")return e.oauth.scopes}n(Ed,"readOAuthScopes");function Gi(e){return e!==void 0&&e.length>0}n(Gi,"hasItems");function qd(e){let t=e.serverInfo?.icons;return Gi(t)?t:void 0}n(qd,"readServerIcons");async function Md(e){if(!(e.returnTo===void 0||!e.isUserOwned))return nr({requestUrl:e.requestUrl,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:e.registeredConnection.upstreamServerId,authProfileId:e.registeredConnection.authProfileId,operationId:e.route.operationId,returnTo:e.returnTo})}n(Md,"readConnectUrl");function ge(e,t){return t===void 0?{}:{[e]:t}}n(ge,"optionalRequirementField");function zd(e){return e.readiness!==void 0?e.readiness:e.isUserOwned?Dn(e.connection):{connected:!0,status:"active"}}n(zd,"readSetupConnectionStatus");function Dd(e){let t=Ed(e);return Gi(t)?t:void 0}n(Dd,"readScopesRequested");function Hd(e){return e.isUserOwned&&"updatedAt"in e.connectionStatus&&e.connectionStatus.updatedAt!==void 0?e.connectionStatus.updatedAt:void 0}n(Hd,"readUpdatedAt");function Bd(){return{tools:[],prompts:[],resources:[]}}n(Bd,"readRouteCapabilities");async function Ld(e){let{authConfig:t,authMode:r,description:o,displayName:i,mcpUrl:a,upstreamServerId:s,authProfileId:c}=e.registeredConnection,l=ft(r),h=l==="user",m=zd({connection:e.connection,isUserOwned:h,readiness:e.readiness}),v=e.readiness?.connectUrl??await Md({...e,connected:m.connected,isUserOwned:h});return{upstreamServerId:s,authProfileId:c,authMode:r,ownerMode:l,upstreamDisplayName:i,status:m.status,connected:m.connected,capabilities:Bd(),...ge("description",o),...ge("transportHost",Od(a)),...ge("scopesRequested",Dd(t)),...ge("serverIcons",qd(e.registeredConnection)),...ge("connectUrl",v),...ge("updatedAt",Hd({connectionStatus:m,isUserOwned:h})),...ge("expiresAt",e.readiness?.expiresAt??e.connection?.expiresAt)}}n(Ld,"buildSetupRequirement");function $i(e){let t=j().byOperationId.get(e);if(!t)throw g("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}n($i,"requireRoute");async function xr(e){let t=$i(e.transaction.operationId),r=dt(e.transaction.principal.subjectId),o=[],i=new Map,a=t.connection;if(a===void 0)return[];ft(a.authMode)==="user"&&(i.set(a,o.length),o.push({owner:r,upstreamServerId:a.upstreamServerId,authProfileId:a.authProfileId}));let s=await R().batchGetUpstreamConnections(o),c=[],l=ft(a.authMode)==="user",h=i.get(a),m=await Ni({requestUrl:e.requestUrl,route:t,principal:e.transaction.principal,preloadedConnection:l&&h!==void 0?s[h]:void 0,...e.returnTo===void 0?{}:{returnTo:e.returnTo}}),v=(()=>{if("connectionStatus"in m&&m.connectionStatus)return m.connectionStatus})(),L=(m.kind==="connect_required"||m.kind==="admin_setup_required")&&m.payload.authUrl!==void 0?m.payload.authUrl:void 0;return c.push(await Ld({connection:l&&h!==void 0?s[h]:void 0,registeredConnection:a,route:t,requestUrl:e.requestUrl,returnTo:e.returnTo,transaction:e.transaction,userOwner:r,readiness:v===void 0?void 0:{...v,...L===void 0?{}:{connectUrl:L}}})),c}n(xr,"requirementsForSetup");function jd(e){return e.route.connection?.displayName??e.route.operationId}n(jd,"readRouteDisplayName");async function Ir(e){let t=$i(e.transaction.operationId),r=jd({route:t}),o=await R().readClient({clientId:e.transaction.clientId}),i=o.kind==="found"?o.client:void 0,a={gatewayOrigin:I(e.requestUrl),routeDisplayName:r,clientDisplayName:i?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},s=t.connection?.description;return s!==void 0&&(a.routeDescription=s),a}n(Ir,"consentContext");function Ar(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}n(Ar,"hasUnresolvedUserUpstream");var Nd=["mcp_user"],Gd="dev-browser-user",$d=["resource is required for /oauth/authorize.","MCP clients should start at the MCP server URL and follow its WWW-Authenticate resource_metadata link.","If your client reached this endpoint directly, use /oauth/authorize/{routePath} where {routePath} is the published MCP route path without a leading slash and each segment is URL-encoded as needed, for example /oauth/authorize/mcp/linear, or add resource={protected resource URI from protected-resource metadata}."].join(" "),Zd=d.object({response_type:d.literal("code"),client_id:d.string().min(1),redirect_uri:d.string().min(1),resource:d.url(),code_challenge:d.string().min(43),code_challenge_method:Cn,state:d.string().min(1).optional(),scope:d.literal(P).default(P)}),Fd=d.enum(["continue","approve","cancel"]).default("continue"),Kd=d.object({state:d.string().min(1),decision:Fd}),oe=class extends Error{static{n(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription}};function Zi(e){return typeof e=="string"&&e.length>0?e:void 0}n(Zi,"readQueryString");function Wd(e){let t=Array.from(j().byOperationId.values());if(t.length!==1)return;let r=t[0];if(r!==void 0)return Lt(r.operationId,e.url)}n(Wd,"inferSingleRouteResource");function Jd(e,t){let r=Zi(e.query.resource);if(t===void 0){if(r!==void 0)return r;let i=Wd(e);if(i!==void 0)return i;throw new p("invalid_target",$d)}let o=Lt(t,e.url);if(r===void 0||r===o)return o;throw new p("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}n(Jd,"requireAuthorizeResource");async function Vd(e,t){let r={};t!==void 0&&(r.context=t);let o=await xt(e,r);if(o.principal)return{principal:o.principal};if(!e.user)return o.evictCookie===void 0?{}:{setCookie:o.evictCookie};let i=si(e);return{principal:i,setCookie:await It({principal:i,requestUrl:e.url})}}n(Vd,"resolveBrowserPrincipal");async function Yd(e,t){let r={};t!==void 0&&(r.context=t);let o=await xt(e,r);if(!o.principal)throw g("authentication_required","Authorization setup requires a current browser session.");return o.principal}n(Yd,"requireSetupPrincipal");function Fi(e){return`/oauth/setup?state=${encodeURIComponent(e)}`}n(Fi,"buildSetupReturnTo");async function Ki(e){let t=await xr({transaction:e.transaction,requestUrl:e.requestUrl,returnTo:Fi(e.csrfToken)}),r=await Ir({transaction:e.transaction,requestUrl:e.requestUrl}),o={kind:"setup_page",html:Cr({state:e.csrfToken,operationId:e.transaction.operationId,upstreams:t,...r})};return e.setCookie!==void 0&&(o.setCookie=e.setCookie),o}n(Ki,"renderSetup");function Xd(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}n(Xd,"toAuthorizationTransactionClient");async function Ur(e,t={}){let r=Zd.parse({...e.query,resource:Jd(e,t.operationId),state:Zi(e.query.state)}),o=Ke(r.scope);Ie(r.redirect_uri,"invalid_request","authorize");let i=new Date,a=ee.parse(r.client_id),s=await Ut(r.client_id,i);Ui(s,r.redirect_uri);try{let c=Ae(e.url,r.resource),l=Xd(s);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:a,operationId:c.operationId,scope:o,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved"),t.context&&A(t.context,{eventType:x.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:c.operationId,attributes:{clientId:a,scope:o,responseType:r.response_type}});let h={clientId:s?.clientId??a,...l===void 0?{}:{client:l},redirectUri:r.redirect_uri,resource:r.resource,operationId:c.operationId,scope:o,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state}},{principal:m,setCookie:v}=await Vd(e,t.context);if(!m){let X=await Ci({transaction:h,requestUrl:e.url,now:i});t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:a,operationId:c.operationId},"Downstream OAuth authorize: redirecting to browser login (no session)");let Ye={kind:"redirect",location:X.browserLoginUrl};return v!==void 0&&(Ye.setCookie=v),Ye}let L=await Si({transaction:h,principal:m,now:i});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:a,operationId:c.operationId,subjectId:m.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),t.context&&A(t.context,{eventType:x.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:c.operationId,attributes:{clientId:a,scope:o,responseType:r.response_type,subjectId:m.subjectId}}),Ki({transaction:L.transaction,csrfToken:L.csrfToken,requestUrl:e.url,setCookie:v})}catch(c){throw Qd({redirectUri:r.redirect_uri,clientState:r.state,cause:c})}}n(Ur,"authorizeDownstreamClient");function Qd(e){if(e.cause instanceof oe)return e.cause;let t=eu(e.cause);return t?new oe({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}n(Qd,"toDownstreamAuthorizeRedirectError");function eu(e){if(e instanceof p)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof d.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}n(eu,"mapToOAuthRedirectError");async function Wi(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let h=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,m=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...h===void 0?{}:{idpErrorDescription:h},...m===void 0?{}:{idpErrorUri:m}},"Identity provider redirected browser-login callback with an error"),g("provider_access_denied",h??"The delegated browser login was not completed.")}let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),g("oauth_state_invalid","Browser login callback is missing state.");let i=await hr(o),a={request:e,stateId:i.stateId};t.context!==void 0&&(a.context=t.context);let s=await ci(a),c=await vi({browserLoginStateToken:o,principal:s}),l=await Ki({transaction:c.transaction,csrfToken:c.csrfToken,requestUrl:e.url});return l.setCookie=await It({principal:s,requestUrl:e.url}),l}n(Wi,"completeBrowserLoginCallback");async function Ji(e){let t=D(),r=new URL(e.url);if(!se(r))throw g("forbidden","Local browser login is only available on loopback HTTP origins.");let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw g("oauth_state_invalid","Local browser login is missing state.");let i=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:"/oauth/callback",I(e.url)),a=new URL(I(e.url)).origin;if(i.origin!==a||i.pathname!=="/oauth/callback")throw g("oauth_callback_mismatch","Local browser login redirect_uri must target this gateway's /oauth/callback route.");i.searchParams.set("state",o);let s={subjectId:st.parse(Gd),roles:Nd};return{kind:"redirect",location:i,setCookie:await It({principal:s,requestUrl:e.url})}}n(Ji,"completeLocalDevBrowserLogin");function tu(e){let t=e.method==="POST"?e.body:e.query;return Kd.parse(t)}n(tu,"readSetupContinueRequest");async function Vi(e){let{state:t,decision:r}=tu({method:e.request.method,query:e.request.query,body:e.body}),o=new Date,i=await wr({csrfToken:t,now:o}),a=await Yd(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await Ai({csrfToken:t,currentBrowserPrincipal:a,now:o})};let s=await xi({csrfToken:t,currentBrowserPrincipal:a,now:o}),c=await xr({transaction:s,requestUrl:e.request.url,returnTo:Fi(t)});if(r==="approve"&&Ar(c)&&await Ri({csrfToken:t,currentBrowserPrincipal:a,now:o}),Ar(c)){let l=await Ir({transaction:s,requestUrl:e.request.url});return{kind:"setup_page",html:Cr({state:t,operationId:s.operationId,upstreams:c,...l})}}return{kind:"redirect",location:await Ii({csrfToken:t,currentBrowserPrincipal:a,now:o})}}n(Vi,"continueDownstreamAuthorizeSetup");z();import{createLocalJWKSet as ru,decodeJwt as nu,errors as We,jwtVerify as ou}from"jose";var iu=new Set(["authorization_code","refresh_token"]),au="urn:ietf:params:oauth:client-assertion-type:jwt-bearer",su=1e4,cu=32*1024,du=2,Yi=d.object({client_id:d.string().min(1).optional(),client_secret:d.string().min(1).optional(),client_assertion_type:d.string().min(1).optional(),client_assertion:d.string().min(1).optional()}),uu=d.discriminatedUnion("grant_type",[Yi.extend({grant_type:d.literal("authorization_code"),code:d.string().min(1),redirect_uri:d.string().min(1),code_verifier:at,resource:d.url().optional(),scope:d.literal(P).optional()}),Yi.extend({grant_type:d.literal("refresh_token"),refresh_token:d.string().min(1),resource:d.url().optional(),scope:d.literal(P).optional()})]);function lu(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!iu.has(t)))throw new p("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}n(lu,"assertSupportedGrantType");var pu=d.object({token:d.string().min(1),client_id:d.string().min(1).optional(),token_type_hint:d.string().optional(),client_secret:d.string().min(1).optional(),client_assertion_type:d.string().min(1).optional(),client_assertion:d.string().min(1).optional()}),mu=d.object({keys:d.array(d.record(d.string(),d.unknown())).min(1)}).passthrough();function Xi(){return D().gateway.accessTokenTtlSeconds}n(Xi,"readAccessTokenTtlSeconds");function fu(){return D().gateway.refreshTokenTtlSeconds}n(fu,"readRefreshTokenTtlSeconds");function hu(e,t){let r=Xi(),o=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),i=Math.min(r,o);return{expiresAt:_(F(e,i)),expiresIn:i}}n(hu,"calculateAccessTokenExpiresAt");function Qi(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new p("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new p("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new p("invalid_client","Malformed HTTP Basic client authentication.")}}n(Qi,"readBasicClientSecret");function ea(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new p("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t!==void 0)return t;if(e.clientAssertion!==void 0){try{let r=nu(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new p("invalid_client","Malformed private_key_jwt client assertion.")}throw new p("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new p("invalid_client","Client authentication or client_id is required.")}n(ea,"resolveAuthenticatedClientId");function gu(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new p("invalid_request","Use only one client authentication method per request.");return e.basicClientSecret!==void 0?{clientSecret:e.basicClientSecret,clientSecretSource:"basic"}:e.bodyClientSecret!==void 0?{clientSecret:e.bodyClientSecret,clientSecretSource:"post"}:{}}n(gu,"resolveClientSecretInput");function yu(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}n(yu,"hasClientAssertion");function wu(e){if(e.requestUrl===void 0)throw new p("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(e.pathname,e.requestUrl);return t.search="",t.hash="",t.toString()}n(wu,"buildEndpointAudience");function _u(e){return e instanceof We.JWTExpired?"expired":e instanceof We.JWTClaimValidationFailed?"claim":e instanceof We.JWSSignatureVerificationFailed?"signature":e instanceof We.JWKSNoMatchingKey?"jwks_no_match":e instanceof We.JWTInvalid?"invalid":e instanceof d.ZodError?"schema":"other"}n(_u,"readJwtFailureKind");async function Ru(e){let{response:t,json:r}=await Kn(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:du,maxResponseBytes:cu,timeoutMs:su});if(!t.ok)throw new p("invalid_client","Client JWKS could not be fetched.");return mu.parse(r)}n(Ru,"fetchClientJwks");async function bu(e){if(e.clientAssertionType!==au||e.clientAssertion===void 0)throw new p("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=ee.parse(e.clientId),r=await Ut(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new p("invalid_client","Client is not registered for private_key_jwt authentication.");let o=r.metadata.jwks_uri;if(o===void 0)throw new p("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let i=wu({requestUrl:e.requestUrl,pathname:e.endpointPathname});try{let a=await Ru({jwksUri:o,context:e.context});await ou(e.clientAssertion,ru(a),{issuer:t,subject:t,audience:i,currentDate:e.now})}catch(a){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:_u(a)},"OAuth private_key_jwt client authentication failed"),new p("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}n(bu,"verifyPrivateKeyJwtClientAssertion");async function Cu(e){let t=ee.parse(e.clientId);return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await C(e.clientSecret)}}n(Cu,"buildRuntimeHttpClientAuth");async function ta(e){if(yu({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new p("invalid_request","Use only one client authentication method per request.");return bu(e)}let t=gu({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return Cu({clientId:e.clientId,...t})}n(ta,"resolveRuntimeHttpClientAuth");async function ra(e){lu(e.body);let t=uu.parse(e.body),r=Qi(e.authorizationHeader),o=ea({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),i=new Date,a=await ta({clientId:o,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,endpointPathname:"/oauth/token",now:i,context:e.context});return Su({parsed:t,clientId:o,clientAuth:a,now:i,requestUrl:e.requestUrl,context:e.context})}n(ra,"exchangeDownstreamToken");async function Su(e){if(e.parsed.grant_type==="authorization_code"){Ie(e.parsed.redirect_uri,"invalid_request","token"),Ke(e.parsed.scope),e.parsed.resource!==void 0&&Ae(e.requestUrl??e.parsed.resource,e.parsed.resource);let s=W(),c=W(),l=_(F(e.now,fu())),h=hu(e.now,l),m=await R().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await C(e.parsed.code),redirectUri:e.parsed.redirect_uri,...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},codeChallenge:await jn(e.parsed.code_verifier),currentRefreshTokenHash:await C(s),accessTokenHash:await C(c),grantExpiresAt:l,accessTokenExpiresAt:h.expiresAt,now:_(e.now)});if(m.kind==="invalid_client")throw new p("invalid_client","Client authentication failed.");if(m.kind==="resource_mismatch")throw new p("invalid_target","Token request resource must match the authorization code resource.");if(m.kind!=="exchanged")throw new p("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&A(e.context,{eventType:x.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:c,token_type:"Bearer",expires_in:h.expiresIn,refresh_token:s,scope:m.grant.scope,resource:m.grant.resource}}Ke(e.parsed.scope),e.parsed.resource!==void 0&&Ae(e.requestUrl??e.parsed.resource,e.parsed.resource);let t=W(),r=W(),o=_(F(e.now,Xi())),i=await R().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:await C(e.parsed.refresh_token),nextRefreshTokenHash:await C(t),accessTokenHash:await C(r),...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},accessTokenExpiresAt:o,now:_(e.now)});if(i.kind==="invalid_client")throw new p("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new p("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new p("invalid_grant","Refresh token is invalid, expired, or revoked.");Ae(e.requestUrl??i.grant.resource,i.grant.resource);let a=i.accessToken.expiresAt;return e.context&&(A(e.context,{eventType:x.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),A(e.context,{eventType:x.MCP_OAUTH_TOKEN_REFRESH_ROTATED,outcome:"success",attributes:{clientId:e.clientId}})),{access_token:r,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(a).getTime()-e.now.getTime())/1e3)),refresh_token:t,scope:i.grant.scope,resource:i.grant.resource}}n(Su,"exchangeDownstreamTokenWithRuntimeHttp");async function na(e){let t=pu.parse(e.body),r=Qi(e.authorizationHeader),o=ea({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),i=new Date;if((await R().revokeOAuthToken({clientAuth:await ta({clientId:o,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,endpointPathname:"/oauth/revoke",now:i,context:e.context}),tokenHash:await C(t.token),now:_(i)})).kind==="invalid_client")throw new p("invalid_client","Client authentication failed.");e.context?.log.info({event:"oauth_token_revoked",clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed"),e.context&&A(e.context,{eventType:x.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}n(na,"revokeDownstreamToken");var vu=64*1024,xu=16*1024,Iu="text/html; charset=utf-8";function Au(e){let t={};for(let[r,o]of e.entries())t[r]=o;return t}n(Au,"formDataToObject");async function Uu(e){return ni(e,{maxBytes:vu,label:"Request body"})}n(Uu,"readJsonBody");async function kr(e){return Au(await oi(e,{maxBytes:xu,label:"Request body"}))}n(kr,"readFormBody");async function oa(e,t,r){let o=ce(r),i=r instanceof d.ZodError?kt(r):void 0,a={code:o??(r instanceof d.ZodError?"invalid_request":"internal_server_error")};return i!==void 0&&(a.detail=i),Rn(e,t,a)}n(oa,"handleProblem");function Je(e){let t=new Headers(e.headers);t.set("cache-control","no-store"),t.set("pragma","no-cache");let r={error:e.error};return e.errorDescription!==void 0&&(r.error_description=e.errorDescription),Response.json(r,{status:e.status??400,headers:t})}n(Je,"oauthErrorResponse");function ku(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}n(ku,"readOAuthProtocolHeaders");function Pu(e,t){let r=H("internal_server_error");return Je({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:ku(e,t)})}n(Pu,"oauthProtocolErrorResponse");function ia(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}n(ia,"readZodOAuthErrorCode");function Tu(e){let t={error:ia(e)},r=kt(e);return r!==void 0&&(t.errorDescription=r),Je(t)}n(Tu,"oauthZodErrorResponse");function Ou(e){let t=ce(e);if(t===void 0)return;let r=H(t);if(r.oauthError===void 0)return;let o={error:r.oauthError,status:qu(r.oauthError)};return r.oauthError==="server_error"?o.errorDescription=r.publicDetail:e instanceof Error?o.errorDescription=e.message:o.errorDescription=r.publicDetail,Je(o)}n(Ou,"oauthGatewayProblemResponse");function Eu(){let t={error:"server_error",status:500,errorDescription:H("internal_server_error").publicDetail};return Je(t)}n(Eu,"oauthFallbackErrorResponse");function qu(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}n(qu,"readOAuthStatus");function Pr(e,t={}){return e instanceof oe?ca(e):e instanceof p?Pu(e,t):e instanceof d.ZodError?Tu(e):Ou(e)??Eu()}n(Pr,"oauthProblemResponse");function Tr(e,t){let r=xe(e.url);if(t instanceof oe)return ca(t);if(t instanceof p){let a=H("internal_server_error");return $({host:r,kind:Mu(t.errorCode),title:"Authorization failed",detail:t.errorCode==="server_error"?a.publicDetail:t.message,code:t.errorCode,status:t.status})}if(t instanceof d.ZodError)return $({host:r,kind:"invalid_request",detail:kt(t)??"The authorization request was invalid.",code:ia(t)});let o=ce(t);if(o!==void 0){let a=H(o);return $({host:r,kind:sa(o),detail:a.status<500&&t instanceof Error?t.message:a.publicDetail,code:a.oauthError??o,status:a.status})}let i=H("internal_server_error");return $({host:r,kind:"internal_error",detail:i.publicDetail,code:"server_error",status:i.status})}n(Tr,"browserOAuthProblemResponse");function aa(e,t){let r=xe(e.url),o=ce(t);if(o!==void 0){let a=H(o);return $({host:r,kind:sa(o),detail:a.status<500&&t instanceof Error?t.message:a.publicDetail,code:o,status:a.status})}if(t instanceof d.ZodError)return $({host:r,kind:"invalid_request",detail:kt(t)??"The authorization request was invalid.",code:"invalid_request"});let i=H("internal_server_error");return $({host:r,kind:"internal_error",detail:i.publicDetail,code:"internal_server_error",status:i.status})}n(aa,"browserGatewayProblemResponse");function Mu(e){return e==="server_error"?"internal_error":"invalid_request"}n(Mu,"readOAuthBrowserErrorKind");function sa(e){if(H(e).status>=500)return"internal_error";switch(e){case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"configuration_error";case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"upstream_client_registration_required":return"admin_required";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"invalid_request":case"authentication_required":case"forbidden":case"not_found":case"too_many_requests":case"identity_context_missing":return"invalid_request";case"upstream_capability_invocation_failed":case"upstream_capability_unavailable":case"upstream_import_failed":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}n(sa,"readGatewayBrowserErrorKind");function Y(e,t,r){let o={event:t},i=!1;if(r instanceof p)o.oauthError=r.errorCode,o.status=r.status,K(o,"error",r);else if(r instanceof oe)o.oauthError=r.errorCode,K(o,"error",r);else if(r instanceof d.ZodError){o.code="invalid_request",K(o,"error",r);let a=r.issues[0];a&&(o.zodPath=a.path.join("."))}else{let a=ce(r);if(a!==void 0){let s=H(a);o.code=a,o.status=s.status,s.oauthError!==void 0&&(o.oauthError=s.oauthError),i=s.status>=500||s.oauthError==="server_error",K(o,"error",r)}else i=!0,K(o,"error",r)}if(i){let a=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(o,a.message)}else e.log.warn(o,"OAuth handler rejected the request")}n(Y,"logUnexpectedOAuthHandlerError");function ca(e){let t;try{t=new URL(e.redirectUri)}catch{return Je({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}n(ca,"downstreamAuthorizeRedirectErrorResponse");function kt(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}n(kt,"formatZodErrorDetail");function zu(e,t){let r={event:"browser_login_callback_failed",code:ce(t)??"invalid_request"};K(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}n(zu,"logBrowserLoginCallbackFailure");function da(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(null,{status:302,headers:t})}n(da,"redirectResultResponse");function Pt(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":Iu,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(e.html,{status:200,headers:t})}return da(e)}n(Pt,"authorizeResultResponse");async function ua(e,t){try{return Response.json(Un(e.url))}catch(r){return Y(t,"oauth_authorization_server_metadata_failed",r),oa(e,t,r)}}n(ua,"authorizationServerMetadataHandler");async function la(e,t){try{let r=jt(e.params.routePath);return Response.json(kn({operationId:r.operationId,requestUrl:e.url}))}catch(r){return Y(t,"oauth_authorization_server_metadata_failed",r),oa(e,t,r)}}n(la,"scopedAuthorizationServerMetadataHandler");async function pa(e,t){try{let r=await Pi(await Uu(e)),o=r,i=typeof o.client_id=="string"?o.client_id:void 0,a=typeof o.client_name=="string"?o.client_name:void 0,s=Array.isArray(o.redirect_uris)?o.redirect_uris.length:void 0,c=typeof o.token_endpoint_auth_method=="string"?o.token_endpoint_auth_method:void 0;return t.log.info({event:"oauth_dcr_client_registered",clientId:i,clientName:a,redirectUriCount:s,tokenEndpointAuthMethod:c},"OAuth Dynamic Client Registration completed"),A(t,{eventType:x.MCP_OAUTH_CLIENT_REGISTERED,outcome:"success",clientName:a,attributes:{clientId:i,redirectUriCount:s,tokenEndpointAuthMethod:c}}),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return Y(t,"oauth_register_failed",r),Pr(r)}}n(pa,"registerHandler");async function ma(e,t){try{return Pt(await Ur(e,{context:t}))}catch(r){return Y(t,"oauth_authorize_failed",r),Tr(e,r)}}n(ma,"authorizeHandler");async function fa(e,t){try{let r=jt(e.params.routePath);return Pt(await Ur(e,{operationId:r.operationId,context:t}))}catch(r){return Y(t,"oauth_authorize_scoped_failed",r),Tr(e,r)}}n(fa,"scopedAuthorizeHandler");async function ha(e,t){try{let r=await Wi(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),Pt(r)}catch(r){return zu(t,r),aa(e,r)}}n(ha,"callbackHandler");async function ga(e,t){try{return da(await Ji(e))}catch(r){return Y(t,"oauth_dev_login_failed",r),Tr(e,r)}}n(ga,"devLoginHandler");async function ya(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await Vi({request:e,body:e.method==="POST"?await kr(e):void 0,context:t});return Pt(r)}catch(r){return Y(t,"oauth_setup_failed",r),aa(e,r)}}n(ya,"setupHandler");async function wa(e,t){try{return Response.json(await ra({body:await kr(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return Y(t,"oauth_token_failed",r),Pr(r)}}n(wa,"tokenHandler");async function _a(e,t){try{return await na({body:await kr(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return Y(t,"oauth_revoke_failed",r),Pr(r)}}n(_a,"revokeHandler");var Du={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},Ra=new Nr("upstream-request");function Hu(e){let t=Ra.get(e);if(!t)throw new E("Upstream request context has not been set");return t}n(Hu,"readUpstreamRequestContext");function Bu(e,t){return t.some(r=>r===e)}n(Bu,"requestContextMatchesKind");function Lu(e){return typeof e=="string"?[e]:e}n(Lu,"toExpectedKinds");function Ue(e,t){Ra.set(e,t)}n(Ue,"setUpstreamRequestContext");function Ve(e,t){let r=Hu(e),o=Lu(t);if(!Bu(r.kind,o)){let i=Du[o[0]];throw new E(`${i} request context has not been set`)}return r}n(Ve,"requireUpstreamRequestContext");function ba(e){return b`<p data-gateway-error-code="${e.code}">${e.body}</p>`}n(ba,"renderBrowserResult");var ju="text/html; charset=utf-8",Nu="none";function Gu(e){let t=Ct(e.host);return ve({title:e.title,iconHref:t,styles:Se,headerIcon:St({iconHref:t,fallbackIconHref:bt}),heading:e.title,subhead:"",body:ba({body:e.body,code:e.code??Nu}),footer:""})}n(Gu,"browserResultHtml");function $u(e,t=200){return new Response(Ce(e),{status:t,headers:{"content-type":ju,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n($u,"browserResultResponse");function Ca(e){return $u(Gu(e))}n(Ca,"browserConnectionSuccessResponse");function Tt(e,t){let r=_n(t);return $({host:e,kind:Zu(t),detail:r.body,code:t})}n(Tt,"browserConnectionFailureResponse");function Zu(e){switch(e){case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed"}}n(Zu,"readCallbackFailureBrowserErrorKind");var Fu=["callback_authorization_code","callback_provider_error","callback_invalid"];function Ku(e){return"cause"in e?e.cause:void 0}n(Ku,"readErrorCause");function Wu(e){return e.stack?.split(`
28
- `).slice(1,4).map(t=>t.trim()).join(" | ")}n(Wu,"readFirstStackFrame");function Sa(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=Wu(r))}n(Sa,"addErrorAttributes");function Or(e){if(!(e instanceof y))return;let t=e.extensionMembers?.[w];return rn(t)?t:void 0}n(Or,"readRuntimeGatewayCode");function Ju(e,t,r){switch(t.kind){case"callback_provider_error":return e.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:t.upstreamServerId,providerError:t.error,...t.errorDescription===void 0?{}:{providerErrorDescription:t.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),A(e,{eventType:x.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:t.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:t.error,errorDescription:t.errorDescription}}),Tt(r,"provider_access_denied");case"callback_invalid":return e.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:t.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),Tt(r,"oauth_state_invalid");case"callback_authorization_code":return t}}n(Ju,"requireAuthorizationCallbackRequest");function Vu(e,t){A(e,{eventType:x.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}n(Vu,"emitCallbackReceivedAnalyticsEvent");function Yu(e,t){A(e,{eventType:x.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}n(Yu,"emitTokenExchangeSucceededAnalyticsEvent");function Xu(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return Ca({host:xe(e.url),title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}n(Xu,"buildSuccessfulCallbackResponse");function Qu(e){let t={detail:e instanceof Error?e.message:void 0};return Sa(t,"error",e),e instanceof Error&&Sa(t,"cause",Ku(e)),t}n(Qu,"buildTokenExchangeFailureAttributes");function el(e){A(e.context,{eventType:x.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:Or(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:Qu(e.error)})}n(el,"emitTokenExchangeFailedAnalyticsEvent");function tl(e,t){let r=Or(t);return Tt(e,nn(r)?r:"upstream_token_exchange_failed")}n(tl,"tokenExchangeFailureResponse");async function Er(e,t){let r=Ve(t,Fu),o=xe(e.url),i=Ju(t,r,o);if(i instanceof Response)return i;Vu(t,i);try{let a=await Ko({request:e,callbackRequest:i});return Yu(t,a),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:a.upstreamServerId,operationId:a.operationId,authProfileId:a.authProfileId,ownerMode:a.ownerMode},"Upstream OAuth token exchange completed; user connection established"),Xu(e,a)}catch(a){let s={event:"upstream_oauth_token_exchange_failed",code:Or(a)??"upstream_token_exchange_failed",upstreamServerId:i.upstreamServerId};return K(s,"error",a),t.log.warn(s,"Upstream OAuth token exchange failed; user shown connection-failure page"),el({context:t,callbackRequest:i,error:a}),tl(o,a)}}n(Er,"callbackHandler");function rl(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}n(rl,"clientMetadataProblemDetail");async function va(e,t){let r=Ve(t,"connect"),o=await Fo({request:e,connectRequest:r});if(A(t,{eventType:x.MCP_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:o.operationId,upstreamServerTitle:o.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:o.authProfileId,operationId:o.operationId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),r.redirect)return Response.redirect(o.authUrl,302);let i=await wt({requestUrl:e.url,owner:o.owner,initiatedBySubjectId:o.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:o.authProfileId,upstreamDisplayName:o.upstreamDisplayName,operationId:o.operationId,subject:"MCP route",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(i,{status:428})}n(va,"connectHandler");async function xa(e,t){let r=Ve(t,"client_metadata");try{let o=To(e.url),i=Oo(o,r.upstreamServerId,r.authProfileId);return Response.json(i)}catch(o){if(!(o instanceof k))throw o;let i=o instanceof Error?o.message:String(o);return t.log.warn({event:"oauth_client_metadata_request_failed",upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:i},"Failed to serve OAuth client metadata document for upstream connection"),ae.notFound(e,t,{code:"not_found",detail:rl(o)})}}n(xa,"oauthClientMetadataHandler");function ie(e){if(typeof e=="string"&&e.length!==0)return e}n(ie,"readOptionalQueryString");function nl(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new E(`Validated path parameter ${t} is missing`);return r}n(nl,"requirePathString");function ol(e){let t=ie(e);return t?rt.parse(t):void 0}n(ol,"readOptionalOperationId");function il(e,t){let r=ie(e);return r?sn.parse(r):it(t,"user-oauth")}n(il,"readOptionalAuthProfileId");function al(e){let t=ol(e);if(!t)throw new y({message:"operationId query parameter is required.",extensionMembers:{[w]:"invalid_request"}});return t}n(al,"readRequiredOperationId");function sl(e){let t=On(ie(e));return t===void 0?{}:{returnTo:t}}n(sl,"readOptionalReturnTo");function cl(e){let t=ie(e.query.error_description);return t===void 0?{}:{errorDescription:t}}n(cl,"readOptionalProviderErrorDescription");function dl(e){let t=N(e.authMode);if(t.connectSupport!=="none")return e;throw new y({message:t.connectUnsupportedDetail??"This upstream does not support browser connection flows.",extensionMembers:{[w]:"invalid_request"}})}n(dl,"requireConnectableRouteAuth");function ul(e,t,r,o){return{kind:"connect",...be(e,t),...o===void 0?{}:{returnTo:o},redirect:r}}n(ul,"buildConnectContextForPrincipal");function ll(e,t,r){let o=ut(t),i=N(e.authMode);if(o.mode!==i.ownerMode)throw new y({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[w]:"oauth_callback_mismatch"}});return{kind:"connect",...e,...t.returnTo===void 0?{}:{returnTo:t.returnTo},owner:o,initiatedBySubjectId:t.initiatedBySubjectId,redirect:r}}n(ll,"buildConnectContextForTicket");async function pl(e,t){let r=dl(Rt(t,al(e.query.operationId))),o=e.query.redirect==="true",i=ie(e.query.browserTicket);if(e.user){if(i)throw new y({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[w]:"invalid_request"}});let s=ct(e.user,e.url);return ul(r,s,o,sl(e.query.returnTo).returnTo)}if(!i)throw new y({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[w]:"authentication_required"}});let a=await Ao(i);if(a.ownerMode!==r.ownerMode||a.upstreamServerId!==r.upstreamServerId||a.authProfileId!==r.authProfileId||a.operationId!==r.operationId)throw new y({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[w]:"oauth_callback_mismatch"}});return await Uo(a),ll(r,a,o)}n(pl,"resolveConnectContext");async function ml(e,t,r){let o=an.parse(nl(e,"connection"));switch(r){case"connect":Ue(t,await pl(e,o));return;case"callback":{let i=ie(e.query.error);if(i){Ue(t,{kind:"callback_provider_error",upstreamServerId:o,error:i,...cl(e)});return}let a=ie(e.query.code),s=ie(e.query.state);if(a&&s){Ue(t,{kind:"callback_authorization_code",upstreamServerId:o,code:a,state:s});return}Ue(t,{kind:"callback_invalid",upstreamServerId:o});return}case"client_metadata":Ue(t,{kind:"client_metadata",upstreamServerId:o,authProfileId:il(e.query.authProfileId,o)});return}}n(ml,"resolveUpstreamRequestInbound");async function fl(e,t,r){try{await ml(e,t,r);return}catch(o){let i=o instanceof y?o.extensionMembers?.[w]:void 0,a=o instanceof Error?o.message:void 0;switch(i){case"invalid_request":case"oauth_callback_mismatch":return ae.badRequest(e,t,{code:i,detail:a});case"authentication_required":return ae.unauthorized(e,t,{code:i,detail:a});default:throw o}}}n(fl,"applyUpstreamRequestContext");function Ot(e,t){return n(async(o,i)=>{let a=await fl(o,i,e);return a||t(o,i)},"wrapped")}n(Ot,"withUpstreamRequestContext");var hl={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function gl(){return new Response(null,{status:204,headers:hl})}n(gl,"buildWellKnownPreflightResponse");function yl(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}n(yl,"withWellKnownCorsHeaders");function qr(e){return async(t,r)=>t.method==="OPTIONS"?gl():yl(await e(t,r))}n(qr,"wrapWellKnownHandler");var Ua=[{routeName:"oauth_as_metadata",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:qr(ua),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:qr(la),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:qr(Pn),corsPolicy:"anything-goes"},{routeName:"oauth_register",path:"/oauth/register",methods:["POST"],handler:pa},{routeName:"oauth_authorize",path:"/oauth/authorize",methods:["GET"],handler:ma},{routeName:"oauth_authorize_scoped",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:fa},{routeName:"oauth_callback",path:"/oauth/callback",methods:["GET"],handler:ha},{routeName:"oauth_dev_login",path:"/oauth/dev-login",methods:["GET"],handler:ga},{routeName:"oauth_setup",path:"/oauth/setup",methods:["GET","POST"],handler:ya},{routeName:"oauth_token",path:"/oauth/token",methods:["POST"],handler:wa},{routeName:"oauth_revoke",path:"/oauth/revoke",methods:["POST"],handler:_a},{routeName:"upstream_client_metadata",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:Ot("client_metadata",xa)},{routeName:"upstream_connect",path:"/auth/connections/:connection/connect",methods:["GET"],handler:Ot("connect",va)},{routeName:"upstream_callback",path:"/auth/connections/:connection/callback",methods:["GET"],handler:Ot("callback",Er)}],wl=Ua.filter(e=>!e.routeName.startsWith("upstream_")),_l=Ua.filter(e=>e.routeName.startsWith("upstream_"));function ka(e){return e?.some(en)??!1}n(ka,"hasMcpOAuthRuntimeConfigPolicy");function Pa(e){return e?.some(t=>mn(t.policyType))??!1}n(Pa,"hasMcpTokenExchangePolicy");function Ta(e){return ka(e)||Pa(e)}n(Ta,"shouldRegisterMcpGatewayInternalRoutes");function Rl(e){gn(fn({routes:e.routes,policies:e.policies}))}n(Rl,"initializeMcpGatewayConnectionRegistry");function bl(e){let t=tn(e.policies);if(!t){let r=[...Qr].map(o=>`\`${o}\``).join(", ");throw new k(`MCP gateway: could not find an MCP authorization policy in policies.json. Add one of [${r}] and reference it on your MCP routes.`)}return t.config}n(bl,"initializeMcpGatewayOAuthRuntimeConfig");function Ia(e,t,r){return async(o,i)=>{r&&Yr(i,r());let a=o.method==="OPTIONS",s=Date.now();a||i.log.info({event:`${e}_received`,method:o.method},`MCP gateway: ${e} received`);let c=await t(o,i);return a||i.log.info({event:`${e}_responded`,status:c.status,durationMs:Date.now()-s},`MCP gateway: ${e} responded`),c}}n(Ia,"wrapInternalHandler");function Aa(e,t,r){e.addPluginRoute({path:t.path,methods:t.methods,handler:r,processors:[jr],corsPolicy:t.corsPolicy??"none"})}n(Aa,"addInternalRoute");function Oa(e,t){Rl(t);let r=ka(t.policies),o=Pa(t.policies),i,a=n(()=>(i===void 0&&(i=bl(t)),i),"readOAuthConfig");if(r)for(let s of wl)Aa(e,s,Ia(s.routeName,s.handler,a));if(o)for(let s of _l)Aa(e,s,Ia(s.routeName,s.handler))}n(Oa,"registerMcpGatewayInternalRoutes");function Ea(e){hn(e)}n(Ea,"configureLazyMcpGatewayState");var Mr=class extends Br{static{n(this,"McpGatewayPlugin")}registerRoutes(t){let r=t.parsedRouteData;if(!r||!Ta(r.policies))return;let o={routes:r.routes,policies:r.policies};Ea(o),Oa(t.router,o)}};var Cl={Allow:"POST"};async function Sl(e,t){return e.method==="GET"?ae.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},Cl):Jr(e,t)}n(Sl,"McpProxyHandler");export{Ha as McpAuth0OAuthInboundPolicy,Gt as McpCapabilityFilterInboundPolicy,Mr as McpGatewayPlugin,Da as McpOAuthInboundPolicy,Sl as McpProxyHandler,ur as McpTokenExchangeInboundPolicy};
27
+ </style></head><body><main class="card"><header class="card__head">${e.headerIcon}<h1 class="card__title">${e.heading}</h1>${e.subhead}</header><div class="card__body">${e.body}</div>${e.footer}</main></body></html>`}n(xe,"renderShell");var hr="zuplo.com";function di(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(di,"s2FaviconHref");function td(e){return`https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&drop_404_icon=true&fallback_opts=TYPE,SIZE,URL&url=http://${e}&size=128`}n(td,"strictFaviconHref");var St=di(hr);function vt(e){let t=e.toLowerCase();return t===hr||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?di(hr):td(e)}n(vt,"resolveIconHref");function xt(e){return S`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}n(xt,"renderShellIcon");var rd="text/html; charset=utf-8";function Ae(e){try{return new URL(e).host}catch{return""}}n(Ae,"safeHostFromUrl");function $(e){let t=vt(e.host),r=nd(e.kind??"authorization_failed");return new Response(Se(xe({title:e.title??r.title,iconHref:t,styles:ve,headerIcon:xt({iconHref:t,fallbackIconHref:St}),heading:e.title??r.title,subhead:"",body:ci({code:e.code??"unknown",detail:e.detail,guidance:S`<p class="card__description">${r.guidance}</p>`,action:od(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":rd,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n($,"browserErrorPageResponse");function nd(e){switch(e){case"session_expired":return{title:"Authorization expired",guidance:"Return to your MCP client and reconnect. Expired authorization requests cannot be resumed."};case"access_denied":return{title:"Authorization canceled",guidance:"Return to your MCP client to retry if you want to grant access."};case"configuration_error":return{title:"Configuration needs attention",guidance:"Contact your workspace admin with this error code. The gateway or upstream configuration must be fixed before retrying."};case"connection_failed":return{title:"Connection failed",guidance:"Return to your MCP client and reconnect this upstream. If this keeps happening, contact your gateway administrator with this error code."};case"invalid_request":return{title:"Authorization request invalid",guidance:"Return to your MCP client and try connecting again. If this keeps happening, the client request may need to be fixed."};case"admin_required":return{title:"Admin setup required",guidance:"Contact your workspace admin with this error code. This connection cannot be completed until setup is finished."};case"internal_error":return{title:"Gateway error",guidance:"Try again later from your MCP client. If this keeps happening, contact your gateway administrator with this error code."};case"authorization_failed":return{title:"Authorization failed",guidance:"Return to your MCP client and start authorization again. If this keeps happening, contact your gateway administrator with this error code."}}}n(nd,"readBrowserErrorPagePresentation");function od(e){return e===void 0?ge:S`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(od,"renderAction");var ui="application/json",id="application/x-www-form-urlencoded";function At(e,t){return new y({message:e,extensionMembers:{[w]:"invalid_request"}},t===void 0?void 0:{cause:t})}n(At,"invalidRequestError");function ad(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}n(ad,"normalizeContentType");function sd(e,t){return e===t?!0:t===ui&&e.endsWith("+json")}n(sd,"contentTypeMatches");function cd(e,t){if(!t||t.length===0)return;let r=ad(e.headers.get("content-type"));if(!t.some(o=>sd(r,o)))throw At(`Request body must be ${t.join(" or ")}.`)}n(cd,"assertExpectedContentType");function dd(e,t,r){let o=e.headers.get("content-length");if(!o)return;let i=Number.parseInt(o,10);if(Number.isFinite(i)&&i>t)throw At(`${r} exceeded the maximum allowed size.`)}n(dd,"assertContentLengthWithinLimit");async function li(e,t){let r=t.label??"Request body";cd(e,t.expectedContentTypes),dd(e,t.maxBytes,r);let o=await Wn(e.body,{maxBytes:t.maxBytes,createLimitError:n(()=>At(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(o)}n(li,"readBoundedTextBody");async function pi(e,t){let r=await li(e,{...t,expectedContentTypes:[ui]});try{return JSON.parse(r)}catch(o){throw At("Request body must be valid JSON.",o)}}n(pi,"readBoundedJsonBody");async function mi(e,t){let r=await li(e,{...t,expectedContentTypes:[id]});return new URLSearchParams(r)}n(mi,"readBoundedFormUrlEncodedBody");z();z();import{errors as _i,jwtVerify as Ri,SignJWT as Ci}from"jose";z();import{errors as ud,jwtVerify as ld,SignJWT as pd}from"jose";var yr="zuplo_mcp_session",md=d.object({purpose:d.literal("gateway_browser_session"),sub:dt,browserLoginOrigin:d.string().min(1),roles:d.array(d.string().min(1)).optional(),exp:d.number().int().positive(),iat:d.number().int().positive().optional()});function fd(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let o=r.indexOf("=");if(o<0)continue;let i=r.slice(0,o).trim(),a=r.slice(o+1).trim();if(i)try{t.set(i,decodeURIComponent(a))}catch{t.set(i,a)}}return t}n(fd,"parseCookieHeader");async function fi(){return G({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>ne(e,"browser-session"),"derive")})}n(fi,"getBrowserSessionKey");function gr(e){let t=new URL(I(e)),r=[`${yr}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(gr,"buildBrowserSessionEvictionCookie");function hd(e){let t=new URL(I(e.requestUrl)),r=[`${yr}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(hd,"serializeSessionCookie");function hi(){return new URL(mt("url")).origin}n(hi,"readBrowserLoginOrigin");function wr(){return D().browserLogin.stateTtlSeconds}n(wr,"readBrowserLoginStateTtlSeconds");function gi(e){if(!e.user)throw g("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return ut(e.user,e.url)}n(gi,"resolveCurrentRequestPrincipal");async function It(e,t={}){let r=fd(e.headers.get("cookie")).get(yr);if(!r)return{};try{let{payload:o}=await ld(r,await fi(),{algorithms:[M],issuer:T,audience:q}),i=md.parse(o);if(i.browserLoginOrigin!==hi())return{evictCookie:gr(e.url)};let a={subjectId:i.sub};return i.roles&&i.roles.length>0&&(a.roles=i.roles),{principal:a}}catch(o){return o instanceof ud.JWTExpired?{evictCookie:gr(e.url)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:o instanceof Error?o.name:"unknown",errorMessage:o instanceof Error?o.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:gr(e.url)})}}n(It,"readBrowserSession");async function Ut(e){let t=D().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:hi()};e.principal.roles&&(r.roles=e.principal.roles);let o=await new pd(r).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await fi());return hd({value:o,requestUrl:e.requestUrl,ttlSeconds:t})}n(Ut,"createBrowserSessionCookie");async function yi(e){let t={};e.context!==void 0&&(t.context=e.context);let r=await It(e.request,t);if(r.principal)return r.principal;let o=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(!o)throw g("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.");let{exchangeFederatedAuthorizationCode:i}=await import("../browser-login-idp-SD2N5PY4.js");return i({code:o,nonce:e.stateId,requestUrl:e.request.url,...e.context===void 0?{}:{context:e.context}})}n(yi,"resolveBrowserLoginCallbackPrincipal");function wi(e){let t=D().browserLogin,r=new URL(mt("url")),o=new URL("/oauth/callback",Sn(e.requestUrl));return On(r)?(r.searchParams.set("redirect_uri",o.toString()),r.searchParams.set("state",e.state),r):(r.searchParams.set("response_type","code"),r.searchParams.set("client_id",mt("clientId")),r.searchParams.set("redirect_uri",o.toString()),r.searchParams.set("scope",t.scope),r.searchParams.set("state",e.state),r.searchParams.set("nonce",e.nonce),t.audience&&r.searchParams.set("audience",t.audience),r)}n(wi,"buildBrowserLoginUrl");var gd={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},p=class extends Error{static{n(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,o=gd[t],i){super(r,i),this.name="OAuthProtocolError",this.errorCode=t,this.status=o}};var yd=5*60,wd=d.object({purpose:d.literal("gateway_browser_login"),transactionId:Dt,stateId:Bt,exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),_d=d.object({purpose:d.literal("gateway_authorization_setup"),transactionId:Dt,stateId:Bt,exp:d.number().int().positive(),iat:d.number().int().positive().optional()});async function bi(){return G({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>ne(e,"browser-login"),"derive")})}n(bi,"getBrowserLoginKey");async function Si(){return G({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>ne(e,"authorization-csrf"),"derive")})}n(Si,"getCsrfKey");function vi(e){return{now:e.now??new Date,ttlSeconds:wr()}}n(vi,"readPendingTransactionDependencies");function Rd(e,t){return e.subjectId===t.subjectId}n(Rd,"principalsMatch");function xi(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}n(xi,"toPendingPrincipal");function Ai(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,operationId:e.transaction.operationId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:R(e.now),expiresAt:R(F(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw g("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:xi(e.principal)}}n(Ai,"createTransactionRecord");async function Ii(e){let{id:t,...r}=e.record,o=await C().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(o.kind){case"started":return o.transaction;case"already_exists":throw g("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new p("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new p("invalid_request","redirect_uri is not registered for the client.")}}n(Ii,"startPendingTransaction");async function Cd(e){return new Ci({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await bi())}n(Cd,"signBrowserLoginState");async function Ui(e){return new Ci({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:Lt()}).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await Si())}n(Ui,"signCsrfToken");async function _r(e){try{let{payload:t}=await Ri(e,await bi(),{algorithms:[M],issuer:T,audience:q}),r=wd.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof _i.JWTExpired?g("oauth_state_expired","Browser login state has expired.",t):g("oauth_state_invalid","Browser login state could not be verified.",t)}}n(_r,"verifyBrowserLoginStateToken");async function kt(e){try{let{payload:t}=await Ri(e,await Si(),{algorithms:[M],issuer:T,audience:q});return{transactionId:_d.parse(t).transactionId}}catch(t){throw t instanceof _i.JWTExpired?g("oauth_state_expired","Authorization setup state has expired.",t):g("oauth_state_invalid","Authorization setup state could not be verified.",t)}}n(kt,"verifyCsrfToken");function Rr(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}n(Rr,"pendingStateErrorCode");function bd(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}n(bd,"toPendingAuthorizationGetResult");function Sd(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}n(Sd,"toPendingAuthorizationAdvanceResult");function Cr(e){return e==="principal_mismatch"?"oauth_callback_mismatch":Rr(e==="consumed_already"?"consumed_already":e)}n(Cr,"setupDecisionErrorCode");async function ki(e){let t=e.now??new Date,r=await kt(e.csrfToken),o=await C().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await v(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:R(t)});if(o.kind!=="marked")throw g(Cr(o.kind),"Authorization setup state is invalid, expired, or already used.");return Pi({kind:"available",record:o.transaction})}n(ki,"markSetupApproved");function Pi(e){if(e.kind!=="available")throw g(Rr(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}n(Pi,"requireAwaitingSetup");function vd(e){if(!Rd(e.currentBrowserPrincipal,e.transaction.principal))throw g("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}n(vd,"requireCurrentPrincipalMatches");async function Ti(e){let t=e.now??new Date,r=wr(),o=Ht(),i=Lt(),a=await Cd({transactionId:o,stateId:i,ttlSeconds:r}),s=Ai({id:o,transaction:e.transaction,currentStateHash:await v(a),phase:"awaiting_login",now:t,ttlSeconds:r});if(s.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");let c=await Ii({record:s,client:e.transaction.client});if(c.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");return{transaction:c,browserLoginStateToken:a,browserLoginUrl:wi({state:a,nonce:i,operationId:s.operationId,requestUrl:e.requestUrl})}}n(Ti,"startAwaitingLogin");async function Oi(e){let{now:t,ttlSeconds:r}=vi(e),o=Ht(),i=await Ui({transactionId:o,ttlSeconds:r}),a=Ai({id:o,transaction:e.transaction,currentStateHash:await v(i),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(a.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");let s=await Ii({record:a,client:e.transaction.client});if(s.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:s,csrfToken:i}}n(Oi,"startAwaitingSetup");async function Ei(e){let{now:t,ttlSeconds:r}=vi(e),o=await _r(e.browserLoginStateToken),i=await Ui({transactionId:o.transactionId,ttlSeconds:r}),a=Sd(await C().advancePendingAuthorization({transactionId:o.transactionId,expectedPhase:"awaiting_login",currentStateHash:await v(e.browserLoginStateToken),nextStateHash:await v(i),nextPhase:"awaiting_setup",principal:xi(e.principal),now:R(t)}));if(a.kind!=="advanced")throw g(Rr(a.kind),"Browser login state is invalid, expired, or already used.");if(a.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:a.record,csrfToken:i}}n(Ei,"completeLogin");async function qi(e){let t=await br(e);return vd({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}n(qi,"getSetup");async function br(e){let t=e.now??new Date,r=await kt(e.csrfToken);return Pi(bd(await C().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await v(e.csrfToken),now:R(t)})))}n(br,"getSetupTransaction");async function xd(e){let t=await kt(e.csrfToken),r=J(),o=R(F(e.now,yd)),i=await C().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await v(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await v(r),authorizationCodeExpiresAt:o,grantId:Pn(),now:R(e.now)});if(i.kind!=="approved")throw g(i.kind==="cancelled"?"oauth_state_invalid":Cr(i.kind),"Authorization setup state is invalid, expired, or already used.");let a=new URL(i.transaction.redirectUri);return a.searchParams.set("code",r),i.transaction.clientState&&a.searchParams.set("state",i.transaction.clientState),a}n(xd,"createAuthorizationCodeRedirectWithDecision");async function Ad(e){let t=await kt(e.csrfToken),r=await C().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await v(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:R(e.now)});if(r.kind!=="cancelled")throw g(r.kind==="approved"?"oauth_state_invalid":Cr(r.kind),"Authorization setup state is invalid, expired, or already used.");return Id({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}n(Ad,"createCancelRedirectWithDecision");function Id(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),t}n(Id,"buildClientCancelRedirect");async function Mi(e){let t=e.now??new Date;return xd({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Mi,"approve");async function zi(e){let t=e.now??new Date;return Ad({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(zi,"cancel");z();var Ud=1e4,kd=5*1024,Pd=2,Td=90*24*60*60,Sr=["authorization_code","refresh_token"],vr=["code"],Od=d.object({client_name:d.string().min(1).optional(),redirect_uris:d.array(d.string().min(1)).min(1),grant_types:d.array(d.enum(Sr)).min(1).max(2).optional(),response_types:d.array(d.enum(vr)).min(1).max(1).optional(),scope:d.literal(P).optional(),token_endpoint_auth_method:Un.default("none")});function Ed(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&ce(t))&&t.pathname!=="/"}catch{return!1}}n(Ed,"isCimdClientIdCandidate");function Ie(e,t="invalid_request",r="authorize"){if(qd(e))throw new p(t,"redirect_uris must not include raw whitespace or control characters.");let o;try{o=new URL(e)}catch{throw new p(t,"redirect_uris must be absolute URIs.")}if(o.hash||o.username||o.password)throw new p(t,"redirect_uris must not include credentials or fragments.");let i={source:r},a=An({url:o,context:i});if(a.kind!=="rejected"){a.mode!=="strict"&&void 0;return}throw new p(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}n(Ie,"assertValidRedirectUri");function qd(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}n(qd,"hasForbiddenRawRedirectUriCharacter");async function Md(e){let{response:t,json:r}=await Yn(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:Pd,maxResponseBytes:kd,timeoutMs:Ud});if(!t.ok)throw g("invalid_request","CIMD metadata could not be fetched.");let o=kn.parse(r);for(let i of o.redirect_uris)Ie(i,"invalid_request","cimd");if(o.client_id!==e.clientId)throw g("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return o}n(Md,"fetchCimdMetadata");async function zd(e){let t=Jn(e),r=await Md({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}n(zd,"resolveCimdClient");async function Pt(e,t){let r=te.parse(e);if(Ed(r)){if(!D().gateway.cimdEnabled)throw new p("invalid_client","OAuth client is not registered.");try{return await zd(r)}catch{throw new p("invalid_client","OAuth client is not registered.")}}let o=await C().readClient({clientId:r});if(o.kind==="found"){let i=o.client,a={kind:"dcr",clientId:r,metadata:{client_id:i.clientId,client_name:i.clientName,redirect_uris:i.redirectUris,token_endpoint_auth_method:i.tokenEndpointAuthMethod}};return i.hashedClientSecret&&(a.hashedClientSecret=i.hashedClientSecret),a}throw new p("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}n(Pt,"resolveClient");function Di(e,t){if(!e.metadata.redirect_uris.some(r=>Tn(r,t)))throw g("invalid_request","redirect_uri is not registered for the client.")}n(Di,"assertRedirectRegistered");function Dd(e){let t=Bi(e.grant_types),r=e.response_types??[...vr];if(!Bd(t))throw new p("invalid_client_metadata","grant_types must be a subset of authorization_code and refresh_token.");if(!Hd(r))throw new p("invalid_client_metadata","response_types must be code.");if(!Ld(e.scope))throw new p("invalid_client_metadata",`Only the ${P} scope is supported.`)}n(Dd,"assertSupportedDcrRequest");function Bi(e){return e===void 0?[...Sr]:Array.from(new Set(e))}n(Bi,"normalizeGrantTypes");function Bd(e){return e.length===0?!1:e.every(t=>Sr.includes(t))}n(Bd,"isSupportedGrantTypes");function Hd(e){return e.length===vr.length&&e[0]==="code"}n(Hd,"isSupportedResponseTypes");function Ld(e){return e===void 0||e===P}n(Ld,"isSupportedDcrScope");function Je(e){if(e===void 0||e===P)return P;throw new p("invalid_request",`Only the ${P} scope is supported.`)}n(Je,"assertSupportedOAuthScope");function Ue(e,t){let r;try{r=new URL(t)}catch{throw new p("invalid_target","resource must be an absolute URI.")}if(r.hash)throw new p("invalid_target","resource must not include a fragment.");if(r.protocol!=="https:"&&!ce(r))throw new p("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let o=I(e),i=bn(),a=i?[...i.byOperationId.values()].find(s=>new URL(s.routePath,o).toString()===t):void 0;if(!a)throw new p("invalid_target","resource must match a published MCP route.");return a}n(Ue,"resolveResource");async function Hi(e){let t;try{t=Od.parse(e)}catch(m){if(m instanceof d.ZodError){let A=m.issues.some(L=>L.path[0]==="redirect_uris");throw new p(A?"invalid_redirect_uri":"invalid_client_metadata",m.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:m})}throw m}Dd(t);for(let m of t.redirect_uris)Ie(m,"invalid_redirect_uri","dcr");let r=new Date,o=te.parse(`dcr:${crypto.randomUUID()}`),i=F(r,Td),a=Math.floor(r.getTime()/1e3),s=Math.floor(i.getTime()/1e3),c={client_id:o,client_name:t.client_name??"Dynamically registered MCP client",redirect_uris:t.redirect_uris,grant_types:Bi(t.grant_types),response_types:["code"],scope:P,token_endpoint_auth_method:t.token_endpoint_auth_method,client_id_issued_at:a},l={clientId:o,clientName:String(c.client_name),redirectUris:t.redirect_uris,tokenEndpointAuthMethod:t.token_endpoint_auth_method,createdAt:R(r),clientExpiresAt:R(i)};if(t.token_endpoint_auth_method!=="none"){let m=J();l.hashedClientSecret=await v(m),l.clientSecretExpiresAt=R(i),c.client_secret=m,c.client_secret_expires_at=s,c.client_secret_issued_at=a}if((await C().registerClient(l)).kind==="already_exists")throw g("invalid_request","OAuth client is already registered.");return c}n(Hi,"registerDownstreamClient");function Li(e){return S`<form class="actions" method="post" action="/oauth/setup" ${e.submitOnceAttrs}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate >Cancel</button><button class="button button--primary" type="submit" name="decision" value="approve" ${e.authorizeAttrs} >Authorize</button></form>`}n(Li,"renderActions");var Wh=V('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="4.6" x2="8" y2="8.4"/><circle cx="8" cy="11" r=".7" fill="currentColor" stroke="none"/></svg>');var Vh=V('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),Yh=V('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>');var Xh=V('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var Nd="data:,",Ni=S`data-submit-once="true" onsubmit="if (this.dataset.submitted === 'true') return false; this.dataset.submitted = 'true'; setTimeout(() => this.querySelectorAll('button').forEach((button) => { button.disabled = true; }), 0);"`,ji=S`data-activate-once="true" onclick="if (this.dataset.activated === 'true') return false; this.dataset.activated = 'true'; this.setAttribute('aria-disabled', 'true'); this.style.pointerEvents = 'none';"`;function jd(e,t){if(e)try{let r=new URL(t).origin,o=new URL(e,r);return o.origin!==r||!o.pathname.startsWith("/auth/connections/")?void 0:o.toString()}catch{return}}n(jd,"safeGatewayConnectHref");function Gd(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}n(Gd,"deriveMode");function $d(e){return Li({state:e.state,submitOnceAttrs:Ni,authorizeAttrs:ge})}n($d,"renderActions");function xr(e,t,r){for(let o of e){if(o.ownerMode!=="user"||o.status!==r)continue;let i=jd(o.connectUrl,t);if(i)return i}}n(xr,"firstUserConnectHref");function Zd(e){let t=e.connectHref?S`<a class="button button--primary" href="${e.connectHref}" ${ji}>Connect</a>`:S`<button class="button button--primary" type="button" disabled aria-disabled="true">Connect</button>`;return S`<form class="actions" method="post" action="/oauth/setup" ${Ni}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate>Cancel</button>${t}</form>`}n(Zd,"renderSetupActions");function Fd(e){return e?S`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${ji}>Re-connect<span class="tooltip" tabindex="0" aria-label="Reset or change how the gateway connects to the upstream service, including changing scopes.">?</span></a></span>`:ge}n(Fd,"renderReconnectAction");function Ar(e){let t=Gd(e.upstreams),r=xr(e.upstreams,e.gatewayOrigin,"not_connected"),o=xr(e.upstreams,e.gatewayOrigin,"reconsent_required"),i=xr(e.upstreams,e.gatewayOrigin,"active"),a=t==="setup"?r??o:void 0,s=S`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>`,c=t==="setup"?S`<footer class="card__footer">${Zd({state:e.state,connectHref:a})}</footer>`:S`<footer class="card__footer">${Fd(i)}${$d({state:e.state})}</footer>`;return Se(xe({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:Nd,styles:ve,headerIcon:ge,heading:"MCP Gateway",subhead:ge,body:s,footer:c}))}n(Ar,"renderConsentPage");var Kd=1e4,Gi="mcp-session-id",Jd,$i;function Wi(){return{tools:[],prompts:[],resources:[]}}n(Wi,"emptyCapabilities");function Zi(e){let t=new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":Nt});switch(e.type){case"none":return t;case"bearer_token":return t.set("authorization",`Bearer ${e.token}`),t;case"headers":for(let[r,o]of Object.entries(e.headers))t.set(r,o);return t;case"mcp_oauth_provider":throw new Error("MCP OAuth provider credentials require async headers.")}}n(Zi,"buildCredentialHeaders");async function Fi(e){if(e.type!=="mcp_oauth_provider")return Zi(e);let t=await e.provider.tokens();if(!t)return;let r=Zi({type:"none"});return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}n(Fi,"buildAsyncCredentialHeaders");function Ki(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(at.parse({jsonrpc:it,id:1,method:"initialize",params:{protocolVersion:Nt,capabilities:{},clientInfo:{name:"zuplo-mcp-gateway-readiness",version:"0.0.0"}}}))})}n(Ki,"buildInitializePreflight");async function Ir(e){Kn(e.url);let t=new AbortController,r=setTimeout(()=>t.abort(),Kd);try{let o=new Request(e,{redirect:"manual",signal:t.signal});return $i?await $i(o):await et.fetch(o)}finally{clearTimeout(r)}}n(Ir,"runPreflight");function Ur(e){e.body?.cancel().catch(()=>{})}n(Ur,"releasePreflightBody");async function Wd(e){let t=e.response.headers.get(Gi);if(!t)return;let r=new Headers(e.headers);r.set(Gi,t),r.delete("content-type");try{let o=await Ir(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));Ur(o)}catch{}}n(Wd,"terminatePreflightSession");async function Vi(e){let{response:t}=e;return Ur(t),t.status>=200&&t.status<300?(await Wd(e),{kind:"ready",upstreamStatus:t.status,capabilities:Wi()}):t.status===401||t.status===403?{kind:"upstream_auth_rejected",status:t.status,message:"Upstream MCP server rejected the configured credential."}:{kind:"upstream_unavailable",status:t.status,message:"Upstream MCP server did not accept the readiness preflight."}}n(Vi,"classifyResponse");function Ji(e){let t={status:e.state==="reconsent_required"?"reconsent_required":"not_connected",connected:!1};return e.nextAction==="admin_setup_required"?{kind:"admin_setup_required",payload:e,connectionStatus:t}:{kind:"connect_required",payload:e,connectionStatus:t}}n(Ji,"connectRequiredResult");async function Vd(e){try{return Vi({response:await Ir(e.request),upstreamUrl:e.upstreamUrl,headers:e.headers})}catch(t){return{kind:"upstream_unavailable",message:t instanceof Error?t.message:"Upstream MCP server readiness preflight failed."}}}n(Vd,"classifyPreflight");async function Yd(e){let t=e.route.connection;if(t===void 0)return{kind:"ready",upstreamStatus:204,capabilities:Wi()};let r=bt(t.upstreamServerId,e.route.operationId),o=be(r,e.principal),i=e.returnTo===void 0?o:{...o,returnTo:e.returnTo},a=await Ce({request:new Request(e.requestUrl),routeAuth:i,preloadedConnection:e.preloadedConnection});if(a.kind==="connect_required")return Ji(a.payload);let s=await Fi(a.credential);if(s===void 0)return{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens."};let c=Ki({upstreamUrl:t.mcpUrl,headers:s}),l;try{l=await Ir(c)}catch(A){return{kind:"upstream_unavailable",message:A instanceof Error?A.message:"Upstream MCP server readiness preflight failed."}}if(l.status!==401)return Vi({response:l,upstreamUrl:t.mcpUrl,headers:s});Ur(l);let h=await Ce({request:new Request(e.requestUrl),routeAuth:i,forceRefresh:!0,preloadedConnection:e.preloadedConnection});if(h.kind==="connect_required")return Ji(h.payload);let m=await Fi(h.credential);return m===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:Vd({request:Ki({upstreamUrl:t.mcpUrl,headers:m}),upstreamUrl:t.mcpUrl,headers:m})}n(Yd,"checkUpstreamRouteReadinessImpl");function Yi(e){return(Jd??Yd)(e)}n(Yi,"checkUpstreamRouteReadiness");function Xd(e){try{return new URL(e).host}catch{return}}n(Xd,"safeUrlHost");function Qd(e){if(e.mode==="user-oauth"||e.mode==="shared-oauth")return e.oauth.scopes}n(Qd,"readOAuthScopes");function Xi(e){return e!==void 0&&e.length>0}n(Xi,"hasItems");function eu(e){let t=e.serverInfo?.icons;return Xi(t)?t:void 0}n(eu,"readServerIcons");async function tu(e){if(!(e.returnTo===void 0||!e.isUserOwned))return ar({requestUrl:e.requestUrl,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:e.registeredConnection.upstreamServerId,authProfileId:e.registeredConnection.authProfileId,operationId:e.route.operationId,returnTo:e.returnTo})}n(tu,"readConnectUrl");function ye(e,t){return t===void 0?{}:{[e]:t}}n(ye,"optionalRequirementField");function ru(e){return e.readiness!==void 0?e.readiness:e.isUserOwned?jn(e.connection):{connected:!0,status:"active"}}n(ru,"readSetupConnectionStatus");function nu(e){let t=Qd(e);return Xi(t)?t:void 0}n(nu,"readScopesRequested");function ou(e){return e.isUserOwned&&"updatedAt"in e.connectionStatus&&e.connectionStatus.updatedAt!==void 0?e.connectionStatus.updatedAt:void 0}n(ou,"readUpdatedAt");function iu(){return{tools:[],prompts:[],resources:[]}}n(iu,"readRouteCapabilities");async function au(e){let{authConfig:t,authMode:r,description:o,displayName:i,mcpUrl:a,upstreamServerId:s,authProfileId:c}=e.registeredConnection,l=wt(r),h=l==="user",m=ru({connection:e.connection,isUserOwned:h,readiness:e.readiness}),A=e.readiness?.connectUrl??await tu({...e,connected:m.connected,isUserOwned:h});return{upstreamServerId:s,authProfileId:c,authMode:r,ownerMode:l,upstreamDisplayName:i,status:m.status,connected:m.connected,capabilities:iu(),...ye("description",o),...ye("transportHost",Xd(a)),...ye("scopesRequested",nu(t)),...ye("serverIcons",eu(e.registeredConnection)),...ye("connectUrl",A),...ye("updatedAt",ou({connectionStatus:m,isUserOwned:h})),...ye("expiresAt",e.readiness?.expiresAt??e.connection?.expiresAt)}}n(au,"buildSetupRequirement");function Qi(e){let t=N().byOperationId.get(e);if(!t)throw g("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}n(Qi,"requireRoute");async function kr(e){let t=Qi(e.transaction.operationId),r=lt(e.transaction.principal.subjectId),o=[],i=new Map,a=t.connection;if(a===void 0)return[];wt(a.authMode)==="user"&&(i.set(a,o.length),o.push({owner:r,upstreamServerId:a.upstreamServerId,authProfileId:a.authProfileId}));let s=await C().batchGetUpstreamConnections(o),c=[],l=wt(a.authMode)==="user",h=i.get(a),m=await Yi({requestUrl:e.requestUrl,route:t,principal:e.transaction.principal,preloadedConnection:l&&h!==void 0?s[h]:void 0,...e.returnTo===void 0?{}:{returnTo:e.returnTo}}),A=(()=>{if("connectionStatus"in m&&m.connectionStatus)return m.connectionStatus})(),L=(m.kind==="connect_required"||m.kind==="admin_setup_required")&&m.payload.authUrl!==void 0?m.payload.authUrl:void 0;return c.push(await au({connection:l&&h!==void 0?s[h]:void 0,registeredConnection:a,route:t,requestUrl:e.requestUrl,returnTo:e.returnTo,transaction:e.transaction,userOwner:r,readiness:A===void 0?void 0:{...A,...L===void 0?{}:{connectUrl:L}}})),c}n(kr,"requirementsForSetup");function su(e){return e.route.connection?.displayName??e.route.operationId}n(su,"readRouteDisplayName");async function Pr(e){let t=Qi(e.transaction.operationId),r=su({route:t}),o=await C().readClient({clientId:e.transaction.clientId}),i=o.kind==="found"?o.client:void 0,a={gatewayOrigin:I(e.requestUrl),routeDisplayName:r,clientDisplayName:i?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},s=t.connection?.description;return s!==void 0&&(a.routeDescription=s),a}n(Pr,"consentContext");function Tr(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}n(Tr,"hasUnresolvedUserUpstream");var cu=["mcp_user"],du="dev-browser-user",uu=["resource is required for /oauth/authorize.","MCP clients should start at the MCP server URL and follow its WWW-Authenticate resource_metadata link.","If your client reached this endpoint directly, use /oauth/authorize/{routePath} where {routePath} is the published MCP route path without a leading slash and each segment is URL-encoded as needed, for example /oauth/authorize/mcp/linear, or add resource={protected resource URI from protected-resource metadata}."].join(" "),lu=d.object({response_type:d.literal("code"),client_id:d.string().min(1),redirect_uri:d.string().min(1),resource:d.url(),code_challenge:d.string().min(43),code_challenge_method:In,state:d.string().min(1).optional(),scope:d.literal(P).default(P)}),pu=d.enum(["continue","approve","cancel"]).default("continue"),mu=d.object({state:d.string().min(1),decision:pu}),ie=class extends Error{static{n(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription}};function ea(e){return typeof e=="string"&&e.length>0?e:void 0}n(ea,"readQueryString");function fu(e){let t=Array.from(N().byOperationId.values());if(t.length!==1)return;let r=t[0];if(r!==void 0)return jt(r.operationId,e.url)}n(fu,"inferSingleRouteResource");function hu(e,t){let r=ea(e.query.resource);if(t===void 0){if(r!==void 0)return r;let i=fu(e);if(i!==void 0)return i;throw new p("invalid_target",uu)}let o=jt(t,e.url);if(r===void 0||r===o)return o;throw new p("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}n(hu,"requireAuthorizeResource");async function gu(e,t){let r={};t!==void 0&&(r.context=t);let o=await It(e,r);if(o.principal)return{principal:o.principal};if(!e.user)return o.evictCookie===void 0?{}:{setCookie:o.evictCookie};let i=gi(e);return{principal:i,setCookie:await Ut({principal:i,requestUrl:e.url})}}n(gu,"resolveBrowserPrincipal");async function yu(e,t){let r={};t!==void 0&&(r.context=t);let o=await It(e,r);if(!o.principal)throw g("authentication_required","Authorization setup requires a current browser session.");return o.principal}n(yu,"requireSetupPrincipal");function ta(e){return`/oauth/setup?state=${encodeURIComponent(e)}`}n(ta,"buildSetupReturnTo");async function ra(e){let t=await kr({transaction:e.transaction,requestUrl:e.requestUrl,returnTo:ta(e.csrfToken)}),r=await Pr({transaction:e.transaction,requestUrl:e.requestUrl}),o={kind:"setup_page",html:Ar({state:e.csrfToken,operationId:e.transaction.operationId,upstreams:t,...r})};return e.setCookie!==void 0&&(o.setCookie=e.setCookie),o}n(ra,"renderSetup");function wu(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}n(wu,"toAuthorizationTransactionClient");async function Or(e,t={}){let r=lu.parse({...e.query,resource:hu(e,t.operationId),state:ea(e.query.state)}),o=Je(r.scope);Ie(r.redirect_uri,"invalid_request","authorize");let i=new Date,a=te.parse(r.client_id),s=await Pt(r.client_id,i);Di(s,r.redirect_uri);try{let c=Ue(e.url,r.resource),l=wu(s);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:a,operationId:c.operationId,scope:o,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved"),t.context&&b(t.context,{eventType:_.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:c.operationId,attributes:{clientId:a,scope:o,responseType:r.response_type}});let h={clientId:s?.clientId??a,...l===void 0?{}:{client:l},redirectUri:r.redirect_uri,resource:r.resource,operationId:c.operationId,scope:o,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state}},{principal:m,setCookie:A}=await gu(e,t.context);if(!m){let Q=await Ti({transaction:h,requestUrl:e.url,now:i});t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:a,operationId:c.operationId},"Downstream OAuth authorize: redirecting to browser login (no session)");let Qe={kind:"redirect",location:Q.browserLoginUrl};return A!==void 0&&(Qe.setCookie=A),Qe}let L=await Oi({transaction:h,principal:m,now:i});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:a,operationId:c.operationId,subjectId:m.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),t.context&&b(t.context,{eventType:_.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:c.operationId,attributes:{clientId:a,scope:o,responseType:r.response_type,subjectId:m.subjectId}}),ra({transaction:L.transaction,csrfToken:L.csrfToken,requestUrl:e.url,setCookie:A})}catch(c){throw _u({redirectUri:r.redirect_uri,clientState:r.state,cause:c})}}n(Or,"authorizeDownstreamClient");function _u(e){if(e.cause instanceof ie)return e.cause;let t=Ru(e.cause);return t?new ie({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}n(_u,"toDownstreamAuthorizeRedirectError");function Ru(e){if(e instanceof p)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof d.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}n(Ru,"mapToOAuthRedirectError");async function na(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let h=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,m=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...h===void 0?{}:{idpErrorDescription:h},...m===void 0?{}:{idpErrorUri:m}},"Identity provider redirected browser-login callback with an error"),g("provider_access_denied",h??"The delegated browser login was not completed.")}let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),g("oauth_state_invalid","Browser login callback is missing state.");let i=await _r(o),a={request:e,stateId:i.stateId};t.context!==void 0&&(a.context=t.context);let s=await yi(a),c=await Ei({browserLoginStateToken:o,principal:s}),l=await ra({transaction:c.transaction,csrfToken:c.csrfToken,requestUrl:e.url});return l.setCookie=await Ut({principal:s,requestUrl:e.url}),l}n(na,"completeBrowserLoginCallback");async function oa(e){let t=D(),r=new URL(e.url);if(!ce(r))throw g("forbidden","Local browser login is only available on loopback HTTP origins.");let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw g("oauth_state_invalid","Local browser login is missing state.");let i=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:"/oauth/callback",I(e.url)),a=new URL(I(e.url)).origin;if(i.origin!==a||i.pathname!=="/oauth/callback")throw g("oauth_callback_mismatch","Local browser login redirect_uri must target this gateway's /oauth/callback route.");i.searchParams.set("state",o);let s={subjectId:dt.parse(du),roles:cu};return{kind:"redirect",location:i,setCookie:await Ut({principal:s,requestUrl:e.url})}}n(oa,"completeLocalDevBrowserLogin");function Cu(e){let t=e.method==="POST"?e.body:e.query;return mu.parse(t)}n(Cu,"readSetupContinueRequest");async function ia(e){let{state:t,decision:r}=Cu({method:e.request.method,query:e.request.query,body:e.body}),o=new Date,i=await br({csrfToken:t,now:o}),a=await yu(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await zi({csrfToken:t,currentBrowserPrincipal:a,now:o})};let s=await qi({csrfToken:t,currentBrowserPrincipal:a,now:o}),c=await kr({transaction:s,requestUrl:e.request.url,returnTo:ta(t)});if(r==="approve"&&Tr(c)&&await ki({csrfToken:t,currentBrowserPrincipal:a,now:o}),Tr(c)){let l=await Pr({transaction:s,requestUrl:e.request.url});return{kind:"setup_page",html:Ar({state:t,operationId:s.operationId,upstreams:c,...l})}}return{kind:"redirect",location:await Mi({csrfToken:t,currentBrowserPrincipal:a,now:o})}}n(ia,"continueDownstreamAuthorizeSetup");z();import{createLocalJWKSet as bu,decodeJwt as Su,errors as We,jwtVerify as vu}from"jose";var xu=new Set(["authorization_code","refresh_token"]),Au="urn:ietf:params:oauth:client-assertion-type:jwt-bearer",Iu=1e4,Uu=32*1024,ku=2,aa=d.object({client_id:d.string().min(1).optional(),client_secret:d.string().min(1).optional(),client_assertion_type:d.string().min(1).optional(),client_assertion:d.string().min(1).optional()}),Pu=d.discriminatedUnion("grant_type",[aa.extend({grant_type:d.literal("authorization_code"),code:d.string().min(1),redirect_uri:d.string().min(1),code_verifier:ct,resource:d.url().optional(),scope:d.literal(P).optional()}),aa.extend({grant_type:d.literal("refresh_token"),refresh_token:d.string().min(1),resource:d.url().optional(),scope:d.literal(P).optional()})]);function Tu(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!xu.has(t)))throw new p("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}n(Tu,"assertSupportedGrantType");var Ou=d.object({token:d.string().min(1),client_id:d.string().min(1).optional(),token_type_hint:d.string().optional(),client_secret:d.string().min(1).optional(),client_assertion_type:d.string().min(1).optional(),client_assertion:d.string().min(1).optional()}),Eu=d.object({keys:d.array(d.record(d.string(),d.unknown())).min(1)}).passthrough();function sa(){return D().gateway.accessTokenTtlSeconds}n(sa,"readAccessTokenTtlSeconds");function qu(){return D().gateway.refreshTokenTtlSeconds}n(qu,"readRefreshTokenTtlSeconds");function Mu(e,t){let r=sa(),o=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),i=Math.min(r,o);return{expiresAt:R(F(e,i)),expiresIn:i}}n(Mu,"calculateAccessTokenExpiresAt");function ca(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new p("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new p("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new p("invalid_client","Malformed HTTP Basic client authentication.")}}n(ca,"readBasicClientSecret");function da(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new p("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t!==void 0)return t;if(e.clientAssertion!==void 0){try{let r=Su(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new p("invalid_client","Malformed private_key_jwt client assertion.")}throw new p("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new p("invalid_client","Client authentication or client_id is required.")}n(da,"resolveAuthenticatedClientId");function zu(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new p("invalid_request","Use only one client authentication method per request.");return e.basicClientSecret!==void 0?{clientSecret:e.basicClientSecret,clientSecretSource:"basic"}:e.bodyClientSecret!==void 0?{clientSecret:e.bodyClientSecret,clientSecretSource:"post"}:{}}n(zu,"resolveClientSecretInput");function Du(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}n(Du,"hasClientAssertion");function Bu(e){if(e.requestUrl===void 0)throw new p("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(e.pathname,e.requestUrl);return t.search="",t.hash="",t.toString()}n(Bu,"buildEndpointAudience");function Hu(e){return e instanceof We.JWTExpired?"expired":e instanceof We.JWTClaimValidationFailed?"claim":e instanceof We.JWSSignatureVerificationFailed?"signature":e instanceof We.JWKSNoMatchingKey?"jwks_no_match":e instanceof We.JWTInvalid?"invalid":e instanceof d.ZodError?"schema":"other"}n(Hu,"readJwtFailureKind");async function Lu(e){let{response:t,json:r}=await Xn(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:ku,maxResponseBytes:Uu,timeoutMs:Iu});if(!t.ok)throw new p("invalid_client","Client JWKS could not be fetched.");return Eu.parse(r)}n(Lu,"fetchClientJwks");async function Nu(e){if(e.clientAssertionType!==Au||e.clientAssertion===void 0)throw new p("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=te.parse(e.clientId),r=await Pt(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new p("invalid_client","Client is not registered for private_key_jwt authentication.");let o=r.metadata.jwks_uri;if(o===void 0)throw new p("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let i=Bu({requestUrl:e.requestUrl,pathname:e.endpointPathname});try{let a=await Lu({jwksUri:o,context:e.context});await vu(e.clientAssertion,bu(a),{issuer:t,subject:t,audience:i,currentDate:e.now})}catch(a){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:Hu(a)},"OAuth private_key_jwt client authentication failed"),new p("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}n(Nu,"verifyPrivateKeyJwtClientAssertion");async function ju(e){let t=te.parse(e.clientId);return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await v(e.clientSecret)}}n(ju,"buildRuntimeHttpClientAuth");async function ua(e){if(Du({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new p("invalid_request","Use only one client authentication method per request.");return Nu(e)}let t=zu({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return ju({clientId:e.clientId,...t})}n(ua,"resolveRuntimeHttpClientAuth");async function la(e){Tu(e.body);let t=Pu.parse(e.body),r=ca(e.authorizationHeader),o=da({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),i=new Date,a=await ua({clientId:o,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,endpointPathname:"/oauth/token",now:i,context:e.context});return Gu({parsed:t,clientId:o,clientAuth:a,now:i,requestUrl:e.requestUrl,context:e.context})}n(la,"exchangeDownstreamToken");async function Gu(e){if(e.parsed.grant_type==="authorization_code"){Ie(e.parsed.redirect_uri,"invalid_request","token"),Je(e.parsed.scope),e.parsed.resource!==void 0&&Ue(e.requestUrl??e.parsed.resource,e.parsed.resource);let s=J(),c=J(),l=R(F(e.now,qu())),h=Mu(e.now,l),m=await C().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await v(e.parsed.code),redirectUri:e.parsed.redirect_uri,...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},codeChallenge:await Fn(e.parsed.code_verifier),currentRefreshTokenHash:await v(s),accessTokenHash:await v(c),grantExpiresAt:l,accessTokenExpiresAt:h.expiresAt,now:R(e.now)});if(m.kind==="invalid_client")throw new p("invalid_client","Client authentication failed.");if(m.kind==="resource_mismatch")throw new p("invalid_target","Token request resource must match the authorization code resource.");if(m.kind!=="exchanged")throw new p("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&b(e.context,{eventType:_.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:c,token_type:"Bearer",expires_in:h.expiresIn,refresh_token:s,scope:m.grant.scope,resource:m.grant.resource}}Je(e.parsed.scope),e.parsed.resource!==void 0&&Ue(e.requestUrl??e.parsed.resource,e.parsed.resource);let t=J(),r=J(),o=R(F(e.now,sa())),i=await C().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:await v(e.parsed.refresh_token),nextRefreshTokenHash:await v(t),accessTokenHash:await v(r),...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},accessTokenExpiresAt:o,now:R(e.now)});if(i.kind==="invalid_client")throw new p("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new p("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new p("invalid_grant","Refresh token is invalid, expired, or revoked.");Ue(e.requestUrl??i.grant.resource,i.grant.resource);let a=i.accessToken.expiresAt;return e.context&&(b(e.context,{eventType:_.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),b(e.context,{eventType:_.MCP_OAUTH_TOKEN_REFRESH_ROTATED,outcome:"success",attributes:{clientId:e.clientId}})),{access_token:r,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(a).getTime()-e.now.getTime())/1e3)),refresh_token:t,scope:i.grant.scope,resource:i.grant.resource}}n(Gu,"exchangeDownstreamTokenWithRuntimeHttp");async function pa(e){let t=Ou.parse(e.body),r=ca(e.authorizationHeader),o=da({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),i=new Date;if((await C().revokeOAuthToken({clientAuth:await ua({clientId:o,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,endpointPathname:"/oauth/revoke",now:i,context:e.context}),tokenHash:await v(t.token),now:R(i)})).kind==="invalid_client")throw new p("invalid_client","Client authentication failed.");e.context?.log.info({event:"oauth_token_revoked",clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed"),e.context&&b(e.context,{eventType:_.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}n(pa,"revokeDownstreamToken");var $u=64*1024,Zu=16*1024,Fu="text/html; charset=utf-8";function Ku(e){let t={};for(let[r,o]of e.entries())t[r]=o;return t}n(Ku,"formDataToObject");async function Ju(e){return pi(e,{maxBytes:$u,label:"Request body"})}n(Ju,"readJsonBody");async function Er(e){return Ku(await mi(e,{maxBytes:Zu,label:"Request body"}))}n(Er,"readFormBody");async function ma(e,t,r){let o=de(r),i=r instanceof d.ZodError?Tt(r):void 0,a={code:o??(r instanceof d.ZodError?"invalid_request":"internal_server_error")};return i!==void 0&&(a.detail=i),xn(e,t,a)}n(ma,"handleProblem");function Ve(e){let t=new Headers(e.headers);t.set("cache-control","no-store"),t.set("pragma","no-cache");let r={error:e.error};return e.errorDescription!==void 0&&(r.error_description=e.errorDescription),Response.json(r,{status:e.status??400,headers:t})}n(Ve,"oauthErrorResponse");function Wu(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}n(Wu,"readOAuthProtocolHeaders");function Vu(e,t){let r=B("internal_server_error");return Ve({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:Wu(e,t)})}n(Vu,"oauthProtocolErrorResponse");function fa(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}n(fa,"readZodOAuthErrorCode");function Yu(e){let t={error:fa(e)},r=Tt(e);return r!==void 0&&(t.errorDescription=r),Ve(t)}n(Yu,"oauthZodErrorResponse");function Xu(e){let t=de(e);if(t===void 0)return;let r=B(t);if(r.oauthError===void 0)return;let o={error:r.oauthError,status:el(r.oauthError)};return r.oauthError==="server_error"?o.errorDescription=r.publicDetail:e instanceof Error?o.errorDescription=e.message:o.errorDescription=r.publicDetail,Ve(o)}n(Xu,"oauthGatewayProblemResponse");function Qu(){let t={error:"server_error",status:500,errorDescription:B("internal_server_error").publicDetail};return Ve(t)}n(Qu,"oauthFallbackErrorResponse");function el(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}n(el,"readOAuthStatus");function qr(e,t={}){return e instanceof ie?ya(e):e instanceof p?Vu(e,t):e instanceof d.ZodError?Yu(e):Xu(e)??Qu()}n(qr,"oauthProblemResponse");function Mr(e,t){let r=Ae(e.url);if(t instanceof ie)return ya(t);if(t instanceof p){let a=B("internal_server_error");return $({host:r,kind:tl(t.errorCode),title:"Authorization failed",detail:t.errorCode==="server_error"?a.publicDetail:t.message,code:t.errorCode,status:t.status})}if(t instanceof d.ZodError)return $({host:r,kind:"invalid_request",detail:Tt(t)??"The authorization request was invalid.",code:fa(t)});let o=de(t);if(o!==void 0){let a=B(o);return $({host:r,kind:ga(o),detail:a.status<500&&t instanceof Error?t.message:a.publicDetail,code:a.oauthError??o,status:a.status})}let i=B("internal_server_error");return $({host:r,kind:"internal_error",detail:i.publicDetail,code:"server_error",status:i.status})}n(Mr,"browserOAuthProblemResponse");function ha(e,t){let r=Ae(e.url),o=de(t);if(o!==void 0){let a=B(o);return $({host:r,kind:ga(o),detail:a.status<500&&t instanceof Error?t.message:a.publicDetail,code:o,status:a.status})}if(t instanceof d.ZodError)return $({host:r,kind:"invalid_request",detail:Tt(t)??"The authorization request was invalid.",code:"invalid_request"});let i=B("internal_server_error");return $({host:r,kind:"internal_error",detail:i.publicDetail,code:"internal_server_error",status:i.status})}n(ha,"browserGatewayProblemResponse");function tl(e){return e==="server_error"?"internal_error":"invalid_request"}n(tl,"readOAuthBrowserErrorKind");function ga(e){if(B(e).status>=500)return"internal_error";switch(e){case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"configuration_error";case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"upstream_client_registration_required":return"admin_required";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"invalid_request":case"authentication_required":case"forbidden":case"not_found":case"too_many_requests":case"identity_context_missing":return"invalid_request";case"upstream_capability_invocation_failed":case"upstream_capability_unavailable":case"upstream_import_failed":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}n(ga,"readGatewayBrowserErrorKind");function Y(e,t,r){let o={event:t},i=!1;if(r instanceof p)o.oauthError=r.errorCode,o.status=r.status,K(o,"error",r);else if(r instanceof ie)o.oauthError=r.errorCode,K(o,"error",r);else if(r instanceof d.ZodError){o.code="invalid_request",K(o,"error",r);let a=r.issues[0];a&&(o.zodPath=a.path.join("."))}else{let a=de(r);if(a!==void 0){let s=B(a);o.code=a,o.status=s.status,s.oauthError!==void 0&&(o.oauthError=s.oauthError),i=s.status>=500||s.oauthError==="server_error",K(o,"error",r)}else i=!0,K(o,"error",r)}if(i){let a=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(o,a.message)}else e.log.warn(o,"OAuth handler rejected the request")}n(Y,"logUnexpectedOAuthHandlerError");function ya(e){let t;try{t=new URL(e.redirectUri)}catch{return Ve({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}n(ya,"downstreamAuthorizeRedirectErrorResponse");function Tt(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}n(Tt,"formatZodErrorDetail");function rl(e,t){let r={event:"browser_login_callback_failed",code:de(t)??"invalid_request"};K(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}n(rl,"logBrowserLoginCallbackFailure");function wa(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(null,{status:302,headers:t})}n(wa,"redirectResultResponse");function Ot(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":Fu,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(e.html,{status:200,headers:t})}return wa(e)}n(Ot,"authorizeResultResponse");async function _a(e,t){try{return Response.json(En(e.url))}catch(r){return Y(t,"oauth_authorization_server_metadata_failed",r),ma(e,t,r)}}n(_a,"authorizationServerMetadataHandler");async function Ra(e,t){try{let r=Gt(e.params.routePath);return Response.json(qn({operationId:r.operationId,requestUrl:e.url}))}catch(r){return Y(t,"oauth_authorization_server_metadata_failed",r),ma(e,t,r)}}n(Ra,"scopedAuthorizationServerMetadataHandler");async function Ca(e,t){try{let r=await Hi(await Ju(e)),o=r,i=typeof o.client_id=="string"?o.client_id:void 0,a=typeof o.client_name=="string"?o.client_name:void 0,s=Array.isArray(o.redirect_uris)?o.redirect_uris.length:void 0,c=typeof o.token_endpoint_auth_method=="string"?o.token_endpoint_auth_method:void 0;return t.log.info({event:"oauth_dcr_client_registered",clientId:i,clientName:a,redirectUriCount:s,tokenEndpointAuthMethod:c},"OAuth Dynamic Client Registration completed"),b(t,{eventType:_.MCP_OAUTH_CLIENT_REGISTERED,outcome:"success",clientName:a,attributes:{clientId:i,redirectUriCount:s,tokenEndpointAuthMethod:c}}),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return Y(t,"oauth_register_failed",r),qr(r)}}n(Ca,"registerHandler");async function ba(e,t){try{return Ot(await Or(e,{context:t}))}catch(r){return Y(t,"oauth_authorize_failed",r),Mr(e,r)}}n(ba,"authorizeHandler");async function Sa(e,t){try{let r=Gt(e.params.routePath);return Ot(await Or(e,{operationId:r.operationId,context:t}))}catch(r){return Y(t,"oauth_authorize_scoped_failed",r),Mr(e,r)}}n(Sa,"scopedAuthorizeHandler");async function va(e,t){try{let r=await na(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),Ot(r)}catch(r){return rl(t,r),ha(e,r)}}n(va,"callbackHandler");async function xa(e,t){try{return wa(await oa(e))}catch(r){return Y(t,"oauth_dev_login_failed",r),Mr(e,r)}}n(xa,"devLoginHandler");async function Aa(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await ia({request:e,body:e.method==="POST"?await Er(e):void 0,context:t});return Ot(r)}catch(r){return Y(t,"oauth_setup_failed",r),ha(e,r)}}n(Aa,"setupHandler");async function Ia(e,t){try{return Response.json(await la({body:await Er(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return Y(t,"oauth_token_failed",r),qr(r)}}n(Ia,"tokenHandler");async function Ua(e,t){try{return await pa({body:await Er(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return Y(t,"oauth_revoke_failed",r),qr(r)}}n(Ua,"revokeHandler");var nl={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},ka=new Fr("upstream-request");function ol(e){let t=ka.get(e);if(!t)throw new E("Upstream request context has not been set");return t}n(ol,"readUpstreamRequestContext");function il(e,t){return t.some(r=>r===e)}n(il,"requestContextMatchesKind");function al(e){return typeof e=="string"?[e]:e}n(al,"toExpectedKinds");function ke(e,t){ka.set(e,t)}n(ke,"setUpstreamRequestContext");function Ye(e,t){let r=ol(e),o=al(t);if(!il(r.kind,o)){let i=nl[o[0]];throw new E(`${i} request context has not been set`)}return r}n(Ye,"requireUpstreamRequestContext");function Pa(e){return S`<p data-gateway-error-code="${e.code}">${e.body}</p>`}n(Pa,"renderBrowserResult");var sl="text/html; charset=utf-8",cl="none";function dl(e){let t=vt(e.host);return xe({title:e.title,iconHref:t,styles:ve,headerIcon:xt({iconHref:t,fallbackIconHref:St}),heading:e.title,subhead:"",body:Pa({body:e.body,code:e.code??cl}),footer:""})}n(dl,"browserResultHtml");function ul(e,t=200){return new Response(Se(e),{status:t,headers:{"content-type":sl,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(ul,"browserResultResponse");function Ta(e){return ul(dl(e))}n(Ta,"browserConnectionSuccessResponse");function Et(e,t){let r=vn(t);return $({host:e,kind:ll(t),detail:r.body,code:t})}n(Et,"browserConnectionFailureResponse");function ll(e){switch(e){case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed"}}n(ll,"readCallbackFailureBrowserErrorKind");var pl=["callback_authorization_code","callback_provider_error","callback_invalid"];function ml(e){return"cause"in e?e.cause:void 0}n(ml,"readErrorCause");function fl(e){return e.stack?.split(`
28
+ `).slice(1,4).map(t=>t.trim()).join(" | ")}n(fl,"readFirstStackFrame");function Oa(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=fl(r))}n(Oa,"addErrorAttributes");function zr(e){if(!(e instanceof y))return;let t=e.extensionMembers?.[w];return sn(t)?t:void 0}n(zr,"readRuntimeGatewayCode");function hl(e,t,r){switch(t.kind){case"callback_provider_error":return e.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:t.upstreamServerId,providerError:t.error,...t.errorDescription===void 0?{}:{providerErrorDescription:t.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),b(e,{eventType:_.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:t.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:t.error,errorDescription:t.errorDescription}}),Et(r,"provider_access_denied");case"callback_invalid":return e.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:t.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),Et(r,"oauth_state_invalid");case"callback_authorization_code":return t}}n(hl,"requireAuthorizationCallbackRequest");function gl(e,t){b(e,{eventType:_.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}n(gl,"emitCallbackReceivedAnalyticsEvent");function yl(e,t){b(e,{eventType:_.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}n(yl,"emitTokenExchangeSucceededAnalyticsEvent");function wl(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return Ta({host:Ae(e.url),title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}n(wl,"buildSuccessfulCallbackResponse");function _l(e){let t={detail:e instanceof Error?e.message:void 0};return Oa(t,"error",e),e instanceof Error&&Oa(t,"cause",ml(e)),t}n(_l,"buildTokenExchangeFailureAttributes");function Rl(e){b(e.context,{eventType:_.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:zr(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:_l(e.error)})}n(Rl,"emitTokenExchangeFailedAnalyticsEvent");function Cl(e,t){let r=zr(t);return Et(e,cn(r)?r:"upstream_token_exchange_failed")}n(Cl,"tokenExchangeFailureResponse");async function Dr(e,t){let r=Ye(t,pl),o=Ae(e.url),i=hl(t,r,o);if(i instanceof Response)return i;gl(t,i);try{let a=await ei({request:e,callbackRequest:i});return yl(t,a),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:a.upstreamServerId,operationId:a.operationId,authProfileId:a.authProfileId,ownerMode:a.ownerMode},"Upstream OAuth token exchange completed; user connection established"),wl(e,a)}catch(a){let s={event:"upstream_oauth_token_exchange_failed",code:zr(a)??"upstream_token_exchange_failed",upstreamServerId:i.upstreamServerId};return K(s,"error",a),t.log.warn(s,"Upstream OAuth token exchange failed; user shown connection-failure page"),Rl({context:t,callbackRequest:i,error:a}),Cl(o,a)}}n(Dr,"callbackHandler");function bl(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}n(bl,"clientMetadataProblemDetail");async function Ea(e,t){let r=Ye(t,"connect"),o=await Qo({request:e,connectRequest:r});if(b(t,{eventType:_.MCP_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:o.operationId,upstreamServerTitle:o.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:o.authProfileId,operationId:o.operationId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),r.redirect)return Response.redirect(o.authUrl,302);let i=await Rt({requestUrl:e.url,owner:o.owner,initiatedBySubjectId:o.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:o.authProfileId,upstreamDisplayName:o.upstreamDisplayName,operationId:o.operationId,subject:"MCP route",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(i,{status:428})}n(Ea,"connectHandler");async function qa(e,t){let r=Ye(t,"client_metadata");try{let o=Do(e.url),i=Bo(o,r.upstreamServerId,r.authProfileId);return Response.json(i)}catch(o){if(!(o instanceof k))throw o;let i=o instanceof Error?o.message:String(o);return t.log.warn({event:"oauth_client_metadata_request_failed",upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:i},"Failed to serve OAuth client metadata document for upstream connection"),se.notFound(e,t,{code:"not_found",detail:bl(o)})}}n(qa,"oauthClientMetadataHandler");function ae(e){if(typeof e=="string"&&e.length!==0)return e}n(ae,"readOptionalQueryString");function Sl(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new E(`Validated path parameter ${t} is missing`);return r}n(Sl,"requirePathString");function vl(e){let t=ae(e);return t?ot.parse(t):void 0}n(vl,"readOptionalOperationId");function xl(e,t){let r=ae(e);return r?ln.parse(r):st(t,"user-oauth")}n(xl,"readOptionalAuthProfileId");function Al(e){let t=vl(e);if(!t)throw new y({message:"operationId query parameter is required.",extensionMembers:{[w]:"invalid_request"}});return t}n(Al,"readRequiredOperationId");function Il(e){let t=Dn(ae(e));return t===void 0?{}:{returnTo:t}}n(Il,"readOptionalReturnTo");function Ul(e){let t=ae(e.query.error_description);return t===void 0?{}:{errorDescription:t}}n(Ul,"readOptionalProviderErrorDescription");function kl(e){let t=j(e.authMode);if(t.connectSupport!=="none")return e;throw new y({message:t.connectUnsupportedDetail??"This upstream does not support browser connection flows.",extensionMembers:{[w]:"invalid_request"}})}n(kl,"requireConnectableRouteAuth");function Pl(e,t,r,o){return{kind:"connect",...be(e,t),...o===void 0?{}:{returnTo:o},redirect:r}}n(Pl,"buildConnectContextForPrincipal");function Tl(e,t,r){let o=pt(t),i=j(e.authMode);if(o.mode!==i.ownerMode)throw new y({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[w]:"oauth_callback_mismatch"}});return{kind:"connect",...e,...t.returnTo===void 0?{}:{returnTo:t.returnTo},owner:o,initiatedBySubjectId:t.initiatedBySubjectId,redirect:r}}n(Tl,"buildConnectContextForTicket");async function Ol(e,t){let r=kl(bt(t,Al(e.query.operationId))),o=e.query.redirect==="true",i=ae(e.query.browserTicket);if(e.user){if(i)throw new y({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[w]:"invalid_request"}});let s=ut(e.user,e.url);return Pl(r,s,o,Il(e.query.returnTo).returnTo)}if(!i)throw new y({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[w]:"authentication_required"}});let a=await Eo(i);if(a.ownerMode!==r.ownerMode||a.upstreamServerId!==r.upstreamServerId||a.authProfileId!==r.authProfileId||a.operationId!==r.operationId)throw new y({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[w]:"oauth_callback_mismatch"}});return await qo(a),Tl(r,a,o)}n(Ol,"resolveConnectContext");async function El(e,t,r){let o=un.parse(Sl(e,"connection"));switch(r){case"connect":ke(t,await Ol(e,o));return;case"callback":{let i=ae(e.query.error);if(i){ke(t,{kind:"callback_provider_error",upstreamServerId:o,error:i,...Ul(e)});return}let a=ae(e.query.code),s=ae(e.query.state);if(a&&s){ke(t,{kind:"callback_authorization_code",upstreamServerId:o,code:a,state:s});return}ke(t,{kind:"callback_invalid",upstreamServerId:o});return}case"client_metadata":ke(t,{kind:"client_metadata",upstreamServerId:o,authProfileId:xl(e.query.authProfileId,o)});return}}n(El,"resolveUpstreamRequestInbound");async function ql(e,t,r){try{await El(e,t,r);return}catch(o){let i=o instanceof y?o.extensionMembers?.[w]:void 0,a=o instanceof Error?o.message:void 0;switch(i){case"invalid_request":case"oauth_callback_mismatch":return se.badRequest(e,t,{code:i,detail:a});case"authentication_required":return se.unauthorized(e,t,{code:i,detail:a});default:throw o}}}n(ql,"applyUpstreamRequestContext");function qt(e,t){return n(async(o,i)=>{let a=await ql(o,i,e);return a||t(o,i)},"wrapped")}n(qt,"withUpstreamRequestContext");var Ml={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function zl(){return new Response(null,{status:204,headers:Ml})}n(zl,"buildWellKnownPreflightResponse");function Dl(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}n(Dl,"withWellKnownCorsHeaders");function Br(e){return async(t,r)=>t.method==="OPTIONS"?zl():Dl(await e(t,r))}n(Br,"wrapWellKnownHandler");var Da=[{routeName:"oauth_as_metadata",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:Br(_a),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:Br(Ra),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:Br(Mn),corsPolicy:"anything-goes"},{routeName:"oauth_register",path:"/oauth/register",methods:["POST"],handler:Ca},{routeName:"oauth_authorize",path:"/oauth/authorize",methods:["GET"],handler:ba},{routeName:"oauth_authorize_scoped",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:Sa},{routeName:"oauth_callback",path:"/oauth/callback",methods:["GET"],handler:va},{routeName:"oauth_dev_login",path:"/oauth/dev-login",methods:["GET"],handler:xa},{routeName:"oauth_setup",path:"/oauth/setup",methods:["GET","POST"],handler:Aa},{routeName:"oauth_token",path:"/oauth/token",methods:["POST"],handler:Ia},{routeName:"oauth_revoke",path:"/oauth/revoke",methods:["POST"],handler:Ua},{routeName:"upstream_client_metadata",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:qt("client_metadata",qa)},{routeName:"upstream_connect",path:"/auth/connections/:connection/connect",methods:["GET"],handler:qt("connect",Ea)},{routeName:"upstream_callback",path:"/auth/connections/:connection/callback",methods:["GET"],handler:qt("callback",Dr)}],Bl=Da.filter(e=>!e.routeName.startsWith("upstream_")),Hl=Da.filter(e=>e.routeName.startsWith("upstream_"));function Ba(e){return e?.some(on)??!1}n(Ba,"hasMcpOAuthRuntimeConfigPolicy");function Ha(e){return e?.some(t=>yn(t.policyType))??!1}n(Ha,"hasMcpTokenExchangePolicy");function La(e){return Ba(e)||Ha(e)}n(La,"shouldRegisterMcpGatewayInternalRoutes");function Ll(e){Rn(wn({routes:e.routes,policies:e.policies}))}n(Ll,"initializeMcpGatewayConnectionRegistry");function Nl(e){let t=an(e.policies);if(!t){let r=[...nn].map(o=>`\`${o}\``).join(", ");throw new k(`MCP gateway: could not find an MCP authorization policy in policies.json. Add one of [${r}] and reference it on your MCP routes.`)}return t.config}n(Nl,"initializeMcpGatewayOAuthRuntimeConfig");function Ma(e,t,r){return async(o,i)=>{r&&tn(i,r());let a=o.method==="OPTIONS",s=Date.now();a||i.log.info({event:`${e}_received`,method:o.method},`MCP gateway: ${e} received`);let c=await t(o,i);return a||i.log.info({event:`${e}_responded`,status:c.status,durationMs:Date.now()-s},`MCP gateway: ${e} responded`),c}}n(Ma,"wrapInternalHandler");function za(e,t,r){e.addPluginRoute({path:t.path,methods:t.methods,handler:r,processors:[Zr],corsPolicy:t.corsPolicy??"none"})}n(za,"addInternalRoute");function Na(e,t){Ll(t);let r=Ba(t.policies),o=Ha(t.policies),i,a=n(()=>(i===void 0&&(i=Nl(t)),i),"readOAuthConfig");if(r)for(let s of Bl)za(e,s,Ma(s.routeName,s.handler,a));if(o)for(let s of Hl)za(e,s,Ma(s.routeName,s.handler))}n(Na,"registerMcpGatewayInternalRoutes");function ja(e){_n(e)}n(ja,"configureLazyMcpGatewayState");var Hr=class extends Gr{static{n(this,"McpGatewayPlugin")}registerRoutes(t){let r=t.parsedRouteData;if(!r||!La(r.policies))return;let o={routes:r.routes,policies:r.policies};ja(o),Na(t.router,o)}};var jl=new TextDecoder;function Gl(e){if(e)try{return JSON.parse(jl.decode(e))}catch{return}}n(Gl,"readBodyJson");function X(e){return e&&typeof e=="object"?e:void 0}n(X,"readRecord");function Xe(e,t){let r=X(e)?.[t];return typeof r=="string"?r:void 0}n(Xe,"readStringProperty");function $a(e,t){let r=X(e)?.[t];return typeof r=="number"?r:void 0}n($a,"readNumberProperty");function Ga(e,t){return $a(e,"code")??(t.status>=400?t.status:void 0)}n(Ga,"readErrorCode");function Za(e){return Array.isArray(e)?e.map(Za).find(t=>t?.method):X(e)}n(Za,"readJsonRpcMessage");function Fa(e){let t=Za(Gl(e)),r=typeof t?.method=="string"?t.method:"",o=t?.params;switch(r){case"tools/list":return{mcpMethod:r,capabilityType:"tool"};case"tools/call":return{mcpMethod:r,capabilityType:"tool",capabilityName:Xe(o,"name")};case"prompts/list":return{mcpMethod:r,capabilityType:"prompt"};case"prompts/get":return{mcpMethod:r,capabilityType:"prompt",capabilityName:Xe(o,"name")};case"resources/list":case"resources/templates/list":return{mcpMethod:r,capabilityType:"resource"};case"resources/read":{let i=Xe(o,"uri");return{mcpMethod:r,capabilityType:"resource",capabilityName:i,resourceUri:i}}default:return null}}n(Fa,"buildBaseCapabilityInput");function Ka(e){return e==="tools/list"||e==="prompts/list"||e==="resources/list"||e==="resources/templates/list"}n(Ka,"isCapabilityListMethod");function $l(e,t,r){let a=X(r)?.[e==="resources/templates/list"?"resourceTemplates":t==="tool"?"tools":t==="prompt"?"prompts":"resources"];return Array.isArray(a)?a.length:void 0}n($l,"readItemCount");async function Zl(e){try{return await e.clone().json()}catch{return}}n(Zl,"readResponseJson");function Ja(e){let t=Fa(e);return!t||Ka(t.mcpMethod)?null:{eventType:_.MCP_CAPABILITY_INVOKED,outcome:"success",...t}}n(Ja,"buildCapabilityInvokedAnalyticsInput");async function Wa(e,t){let r=Fa(e);if(!r)return null;let o=X(await Zl(t)),i=X(o?.error),a=X(i?.data),s=o?.result,c=r.mcpMethod==="tools/call"&&X(s)?.isError===!0;if(X(a?.connectRequired))return{eventType:_.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",...r,httpStatusCode:t.status,reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required",errorCode:$a(i,"code"),mcpErrorType:Xe(i,"message")};if(Ka(r.mcpMethod)){let l=t.status>=400?void 0:$l(r.mcpMethod,r.capabilityType,s);return{eventType:_.MCP_CAPABILITY_LISTED,outcome:t.status>=400||i?"failure":"success",...r,httpStatusCode:t.status,...t.status>=400||i?{reasonCode:"upstream_capability_list_failed",reasonClass:"upstream",errorType:"capability_list_error",errorCode:Ga(i,t)}:{},...l===void 0?{}:{attributes:{itemCount:l}}}}return t.status>=400||i?{eventType:_.MCP_CAPABILITY_FAILED,outcome:"failure",...r,httpStatusCode:t.status,reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"capability_error",errorCode:Ga(i,t),mcpErrorType:Xe(i,"message")}:{eventType:_.MCP_CAPABILITY_COMPLETED,outcome:c?"application_error":"success",...r,httpStatusCode:t.status,toolResultIsError:c,applicationError:c}}n(Wa,"buildCapabilityFinalAnalyticsInput");var Fl={Allow:"POST"};async function Kl(e){try{return await e.clone().arrayBuffer()}catch{return}}n(Kl,"readRequestBody");function Va(e){try{let t=Cn(e.route.path);return{virtualServerName:t.operationId,upstreamServerName:t.connection?.upstreamServerId,upstreamServerTitle:t.connection?.displayName,authProfileId:t.connection?.authProfileId,upstreamAuthMode:t.connection?.authMode}}catch{return{}}}n(Va,"readRouteAnalyticsFields");function Jl(e){let t=Ja(e.requestBody);t&&b(e.context,{...t,...Va(e.context),httpMethod:e.request.method,transport:"http"})}n(Jl,"emitCapabilityInvokedAnalytics");async function Wl(e){let t=await Wa(e.requestBody,e.response);t&&b(e.context,{...t,...Va(e.context),httpMethod:e.request.method,transport:"http",latencyMs:Date.now()-e.startedAt})}n(Wl,"emitCapabilityFinalAnalytics");async function Vl(e,t){if(e.method==="GET")return se.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},Fl);let r=Date.now(),o=await Kl(e);Jl({context:t,request:e,requestBody:o});let i=await Qr(e,t);return await Wl({context:t,request:e,requestBody:o,response:i,startedAt:r}),i}n(Vl,"McpProxyHandler");export{ts as McpAuth0OAuthInboundPolicy,Zt as McpCapabilityFilterInboundPolicy,Hr as McpGatewayPlugin,es as McpOAuthInboundPolicy,Vl as McpProxyHandler,fr as McpTokenExchangeInboundPolicy};
29
29
  //# sourceMappingURL=index.js.map