@zuplo/runtime 6.70.59 → 6.70.61
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.
- package/out/esm/{chunk-AQGS5CID.js → chunk-6WKYPMAI.js} +86 -86
- package/out/esm/chunk-6WKYPMAI.js.map +1 -0
- package/out/esm/index.js +1 -1
- package/out/esm/mcp-gateway/index.js +1 -1
- package/package.json +1 -1
- package/out/esm/chunk-AQGS5CID.js.map +0 -1
- /package/out/esm/{chunk-AQGS5CID.js.LEGAL.txt → chunk-6WKYPMAI.js.LEGAL.txt} +0 -0
package/out/esm/index.js
CHANGED
|
@@ -22,5 +22,5 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{$ as tt,$a as tr,$c as Cr,A as I,Aa as Ht,Ab as ir,Ad as ss,B as J,Ba as Pt,Bb as pr,Bd as es,C as K,Ca as St,Cb as cr,Cd as os,D as M,Da as Tt,Db as hr,Dd as as,E as N,Ea as Ut,Eb as mr,Ed as ns,F as O,Fa as $t,Fb as gr,Fd as is,Ga as kt,Gb as dr,Gd as ps,Ha as Ft,Hb as ur,Hd as cs,Ia as Lt,Ib as fr,Id as hs,Ja as Rt,Jb as xr,Jd as ms,Ka as qt,Kd as gs,La as vt,Ld as ds,Ma as zt,Md as us,Na as Gt,Nd as fs,Oa as It,Od as xs,Pa as Jt,Pd as ys,Qa as Kt,Ra as Mt,Sa as Nt,Ta as Ot,U as Q,Ua as Qt,Uc as yr,V,Va as Vt,Vc as wr,W,Wa as Wt,Wc as Ar,X,Xa as Xt,Xc as br,Y,Ya as Yt,Yc as lr,Z,Za as Zt,Zc as jr,_,_a as _t,_c as Br,a as n,aa as rt,ab as rr,ad as Dr,b as x,ba as st,bb as sr,bd as Er,c as y,ca as et,cb as er,cd as Hr,d as w,da as ot,db as or,dd as Pr,e as A,ea as at,eb as ar,ed as Sr,f as b,fa as nt,fb as nr,fd as Tr,g as l,ga as it,gd as Ur,h as j,ha as pt,hd as $r,i as B,ia as ct,id as kr,ja as ht,jd as Fr,k as C,ka as mt,kd as Lr,l as D,la as gt,ld as Rr,m as E,ma as dt,md as qr,n as H,na as ut,nd as vr,o as P,oa as ft,od as Mr,pa as xt,pd as Nr,q as T,qa as yt,qd as Or,r as U,ra as wt,rd as Qr,s as $,sa as At,sd as Vr,t as k,ta as bt,td as Wr,u as F,ua as lt,ud as Xr,v as L,va as jt,vd as Yr,w as R,wa as Bt,wd as Zr,x as q,xa as Ct,xd as _r,y as v,ya as Dt,yd as ts,z as G,za as Et,zd as rs}from"./chunk-
|
|
25
|
+
import{$ as tt,$a as tr,$c as Cr,A as I,Aa as Ht,Ab as ir,Ad as ss,B as J,Ba as Pt,Bb as pr,Bd as es,C as K,Ca as St,Cb as cr,Cd as os,D as M,Da as Tt,Db as hr,Dd as as,E as N,Ea as Ut,Eb as mr,Ed as ns,F as O,Fa as $t,Fb as gr,Fd as is,Ga as kt,Gb as dr,Gd as ps,Ha as Ft,Hb as ur,Hd as cs,Ia as Lt,Ib as fr,Id as hs,Ja as Rt,Jb as xr,Jd as ms,Ka as qt,Kd as gs,La as vt,Ld as ds,Ma as zt,Md as us,Na as Gt,Nd as fs,Oa as It,Od as xs,Pa as Jt,Pd as ys,Qa as Kt,Ra as Mt,Sa as Nt,Ta as Ot,U as Q,Ua as Qt,Uc as yr,V,Va as Vt,Vc as wr,W,Wa as Wt,Wc as Ar,X,Xa as Xt,Xc as br,Y,Ya as Yt,Yc as lr,Z,Za as Zt,Zc as jr,_,_a as _t,_c as Br,a as n,aa as rt,ab as rr,ad as Dr,b as x,ba as st,bb as sr,bd as Er,c as y,ca as et,cb as er,cd as Hr,d as w,da as ot,db as or,dd as Pr,e as A,ea as at,eb as ar,ed as Sr,f as b,fa as nt,fb as nr,fd as Tr,g as l,ga as it,gd as Ur,h as j,ha as pt,hd as $r,i as B,ia as ct,id as kr,ja as ht,jd as Fr,k as C,ka as mt,kd as Lr,l as D,la as gt,ld as Rr,m as E,ma as dt,md as qr,n as H,na as ut,nd as vr,o as P,oa as ft,od as Mr,pa as xt,pd as Nr,q as T,qa as yt,qd as Or,r as U,ra as wt,rd as Qr,s as $,sa as At,sd as Vr,t as k,ta as bt,td as Wr,u as F,ua as lt,ud as Xr,v as L,va as jt,vd as Yr,w as R,wa as Bt,wd as Zr,x as q,xa as Ct,xd as _r,y as v,ya as Dt,yd as ts,z as G,za as Et,zd as rs}from"./chunk-6WKYPMAI.js";import{a as S,d as z,e as zr,f as Gr,g as Ir,h as Jr,i as Kr}from"./chunk-JRXZBVXH.js";import"./chunk-4SACVMDH.js";import{_ as u,a as t,aa as a,ba as f}from"./chunk-ZIKV2LUM.js";var e=["sha-1","sha-256","sha-384","sha-512"],r=class{static{t(this,"BaseCryptoBeta")}};var o=class extends r{static{t(this,"WorkerCryptoBeta")}async digest(s,p){if(n("runtime.crypto-beta"),!e.includes(s.toLowerCase()))throw new a(`Algorithm ${s} is not supported. Try using ${e.join(", ")}`);let c=new TextEncoder().encode(p),h=await crypto.subtle.digest(s,c);return Array.from(new Uint8Array(h)).map(m=>m.toString(16).padStart(2,"0")).join("")}};export{Dt as AIGatewayAnthropicToOpenAIInboundPolicy,Et as AIGatewayAuthInboundPolicy,I as AIGatewayMeteringInboundPolicy,Ht as AIGatewayOpenAIToAnthropicOutboundPolicy,Pt as AIGatewaySemanticCacheInboundPolicy,St as AIGatewaySemanticCacheOutboundPolicy,Tt as AIGatewayUsageTrackerPolicy,rt as AWSLoggingPlugin,Ut as AkamaiAIFirewallInboundPolicy,wt as AkamaiApiSecurityPlugin,$t as AkamaiFirewallForAiInboundPolicy,kt as AkamaiFirewallForAiOutboundPolicy,Lt as AmberfloMeteringInboundPolicy,Ft as AmberfloMeteringPolicy,qt as ApiAuthKeyInboundPolicy,xs as ApiKeyConsumerClient,Rt as ApiKeyInboundPolicy,dt as AuditLogDataStaxProvider,ut as AuditLogPlugin,zt as Auth0JwtInboundPolicy,Gt as AuthZenInboundPolicy,K as AwsLambdaHandlerExtensions,It as AxiomaticsAuthZInboundPolicy,bt as AzureBlobPlugin,lt as AzureEventHubsRequestLoggerPlugin,At as BackgroundDispatcher,ys as BackgroundLoader,Jt as BasicAuthInboundPolicy,$r as BasicRateLimitInboundPolicy,P as BatchDispatch,Kt as BrownoutInboundPolicy,Mt as CachingInboundPolicy,Nt as ChangeMethodInboundPolicy,Ot as ClearHeadersInboundPolicy,Qt as ClearHeadersOutboundPolicy,Vt as ClerkJwtInboundPolicy,Wt as CognitoJwtInboundPolicy,Xt as CometOpikTracingInboundPolicy,Yt as ComplexRateLimitInboundPolicy,Zt as CompositeInboundPolicy,_t as CompositeOutboundPolicy,f as ConfigurationError,E as ContentTypes,v as ContextData,o as CryptoBeta,tr as CurityPhantomTokenInboundPolicy,F as DataDogLoggingPlugin,ct as DataDogMetricsPlugin,st as DynaTraceLoggingPlugin,ht as DynatraceMetricsPlugin,rr as FirebaseJwtInboundPolicy,sr as FormDataToJsonInboundPolicy,er as GalileoTracingInboundPolicy,or as GeoFilterInboundPolicy,k as GoogleCloudLoggingPlugin,G as Handler,ar as HttpDeprecationOutboundPolicy,B as HttpProblems,b as HttpStatusCode,Bt as HydrolixRequestLoggerPlugin,U as InboundPolicy,nr as JWTScopeValidationInboundPolicy,ft as JwtServicePlugin,et as LokiLoggingPlugin,L as LookupResult,Br as MTLSAuthInboundPolicy,yr as McpAuth0OAuthInboundPolicy,ir as McpClerkOAuthInboundPolicy,pr as McpCognitoOAuthInboundPolicy,cr as McpEntraOAuthInboundPolicy,xt as McpGatewayOAuthProtectedResourcePlugin,hr as McpGoogleOAuthInboundPolicy,mr as McpKeycloakOAuthInboundPolicy,gr as McpLogtoOAuthInboundPolicy,wr as McpOAuthInboundPolicy,dr as McpOktaOAuthInboundPolicy,ur as McpOneLoginOAuthInboundPolicy,fr as McpPingOAuthInboundPolicy,xr as McpWorkosOAuthInboundPolicy,w as MemoryZoneReadThroughCache,Ar as MockApiInboundPolicy,lr as MoesifInboundPolicy,jr as MonetizationInboundPolicy,ot as NewRelicLoggingPlugin,mt as NewRelicMetricsPlugin,yt as OAuthProtectedResourcePlugin,gt as OTelMetricsPlugin,Cr as OktaFGAAuthZInboundPolicy,Dr as OktaJwtInboundPolicy,Er as OpenFGAAuthZInboundPolicy,vt as OpenIdJwtInboundPolicy,Hr as OpenMeterInboundPolicy,$ as OutboundPolicy,j as ProblemResponseFormatter,Pr as PromptInjectionDetectionOutboundPolicy,Sr as PropelAuthJwtInboundPolicy,Tr as QueryParamToHeaderInboundPolicy,Ur as QuotaInboundPolicy,$r as RateLimitInboundPolicy,kr as ReadmeMetricsInboundPolicy,Fr as RemoveHeadersInboundPolicy,Lr as RemoveHeadersOutboundPolicy,Rr as RemoveQueryParamsInboundPolicy,qr as ReplaceStringOutboundPolicy,Ct as RequestLoggerPlugin,vr as RequestSizeLimitInboundPolicy,Mr as RequestValidationInboundPolicy,Or as RequireOriginInboundPolicy,R as ResponseSendingEvent,q as ResponseSentEvent,a as RuntimeError,u as SYSTEM_LOGGER,Nr as SchemaBasedRequestValidation,Qr as SecretMaskingOutboundPolicy,T as SemanticAttributes,Vr as SemanticCacheInboundPolicy,fs as ServiceProviderImpl,Wr as SetBodyInboundPolicy,Xr as SetHeadersInboundPolicy,Yr as SetHeadersOutboundPolicy,Zr as SetQueryParamsInboundPolicy,_r as SetStatusOutboundPolicy,ts as SetUpstreamApiKeyInboundPolicy,rs as SleepInboundPolicy,at as SplunkLoggingPlugin,A as StreamingZoneCache,ss as StripeWebhookVerificationInboundPolicy,nt as SumoLogicLoggingPlugin,es as SupabaseJwtInboundPolicy,S as SystemRouteName,C as TelemetryPlugin,os as UpstreamAzureAdServiceAuthInboundPolicy,as as UpstreamFirebaseAdminAuthInboundPolicy,ns as UpstreamFirebaseUserAuthInboundPolicy,ps as UpstreamGcpFederatedAuthInboundPolicy,cs as UpstreamGcpJwtInboundPolicy,hs as UpstreamGcpServiceAuthInboundPolicy,ms as UpstreamZuploJwtAuthInboundPolicy,it as VMWareLogInsightLoggingPlugin,gs as ValidateJsonSchemaInbound,ds as WebBotAuthInboundPolicy,us as XmlToJsonOutboundPolicy,y as ZoneCache,pt as ZuploMcpSdk,D as ZuploRequest,is as ZuploServices,J as aiGatewayHandler,x as apiServices,M as awsLambdaHandler,jt as defaultGenerateHydrolixEntry,z as environment,Gr as getIdForParameterSchema,Jr as getIdForRefSchema,Ir as getIdForRequestBodySchema,zr as getRawOperationDataIdentifierName,l as httpStatuses,N as legacyDevPortalHandler,Q as mcpServerHandler,V as openApiSpecHandler,W as redirectHandler,O as redirectLegacyDevPortal,Kr as sanitizedIdentifierName,H as serialize,br as setMoesifContext,n as trackFeature,Y as urlForwardHandler,Z as urlRewriteHandler,_ as webSocketHandler,tt as webSocketPipelineHandler,X as zuploServiceProxy};
|
|
26
26
|
//# sourceMappingURL=index.js.map
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{$b as Ye,Ab as Ds,Ac as H,Bb as Hs,Bc as ao,Cb as zs,Cc as so,Db as Ls,Dc as hr,Eb as Bs,Ec as co,Fb as js,Fc as uo,G as Un,Gb as Ns,Gc as gr,H as l,Hb as Gs,Hc as _e,I as kn,Ib as $s,Ic as lo,J as cr,Jb as Fs,Jc as po,K as te,Kb as Bn,Kc as mo,L as Pn,Lb as jn,Lc as fo,M as y,Mb as Nn,Mc as ho,N as ue,Nb as xt,Nc as go,O as vt,Ob as dr,Oc as yo,P as Tn,Pb as At,Pc as b,Q as En,Qb as Ut,Qc as x,R as On,Rb as We,Rc as pe,S as d,Sb as Gn,Sc as U,T as $,Tb as $n,Tc as wo,Ub as Fn,Uc as Zs,Vb as Ve,Vc as Ks,Wb as Zn,Xb as kt,Yb as Kn,Z as Mn,Zb as ur,_b as Jn,a as bt,ac as Pt,bc as Wn,cc as Vn,dc as Yn,ec as Xn,fc as J,gb as we,gc as M,hb as T,hc as Qn,i as ye,ib as qn,ic as eo,j as In,jb as Dn,jc as R,kb as k,kc as ne,l as xn,lb as Hn,lc as Tt,mb as g,mc as B,nb as ke,nc as Z,ob as Pe,oc as to,p as An,pb as Te,pc as ro,qb as Ee,qc as Et,r as Ct,rb as St,rc as no,sb as zn,sc as oe,tb as F,tc as lr,ub as Ln,uc as pr,vb as re,vc as oo,wb as w,wc as Ot,xb as It,xc as mr,yb as D,yc as fr,zb as le,zc as io}from"../chunk-AQGS5CID.js";import{d as sr}from"../chunk-JRXZBVXH.js";import{a as C}from"../chunk-4SACVMDH.js";import{$ as de,a as n,aa as h,ba as q,ca as Sn,da as Rt}from"../chunk-ZIKV2LUM.js";$();function Js(e){let t=Ut.safeParse(e);return t.success?t.data.id:void 0}n(Js,"parseJsonRpcRequestId");function _o(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Js(t)}catch{return}}n(_o,"readJsonRpcRequestIdFromBody");function Mt(e){return Gn.parse({jsonrpc:At,...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(Mt,"jsonRpcErrorResponse");function Ro(e){return new Fn([$n.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Ro,"urlElicitationRequiredError");var qt=d.record(d.string(),d.unknown()),Ws=d.record(d.string(),d.unknown()),Vs=d.object({name:d.string().min(1),description:d.string().min(1).optional(),annotations:Ws.optional(),_meta:qt.optional()}).strict(),Ys=d.object({name:d.string().min(1),description:d.string().min(1).optional(),_meta:qt.optional()}).strict(),Xs=d.object({uri:d.string().min(1),name:d.string().min(1).optional(),description:d.string().min(1).optional(),mimeType:d.string().min(1).optional(),_meta:qt.optional()}).strict(),Qs=d.object({uriTemplate:d.string().min(1),name:d.string().min(1).optional(),description:d.string().min(1).optional(),mimeType:d.string().min(1).optional(),_meta:qt.optional()}).strict(),ec=d.array(d.union([d.string(),Vs])),tc=d.array(d.union([d.string(),Ys])),rc=d.array(d.union([d.string(),Xs])),nc=d.array(d.union([d.string(),Qs])),oc=d.object({tools:ec.optional(),prompts:tc.optional(),resources:rc.optional(),resourceTemplates:nc.optional()}).strict(),wr=[{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 ic(e,t){return qn(oc,e,`MCP capability filter policy "${t}"`)}n(ic,"parseMcpCapabilityFilterOptions");function z(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(z,"isRecord");function ac(e,t){if(!z(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(ac,"readParamString");function _r(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(_r,"readRequestId");function So(e){return e===void 0?void 0:JSON.stringify(e)}n(So,"requestIdKey");function sc(e){let t={};for(let r of wr){let o=e[r.option];if(o===void 0)continue;let i=new Map;for(let a of o){let s=lc(a,r.itemProperty);s!==void 0&&i.set(s.key,s)}t[r.option]=i}return t}n(sc,"buildProjectionMaps");function Rr(e){return wr.find(t=>t.listMethod===e)}n(Rr,"findListRule");function cc(e){return e.requests.some(t=>{if(!z(t))return!1;let r=Rr(t.method);return r!==void 0&&e.projectionMaps[r.option]!==void 0})}n(cc,"shouldFilterListResponses");function dc(e){for(let t of wr){let r=e.projectionMaps[t.option];if(r!==void 0)for(let o of t.directMethods){if(e.request.method!==o.method)continue;let i=ac(e.request.params,o.paramProperty);if(i!==void 0&&!r.has(i))return{id:_r(e.request)}}}}n(dc,"findDisallowedDirectAccess");function uc(e){return Response.json(Mt({id:e,error:{code:We.MethodNotFound,message:"Method not found"}}))}n(uc,"methodNotFoundResponse");function lc(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!z(e))return;let r=e[t];if(typeof r=="string")return{key:r,overlay:e}}n(lc,"buildProjection");function bo(e){let t=e.base[e.property],r=e.overlay[e.property];return z(r)?z(t)?{...t,...r}:r:t}n(bo,"mergeRecordProperty");function pc(e,t){let r={...e,...t.overlay},o=bo({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let i=bo({base:e,overlay:t.overlay,property:"_meta"});return i!==void 0&&(r._meta=i),r}n(pc,"applyProjection");function Co(e,t,r){if(!z(e))return e;let o=e.result;if(!z(o))return e;let i=o[t.resultProperty];return!Array.isArray(i)||!i.every(a=>z(a)&&typeof a[t.itemProperty]=="string")?e:{...e,result:{...o,[t.resultProperty]:i.flatMap(a=>{if(!z(a))return[];let s=a[t.itemProperty];if(typeof s!="string")return[];let c=r.get(s);return c===void 0?[]:[pc(a,c)]})}}}n(Co,"filterAndProjectItems");function mc(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!z(r))continue;let o=Rr(r.method),i=_r(r),a=So(i);o!==void 0&&a!==void 0&&t.set(a,o)}return t}n(mc,"buildListRulesByResponseId");function fc(e){if(Array.isArray(e.responseBody)){let o=mc(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(i=>{if(!z(i)||"error"in i)return i;let a=So(_r(i)),s=a===void 0?void 0:o.get(a),c=s===void 0?void 0:e.projectionMaps[s.option];return s===void 0||c===void 0?i:Co(i,s,c)})}if(!z(e.requestBody)||!z(e.responseBody)||"error"in e.responseBody)return e.responseBody;let t=Rr(e.requestBody.method),r=t===void 0?void 0:e.projectionMaps[t.option];return t===void 0||r===void 0?e.responseBody:Co(e.responseBody,t,r)}n(fc,"filterJsonRpcResponse");async function vo(e){return e.clone().json()}n(vo,"readJson");function hc(e){return e.headers.get("content-type")?.includes("json")??!1}n(hc,"isJsonResponse");var yr=class extends Ct{static{n(this,"McpCapabilityFilterInboundPolicy")}#e;constructor(t,r){let o=ic(t,r);super(o,r),this.#e=sc(o)}async handler(t,r){bt("policy.inbound.mcp-capability-filter");let o;try{o=await vo(t)}catch{return t}let i=Array.isArray(o)?o:[o];for(let a of i){if(!z(a))continue;let s=dc({request:a,projectionMaps:this.#e});if(s!==void 0)return uc(s.id)}return cc({requests:i,projectionMaps:this.#e})&&r.addResponseSendingHook(async a=>{if(!hc(a))return a;let s;try{s=await vo(a)}catch{return a}let c=fc({requestBody:o,responseBody:s,projectionMaps:this.#e});if(c===s)return a;let u=new Headers(a.headers);return u.delete("content-length"),new Response(JSON.stringify(c),{status:a.status,statusText:a.statusText,headers:u})}),t}};var br;br=globalThis.crypto;async function gc(e){return(await br).getRandomValues(new Uint8Array(e))}n(gc,"getRandomValues");async function yc(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await gc(e-o.length);for(let a of i)a<r&&(o+=t[a%t.length])}return o}n(yc,"random");async function wc(e){return await yc(e)}n(wc,"generateVerifier");async function _c(e){let t=await(await br).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(_c,"generateChallenge");async function Cr(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await wc(e),r=await _c(t);return{code_verifier:t,code_challenge:r}}n(Cr,"pkceChallenge");$();var E=kn().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:En.custom,message:"URL must be parseable",fatal:!0}),Un}).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"}),Dt=vt({resource:l().url(),authorization_servers:y(E).optional(),jwks_uri:l().url().optional(),scopes_supported:y(l()).optional(),bearer_methods_supported:y(l()).optional(),resource_signing_alg_values_supported:y(l()).optional(),resource_name:l().optional(),resource_documentation:l().optional(),resource_policy_uri:l().url().optional(),resource_tos_uri:l().url().optional(),tls_client_certificate_bound_access_tokens:te().optional(),authorization_details_types_supported:y(l()).optional(),dpop_signing_alg_values_supported:y(l()).optional(),dpop_bound_access_tokens_required:te().optional()}),Xe=vt({issuer:l(),authorization_endpoint:E,token_endpoint:E,registration_endpoint:E.optional(),scopes_supported:y(l()).optional(),response_types_supported:y(l()),response_modes_supported:y(l()).optional(),grant_types_supported:y(l()).optional(),token_endpoint_auth_methods_supported:y(l()).optional(),token_endpoint_auth_signing_alg_values_supported:y(l()).optional(),service_documentation:E.optional(),revocation_endpoint:E.optional(),revocation_endpoint_auth_methods_supported:y(l()).optional(),revocation_endpoint_auth_signing_alg_values_supported:y(l()).optional(),introspection_endpoint:l().optional(),introspection_endpoint_auth_methods_supported:y(l()).optional(),introspection_endpoint_auth_signing_alg_values_supported:y(l()).optional(),code_challenge_methods_supported:y(l()).optional(),client_id_metadata_document_supported:te().optional()}),Rc=vt({issuer:l(),authorization_endpoint:E,token_endpoint:E,userinfo_endpoint:E.optional(),jwks_uri:E,registration_endpoint:E.optional(),scopes_supported:y(l()).optional(),response_types_supported:y(l()),response_modes_supported:y(l()).optional(),grant_types_supported:y(l()).optional(),acr_values_supported:y(l()).optional(),subject_types_supported:y(l()),id_token_signing_alg_values_supported:y(l()),id_token_encryption_alg_values_supported:y(l()).optional(),id_token_encryption_enc_values_supported:y(l()).optional(),userinfo_signing_alg_values_supported:y(l()).optional(),userinfo_encryption_alg_values_supported:y(l()).optional(),userinfo_encryption_enc_values_supported:y(l()).optional(),request_object_signing_alg_values_supported:y(l()).optional(),request_object_encryption_alg_values_supported:y(l()).optional(),request_object_encryption_enc_values_supported:y(l()).optional(),token_endpoint_auth_methods_supported:y(l()).optional(),token_endpoint_auth_signing_alg_values_supported:y(l()).optional(),display_values_supported:y(l()).optional(),claim_types_supported:y(l()).optional(),claims_supported:y(l()).optional(),service_documentation:l().optional(),claims_locales_supported:y(l()).optional(),ui_locales_supported:y(l()).optional(),claims_parameter_supported:te().optional(),request_parameter_supported:te().optional(),request_uri_parameter_supported:te().optional(),require_request_uri_registration:te().optional(),op_policy_uri:E.optional(),op_tos_uri:E.optional(),client_id_metadata_document_supported:te().optional()}),Ht=ue({...Rc.shape,...Xe.pick({code_challenge_methods_supported:!0}).shape}),Oe=ue({access_token:l(),id_token:l().optional(),token_type:l(),expires_in:On.number().optional(),scope:l().optional(),refresh_token:l().optional()}).strip(),xo=ue({error:l(),error_description:l().optional(),error_uri:l().optional()}),Io=E.optional().or(Tn("").transform(()=>{})),bc=ue({redirect_uris:y(E),token_endpoint_auth_method:l().optional(),grant_types:y(l()).optional(),response_types:y(l()).optional(),client_name:l().optional(),client_uri:E.optional(),logo_uri:Io,scope:l().optional(),contacts:y(l()).optional(),tos_uri:Io,policy_uri:l().optional(),jwks_uri:E.optional(),jwks:Pn().optional(),software_id:l().optional(),software_version:l().optional(),software_statement:l().optional()}).strip(),zt=ue({client_id:l(),client_secret:l().optional(),client_id_issued_at:cr().optional(),client_secret_expires_at:cr().optional()}).strip(),Qe=bc.merge(zt),Vf=ue({error:l(),error_description:l().optional()}).strip(),Yf=ue({token:l(),token_type_hint:l().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 Uo({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(Uo,"checkResourceAllowed");var A=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}},et=class extends A{static{n(this,"InvalidRequestError")}};et.errorCode="invalid_request";var Re=class extends A{static{n(this,"InvalidClientError")}};Re.errorCode="invalid_client";var be=class extends A{static{n(this,"InvalidGrantError")}};be.errorCode="invalid_grant";var Ce=class extends A{static{n(this,"UnauthorizedClientError")}};Ce.errorCode="unauthorized_client";var tt=class extends A{static{n(this,"UnsupportedGrantTypeError")}};tt.errorCode="unsupported_grant_type";var rt=class extends A{static{n(this,"InvalidScopeError")}};rt.errorCode="invalid_scope";var nt=class extends A{static{n(this,"AccessDeniedError")}};nt.errorCode="access_denied";var ie=class extends A{static{n(this,"ServerError")}};ie.errorCode="server_error";var ot=class extends A{static{n(this,"TemporarilyUnavailableError")}};ot.errorCode="temporarily_unavailable";var it=class extends A{static{n(this,"UnsupportedResponseTypeError")}};it.errorCode="unsupported_response_type";var at=class extends A{static{n(this,"UnsupportedTokenTypeError")}};at.errorCode="unsupported_token_type";var st=class extends A{static{n(this,"InvalidTokenError")}};st.errorCode="invalid_token";var ct=class extends A{static{n(this,"MethodNotAllowedError")}};ct.errorCode="method_not_allowed";var dt=class extends A{static{n(this,"TooManyRequestsError")}};dt.errorCode="too_many_requests";var ve=class extends A{static{n(this,"InvalidClientMetadataError")}};ve.errorCode="invalid_client_metadata";var ut=class extends A{static{n(this,"InsufficientScopeError")}};ut.errorCode="insufficient_scope";var lt=class extends A{static{n(this,"InvalidTargetError")}};lt.errorCode="invalid_target";var ko={[et.errorCode]:et,[Re.errorCode]:Re,[be.errorCode]:be,[Ce.errorCode]:Ce,[tt.errorCode]:tt,[rt.errorCode]:rt,[nt.errorCode]:nt,[ie.errorCode]:ie,[ot.errorCode]:ot,[it.errorCode]:it,[at.errorCode]:at,[st.errorCode]:st,[ct.errorCode]:ct,[dt.errorCode]:dt,[ve.errorCode]:ve,[ut.errorCode]:ut,[lt.errorCode]:lt};function Cc(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(Cc,"isClientAuthMethod");var vr="code",Sr="S256";function vc(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Cc(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(vc,"selectClientAuthMethod");function Sc(e,t,r,o){let{client_id:i,client_secret:a}=t;switch(e){case"client_secret_basic":Ic(i,a,r);return;case"client_secret_post":xc(i,a,o);return;case"none":Ac(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(Sc,"applyClientAuthentication");function Ic(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(Ic,"applyBasicAuth");function xc(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(xc,"applyPostAuth");function Ac(e,t){t.set("client_id",e)}n(Ac,"applyPublicAuth");async function To(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=xo.parse(JSON.parse(r)),{error:i,error_description:a,error_uri:s}=o,c=ko[i]||ie;return new c(a||"",s)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new ie(i)}}n(To,"parseErrorResponse");async function Ar(e,t){try{return await Ir(e,t)}catch(r){if(r instanceof Re||r instanceof Ce)return await e.invalidateCredentials?.("all"),await Ir(e,t);if(r instanceof be)return await e.invalidateCredentials?.("tokens"),await Ir(e,t);throw r}}n(Ar,"auth");async function Ir(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:i,fetchFn:a}){let s=await e.discoveryState?.(),c,u,p,f=i;if(!f&&s?.resourceMetadataUrl&&(f=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(u=s.authorizationServerUrl,c=s.resourceMetadata,p=s.authorizationServerMetadata??await Mo(u,{fetchFn:a}),!c)try{c=await Oo(t,{resourceMetadataUrl:f},a)}catch{}(p!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:f?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}else{let P=await Oc(t,{resourceMetadataUrl:f,fetchFn:a});u=P.authorizationServerUrl,p=P.authorizationServerMetadata,c=P.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:f?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}let _=await Uc(t,e,c),S=o||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,I=await Promise.resolve(e.clientInformation());if(!I){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let P=p?.client_id_metadata_document_supported===!0,O=e.clientMetadataUrl;if(O&&!Ur(O))throw new ve(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${O}`);if(P&&O)I={client_id:O},await e.saveClientInformation?.(I);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let vn=await zc(u,{metadata:p,clientMetadata:e.clientMetadata,scope:S,fetchFn:a});await e.saveClientInformation(vn),I=vn}}let G=!e.redirectUrl;if(r!==void 0||G){let P=await Hc(e,u,{metadata:p,resource:_,authorizationCode:r,fetchFn:a});return await e.saveTokens(P),"AUTHORIZED"}let K=await e.tokens();if(K?.refresh_token)try{let P=await Dc(u,{metadata:p,clientInformation:I,refreshToken:K.refresh_token,resource:_,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(P),"AUTHORIZED"}catch(P){if(!(!(P instanceof A)||P instanceof ie))throw P}let Q=e.state?await e.state():void 0,{authorizationUrl:Je,codeVerifier:ee}=await Mc(u,{metadata:p,clientInformation:I,state:Q,redirectUrl:e.redirectUrl,scope:S,resource:_});return await e.saveCodeVerifier(ee),await e.redirectToAuthorization(Je),"REDIRECT"}n(Ir,"authInternal");function Ur(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(Ur,"isHttpsUrl");async function Uc(e,t,r){let o=Ao(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!Uo({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(Uc,"selectResourceURL");function Eo(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let i=xr(e,"resource_metadata")||void 0,a;if(i)try{a=new URL(i)}catch{}let s=xr(e,"scope")||void 0,c=xr(e,"error")||void 0;return{resourceMetadataUrl:a,scope:s,error:c}}n(Eo,"extractWWWAuthenticateParams");function xr(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(xr,"extractFieldFromWwwAuth");async function Oo(e,t,r=fetch){let o=await Tc(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 Dt.parse(await o.json())}n(Oo,"discoverOAuthProtectedResourceMetadata");async function kr(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?kr(e,void 0,r):void 0;throw o}}n(kr,"fetchWithCorsRetry");function kc(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(kc,"buildWellKnownPath");async function Po(e,t,r=fetch){return await kr(e,{"MCP-Protocol-Version":t},r)}n(Po,"tryMetadataDiscovery");function Pc(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(Pc,"shouldAttemptFallback");async function Tc(e,t,r,o){let i=new URL(e),a=o?.protocolVersion??dr,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let u=kc(t,i.pathname);s=new URL(u,o?.metadataServerUrl??i),s.search=i.search}let c=await Po(s,a,r);if(!o?.metadataUrl&&Pc(c,i.pathname)){let u=new URL(`/.well-known/${t}`,i);c=await Po(u,a,r)}return c}n(Tc,"discoverMetadataWithFallback");function Ec(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(Ec,"buildDiscoveryUrls");async function Mo(e,{fetchFn:t=fetch,protocolVersion:r=dr}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=Ec(e);for(let{url:a,type:s}of i){let c=await kr(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"?Xe.parse(await c.json()):Ht.parse(await c.json())}}}n(Mo,"discoverAuthorizationServerMetadata");async function Oc(e,t){let r,o;try{r=await Oo(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 Mo(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(Oc,"discoverOAuthServerInfo");async function Mc(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(vr))throw new Error(`Incompatible auth server: does not support response type ${vr}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Sr))throw new Error(`Incompatible auth server: does not support code challenge method ${Sr}`)}else c=new URL("/authorize",e);let u=await Cr(),p=u.code_verifier,f=u.code_challenge;return c.searchParams.set("response_type",vr),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",f),c.searchParams.set("code_challenge_method",Sr),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:p}}n(Mc,"startAuthorization");function qc(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(qc,"prepareAuthorizationCodeRequest");async function qo(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),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(a&&r.set("resource",a.href),i)await i(u,r,c,t);else if(o){let f=t?.token_endpoint_auth_methods_supported??[],_=vc(o,f);Sc(_,o,u,r)}let p=await(s??fetch)(c,{method:"POST",headers:u,body:r});if(!p.ok)throw await To(p);return Oe.parse(await p.json())}n(qo,"executeTokenRequest");async function Dc(e,{metadata:t,clientInformation:r,refreshToken:o,resource:i,addClientAuthentication:a,fetchFn:s}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),u=await qo(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:a,resource:i,fetchFn:s});return{refresh_token:o,...u}}n(Dc,"refreshAuthorization");async function Hc(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 p=await e.codeVerifier();c=qc(i,p,e.redirectUrl)}let u=await e.clientInformation();return qo(t,{metadata:r,tokenRequestParams:c,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(Hc,"fetchToken");async function zc(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 To(s);return Qe.parse(await s.json())}n(zc,"registerClient");var Pr="zuplo.com",Lc=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),Bc=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Do(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(Do,"s2FaviconHref");function jc(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(jc,"strictFaviconHref");var Lt=Do(Pr);function Tr(e){let t=e.toLowerCase();return t===Pr||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Do(Pr):jc(e)}n(Tr,"resolveIconHref");function Nc(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(Nc,"hostnameFromHost");function Gc(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(Gc,"isLocalOrAddressHost");function $c(e){let t=Nc(e).toLowerCase().replace(/\.$/,"");if(Gc(t)||Bc.some(a=>t===a.slice(1)||t.endsWith(a)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let o=r.slice(-2).join("."),i=Lc.has(o)?3:2;return r.slice(-i).join(".")}n($c,"inferFaviconDomain");function Er(e){return{src:Tr($c(e)),mimeType:"image/png",sizes:["128x128"]}}n(Er,"resolveMcpFaviconIcon");function Bt(e){try{return Er(new URL(e).host)}catch{return}}n(Bt,"resolveMcpFaviconIconFromUrl");function Me(e){let t=J().connectionsById.get(e);if(!t)throw new q(`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(Me,"getUpstreamServerConfig");function Fc(e){let t=J().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new q(`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(Fc,"resolveUpstreamAuthProfileId");function Or(e){Fc(e);let t=J().connectionsById.get(e.upstreamServerId);if(!t)throw new q(`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(Or,"getUpstreamAuthConfig");function qe(e,t){return Or({upstreamServerId:e,authProfileId:t})}n(qe,"requireUpstreamOAuthConfig");function W(e){return new h({message:e,extensionMembers:{[g]:"invalid_request"}})}n(W,"invalidOutboundUrl");function Zc(){let e=sr.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP??globalThis.process?.env?.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP;return typeof e=="string"&&e==="1"}n(Zc,"isTestOnlyAllowHttpLoopbackIdpEnabled");function Kc(){let e=sr.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_CIMD??globalThis.process?.env?.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_CIMD;return typeof e=="string"&&e==="1"}n(Kc,"isTestOnlyAllowHttpLoopbackCimdEnabled");var Jc=new Set(["undefined","null","nan"]);function qr(e,t){if(!e.hostname)throw W(`Outbound URL has an empty hostname (got ${JSON.stringify(t)}). This typically indicates an unset $env(...) reference or a JS template literal coercing \`undefined\` into a URL. Check the policy options or runtime config that produced this URL.`);if(Jc.has(e.hostname.toLowerCase()))throw W(`Outbound URL hostname is ${JSON.stringify(e.hostname)} (from ${JSON.stringify(t)}). This almost always means an environment variable referenced by $env(...) is unset and a JS value was string-coerced into a URL. Set the missing env var or fix the policy option that produced this URL.`)}n(qr,"assertSafeOutboundHostname");var Wc=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),Vc=[{first:0},{first:10},{first:127},{first:169,secondMin:254,secondMax:254},{first:172,secondMin:16,secondMax:31},{first:192,secondMin:168,secondMax:168},{first:100,secondMin:64,secondMax:127},{first:224,firstMax:239},{first:240,firstMax:255}];function Ho(e){if(!/^\d+\.\d+\.\d+\.\d+$/.test(e))return;let t=e.split(".").map(r=>Number(r));if(!(t.length!==4||t.some(r=>Number.isNaN(r)||r<0||r>255)))return t}n(Ho,"parseIpv4Octets");function Yc([e,t],r){let o=r.firstMax??r.first;return e<r.first||e>o?!1:r.secondMin===void 0||r.secondMax===void 0?!0:t>=r.secondMin&&t<=r.secondMax}n(Yc,"ipv4RangeMatches");function zo(e){let t=Ho(e);return t!==void 0&&Vc.some(r=>Yc(t,r))}n(zo,"isPrivateIpv4");function Mr(e){if(!e||e.length>4)return;let t=Number.parseInt(e,16);return Number.isNaN(t)||t<0||t>65535?void 0:t}n(Mr,"parseIpv6Word");function Xc(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}n(Xc,"formatIpv4FromWords");function Qc(e){let t=e.slice(7),r=Ho(t);if(r!==void 0)return r.join(".");let[o,i,a]=t.split(":"),s=Mr(o),c=Mr(i);return a===void 0&&s!==void 0&&c!==void 0?Xc(s,c):void 0}n(Qc,"parseIpv6MappedIpv4");function ed(e){return Mr(e.split(":").find(Boolean))}n(ed,"readFirstIpv6Hextet");function td(e){let t=we(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let o=Qc(t);return o===void 0||zo(o)}let r=ed(t);return r===void 0?!1:(r&65024)===64512||(r&65472)===65152}n(td,"isPrivateIpv6");function Dr(e){let t=we(e);return Wc.has(t)||t.endsWith(".internal")||zo(t)||td(t)}n(Dr,"isBlockedOutboundHostname");function jt(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw W(`Unsupported outbound protocol: ${t.protocol}`);qr(t,e);let r=T(t);if(t.protocol==="http:"&&!r)throw W("Configured outbound HTTP URLs must target loopback hosts.");let o=we(t.hostname);if(!r&&Dr(o))throw W(`Blocked outbound host: ${o}`);return t}n(jt,"validateConfiguredOutboundUrl");function Lo(e){let t=new URL(e),r=T(t),o=r&&Zc();if(t.protocol!=="https:"&&!o)throw W("Identity provider URLs must use https.");if(t.username||t.password||t.search||t.hash)throw W("Identity provider URLs must not include credentials, query params, or fragments.");qr(t,e);let i=we(t.hostname);if(!r&&Dr(i))throw W(`Blocked identity provider host: ${i}`);return t}n(Lo,"validateIdentityProviderUrl");function Bo(e,t){let r=new URL(e),o=r.protocol==="http:"&&T(r)&&Kc();if(r.protocol!=="https:"&&!o||r.pathname==="/"||r.username||r.password||r.hash)throw W(`CIMD ${t} must be an HTTPS URL with a path and no credentials or fragment.`);if(qr(r,e),!o&&Dr(r.hostname))throw W(`CIMD ${t} points at a blocked host.`);return r}n(Bo,"validateCimdUrl");function Nt(e){return Bo(e,"client_id")}n(Nt,"validateCimdClientMetadataUrl");function Se(e){return Bo(e,"jwks_uri")}n(Se,"validateCimdClientJwksUrl");function jo(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let r=n(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}n(jo,"mergeAbortSignals");async function rd(e){try{await e.cancel()}catch{}}n(rd,"cancelReader");async function Gt(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],i=0,a=await r.read();for(;!a.done;){let u=a.value;if(i+=u.byteLength,i>t.maxBytes)throw await rd(r),t.createLimitError();o.push(u),a=await r.read()}let s=new Uint8Array(i),c=0;for(let u of o)s.set(u,c),c+=u.byteLength;return s}n(Gt,"readBoundedByteStream");var nd=2,od=1024*1024,id=1e4,ad=new Set([301,302,303,307,308]),sd=["authorization","proxy-authorization","cookie","cookie2"];function Hr(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Hr,"readRequestUrl");function De(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(De,"readRequestMethod");function cd(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 new h({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}})}n(cd,"assertContentLengthWithinLimit");async function dd(e,t,r){return cd(e,t,r),Gt(e.body,{maxBytes:t,createLimitError:n(()=>new h({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}}),"createLimitError")})}n(dd,"readBoundedResponseBody");function ud(e,t){let r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}n(ud,"responseFromBufferedBody");function ld(e,t){if(!ad.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(ld,"resolveRedirectUrl");function No(e,t){try{return t.validateUrl(e)}catch(r){throw new h({message:"Outbound URL was not allowed.",extensionMembers:{[g]:t.problemCode}},{cause:r})}}n(No,"validateOutboundUrl");function pd(e,t){throw e instanceof h&&St(e.extensionMembers?.[g])?e:new h({message:"Outbound fetch failed.",extensionMembers:{[g]:t}},{cause:e})}n(pd,"normalizeFetchError");function pt(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[o,i]of Object.entries(t.extra))i!==void 0&&(r[o]=i);t.error!==void 0&&B(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(pt,"logOutboundFailure");async function md(e,t,r,o,i,a,s){let c=De(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";pt(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:i,method:c,host:Z(a),error:u,extra:{abortReason:s()}}),pd(u,i)}}n(md,"fetchWithNormalizedError");function fd(e){if(e.redirects>=e.maxRedirects)throw new h({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[g]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new h({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[g]:e.problemCode}})}n(fd,"assertRedirectAllowed");function hd(e,t){let r=new Headers(e);for(let o of sd)r.delete(o);for(let o of t)r.delete(o);return r}n(hd,"stripCrossOriginHeaders");function gd(e,t,r,o,i){let a={...e,method:t,redirect:"manual",signal:r};return o&&(a.headers=hd(e.headers,i)),a}n(gd,"buildRedirectInit");function yd(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(yd,"buildInitialRequestInit");function wd(e){let t=De(e.currentInput,e.currentInit);fd({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=No(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),i=r.origin!==o.origin,a=r.toString();return{currentInput:a,currentUrl:a,currentInit:gd(e.currentInit,t,e.signal,i,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(wd,"followRedirect");async function zr(e,t,r){let o=r.problemCode??"invalid_request",i=r.maxRedirects??nd,a=r.maxResponseBytes??od,s=r.timeoutMs??id,c=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,f=new AbortController,_=jo(f,t.signal),S=!1,I=setTimeout(()=>{S=!0,f.abort()},s),G=e,K=yd(e,t,f.signal),Q;try{Q=No(Hr(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(ee){throw pt(p,{event:"outbound_url_blocked",problemCode:o,method:De(e,t),host:Z(Hr(e)),error:ee}),clearTimeout(I),_?.(),ee}let Je=0;try{for(;;){let ee=await md(p,c,G,K,o,Q,()=>S?`timeout_after_${s}ms`:void 0),P=ld(ee,Q);if(P!==void 0)try{let O=wd({currentInput:G,currentInit:K,currentUrl:Q,redirectUrl:P,redirects:Je,maxRedirects:i,problemCode:o,validateUrl:r.validateUrl,signal:f.signal,additionalCrossOriginStrippedHeaders:u});G=O.currentInput,K=O.currentInit,Q=O.currentUrl,Je=O.redirects;continue}catch(O){throw pt(p,{event:"outbound_redirect_blocked",problemCode:o,method:De(G,K),host:Z(Q),error:O,extra:{redirects:Je,maxRedirects:i,redirectTargetHost:Z(P)}}),O}try{return ud(ee,await dd(ee,a,o))}catch(O){throw pt(p,{event:"outbound_response_size_exceeded",problemCode:o,method:De(G,K),host:Z(Q),error:O,extra:{maxResponseBytes:a,status:ee.status}}),O}}}finally{clearTimeout(I),_?.()}}n(zr,"runSafeOutboundExchange");async function $t(e,t,r){let o=await zr(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(i){throw pt(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:De(e,t),host:Z(Hr(e)),error:i,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new h({message:"Outbound JSON response could not be parsed.",extensionMembers:{[g]:r.problemCode??"invalid_request"}},{cause:i})}}n($t,"runSafeOutboundJsonExchange");function Go(e,t={},r={}){return zr(e,t,{...r,validateUrl:jt})}n(Go,"fetchConfiguredOutbound");function $o(e,t={},r={}){return $t(e,t,{...r,validateUrl:Lo})}n($o,"fetchIdentityProviderJson");function Fo(e,t={},r={}){return $t(e,t,{...r,validateUrl:Nt})}n(Fo,"fetchCimdClientMetadataJson");function Zo(e,t={},r={}){return $t(e,t,{...r,validateUrl:Se})}n(Zo,"fetchCimdClientJwksJson");$();import{errors as Qo,jwtVerify as ei,SignJWT as ti}from"jose";var L="zuplo-mcp-gateway",j=L,N="HS256";import{base64url as _d}from"jose";var Rd=new TextEncoder,bd="MCP gateway could not initialize secure key material.",Cd=32,Ko=new Map,Jo=new Map,vd;function Sd(){return vd??Sn.instance.authPrivateKey}n(Sd,"readAuthPrivateKey");function Wo(e){return new de(bd,e===void 0?void 0:{cause:e})}n(Wo,"createGeneratedKeyMaterialError");function Vo(e,t){let r=_d.decode(t);if(r.byteLength!==Cd)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(Vo,"decodeJwkKeyField");function Id(e){let t=Sd();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=Vo("d",r.d);Vo("x",r.x);let i=Rd.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(Id,"decodeGeneratedKeyMaterial");function xd(e){let t=Ko.get(e);return t||(t=Id(e),Ko.set(e,t)),t}n(xd,"getMasterKeyMaterial");async function V(e){let t=Jo.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(xd(e.keyMaterialPurpose));return Jo.set(e.purpose,r),r}n(V,"readCachedDerivedKey");var Ad="SHA-256";var Ud="zuplo-mcp-gateway:",kd=new TextEncoder,Yo=new WeakMap;async function me(e,t){let r=Yo.get(e);r||(r=new Map,Yo.set(e,r));let o=r.get(t);if(o)return o;let i=await Pd(e,t);return r.set(t,i),i}n(me,"deriveGatewaySigningKey");async function Pd(e,t){let r=Xo(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=kd.encode(`${Ud}${t}`),a=await crypto.subtle.deriveBits({name:"HKDF",hash:Ad,salt:new Uint8Array,info:Xo(i)},o,32*8);return new Uint8Array(a)}n(Pd,"hkdfExpand");function Xo(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(Xo,"copyToArrayBuffer");var ri=15*60,Td=15*60,Ed=Jn.extend({id:po}),Od=Ed.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ni=ur.extend({id:mo,purpose:d.literal("browser_connect")}),Md=ur.extend({purpose:d.literal("browser_connect")}),qd=ni.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),oi=ri*1e3;async function ii(){return V({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>me(e,"oauth-state"),"derive")})}n(ii,"getOAuthStateKey");async function ai(){return V({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>me(e,"browser-connect"),"derive")})}n(ai,"getBrowserConnectKey");async function si(e){let t=Math.floor(Date.now()/1e3)+ri;return new ti(e).setProtectedHeader({alg:N,typ:"JWT"}).setIssuer(L).setAudience(j).setIssuedAt().setExpirationTime(t).sign(await ii())}n(si,"signOAuthState");async function Ft(e){try{let{payload:t}=await ei(e,await ii(),{algorithms:[N],issuer:L,audience:j});return Od.parse(t)}catch(t){throw t instanceof Qo.JWTExpired?new h({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new h({message:"OAuth state could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(Ft,"verifyOAuthState");async function ci(e){let t=Math.floor(Date.now()/1e3)+Td,r=Md.parse(e),o=ni.parse({...r,id:yo()});return new ti(o).setProtectedHeader({alg:N,typ:"JWT"}).setIssuer(L).setAudience(j).setIssuedAt().setExpirationTime(t).sign(await ai())}n(ci,"signBrowserConnectTicket");async function di(e){try{let{payload:t}=await ei(e,await ai(),{algorithms:[N],issuer:L,audience:j});return qd.parse(t)}catch(t){throw t instanceof Qo.JWTExpired?new h({message:"Browser connect ticket has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new h({message:"Browser connect ticket could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(di,"verifyBrowserConnectTicket");async function ui(e){if((await b().consumeBrowserConnectTicket({id:e.id,expiresAt:R(new Date(e.exp*1e3)),now:R(new Date)})).kind==="consumed")throw new h({message:"Browser connect ticket has already been used",extensionMembers:{[g]:"oauth_state_reused"}})}n(ui,"consumeBrowserConnectTicket");function Dd(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(Dd,"buildConnectRequiredMessage");async function Hd(e){let t=k(e.requestUrl,e.requestHeaders),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 ci({...Ye(e),purpose:"browser_connect"})),r.toString()}n(Hd,"buildGatewayBrowserTicketUrl");function zd(e){return M().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(zd,"buildGatewayConnectPath");async function Lr(e){return Hd({...e,path:zd(e.upstreamServerId),redirect:!0})}n(Lr,"buildGatewayConnectUrl");async function Zt(e){let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},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 Lr(t),message:Dd(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(Zt,"buildRedirectConnectRequiredResponse");function li(e){return Ld({...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(li,"buildAdminConnectRequiredResponse");function Ld(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(Ld,"buildAdminSetupRequiredResponse");$();var pi=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function Bd(e,t){return e&&e.length>0?e.join(t):void 0}n(Bd,"joinOAuthScopes");function jd(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of pi)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(jd,"sanitizeAuthorizationServerMetadata");function Br(e){let t=jd(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(Br,"sanitizeOAuthDiscoveryState");function mi(e){let t=new URL(e);for(let r of pi){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(mi,"normalizeDuplicateSingletonAuthorizationRequestParams");function Kt(e){let t=new URL(e);return T(t)&&we(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(Kt,"normalizeLoopbackOAuthRedirectUri");function fi(e){return Bd(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(fi,"readProtectedResourceMetadataScope");function Nd(e){return`Zuplo MCP Gateway - ${e}`}n(Nd,"buildGatewayOAuthClientName");function Gd(e,t){return e&&e.length>0?e.join(t):void 0}n(Gd,"joinOAuthScopeList");function jr(e){return new URL(M().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(jr,"buildOAuthClientMetadataDocumentUrl");function Nr(e){let t=Me(e.upstreamServerId);return{client_name:Nd(t.displayName),client_uri:new URL("/",e.origin).toString(),redirect_uris:[e.redirectUri],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",...e.scope===void 0?{}:{scope:e.scope},token_endpoint_auth_method:"none"}}n(Nr,"buildGatewayOAuthClientMetadata");function hi(e,t,r){let o=qe(t,r),i=Gd(o.scopes,o.scopeDelimiter);return{client_id:jr({origin:e,upstreamServerId:t}),...Nr({origin:e,upstreamServerId:t,redirectUri:Kt(new URL(o.redirectPath,e)).toString(),scope:i})}}n(hi,"buildOAuthClientMetadataDocument");$();import{base64url as fe}from"jose";var $d="SHA-256",ze="AES-GCM",Fd=12,$r="zuplo-secret",Fr=1,gi="generated:auth_private_key:token-encryption",Zd=d.object({version:d.literal(Fr),keyId:d.literal(gi),algorithm:d.literal(ze),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();function He(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(He,"copyToArrayBuffer");async function Gr(){return V({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest($d,He(e));return crypto.subtle.importKey("raw",t,{name:ze},!1,["encrypt","decrypt"])},"derive")})}n(Gr,"getEncryptionKey");function yi(e){return He(new TextEncoder().encode(`${$r}:v${e.version}:${e.keyId}`))}n(yi,"getAssociatedData");function Kd(e){return`${$r}:v${e.version}:${fe.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(Kd,"encodeEnvelope");function Jd(e){let t=`${$r}:v${Fr}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(fe.decode(r));return Zd.parse(JSON.parse(o))}n(Jd,"decodeEnvelope");async function Jt(e){let t=await Gr(),r=crypto.getRandomValues(new Uint8Array(Fd)),o={version:Fr,keyId:gi},i=await crypto.subtle.encrypt({name:ze,iv:r,additionalData:yi(o)},t,new TextEncoder().encode(e));return Kd({...o,algorithm:ze,iv:fe.encode(r),ciphertext:fe.encode(new Uint8Array(i))})}n(Jt,"encryptSecret");async function mt(e){let t=Jd(e);if(t){let s=await Gr(),c=await crypto.subtle.decrypt({name:ze,iv:He(fe.decode(t.iv)),additionalData:yi(t)},s,He(fe.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,o]=e.split(".");if(!r||!o)throw new de("Encrypted payload is malformed");let i=await Gr(),a=await crypto.subtle.decrypt({name:ze,iv:He(fe.decode(r))},i,He(fe.decode(o)));return new TextDecoder().decode(a)}n(mt,"decryptSecret");var Wd=d.union([Qe,zt]),wi=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:Dt.optional(),authorizationServerMetadata:d.union([Xe,Ht]).optional()}).passthrough(),Vd="Bearer",Yd="__zuplo_refresh_only_upstream_access_token__";function Xd(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Xd,"splitScopes");function Qd(e){return Et.parse(e)}n(Qd,"parsePkceCodeVerifier");function eu(e){if(typeof e.expires_in=="number")return R(new Date(Date.now()+e.expires_in*1e3))}n(eu,"readTokenExpiry");async function _i(e){if(e!==void 0)return Jt(JSON.stringify(e))}n(_i,"encryptJson");async function Ri(e,t){if(!e)return;let r=await mt(e);try{return t.parse(JSON.parse(r))}catch(o){throw new h({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:o})}}n(Ri,"decryptJson");function tu(e){if(e===void 0)return;e=Br(e);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(tu,"toOAuthDiscoveryState");function ru(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(ru,"clientInformationAllowsRedirectUri");function nu(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(nu,"clientInformationMatchesCurrentClientMetadataUrl");function ou(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(ou,"isUrlBasedClientInformation");function iu(e,t){return t===void 0?e:{...e,scope:t}}n(iu,"applyOAuthClientMetadataScope");function bi(e,t){return fi({state:e,delimiter:t})}n(bi,"readResourceMetadataScope");function au(e,t){return e&&e.length>0?e.join(t):void 0}n(au,"joinOAuthScopeList");function su(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new q(`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(su,"buildManualOAuthClientInformation");function cu(e,t){let r=jr({origin:new URL(t).origin,upstreamServerId:e});return Ur(r)?r:void 0}n(cu,"buildClientMetadataUrl");function Ci(e){for(let t of e)if(t!==void 0)return t}n(Ci,"firstDefined");function du(e){let t=qe(e.target.upstreamServerId,e.target.authProfileId),r=au(t.scopes,t.scopeDelimiter),o=Nr({origin:new URL(e.redirectUri).origin,upstreamServerId:e.target.upstreamServerId,redirectUri:e.redirectUri,scope:r});if(t.clientRegistration.mode==="manual")return{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,configuredClientInformation:su({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let i=cu(e.target.upstreamServerId,e.redirectUri);return i===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,clientMetadataUrl:i}}n(du,"buildInitialOAuthClientSetup");function uu(e,t){if(t===void 0)return Ci([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(uu,"readEncryptedClientInformation");function lu(e){return Ci([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}n(lu,"readEncryptedDiscoveryState");var Ie=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=du({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=uu(t,this.configuredClientInformation),this.encryptedDiscoveryState=lu(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return iu(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return si({id:t.id,...Ye({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,!ou({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await _i(t),await this.syncPendingState(!1)))}async discoveryState(){return this.loadPersistedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=Br(wi.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.inferredScope=bi(r,this.scopeDelimiter),this.encryptedDiscoveryState=await _i(r),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Oe.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=r.refresh_token?await Jt(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:Oe.parse({...r,refresh_token:await mt(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let a={id:this.connection?.id??ho(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await Jt(r.access_token),encryptedRefreshToken:i,scopes:Xd(r.scope??this.readEffectiveScope()),expiresAt:eu(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await b().upsertUpstreamConnection(a)}async redirectToAuthorization(t){let r=mi(t);this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:Qd(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new h({message:"OAuth code verifier is missing",extensionMembers:{[g]:"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:go(),...Ye({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()+oi)),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 b().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 Ri(this.encryptedClientInformation,Wd)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&(!ru(t,this.redirectUriValue)||!nu({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl}))){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}return t===void 0&&this.pendingState?.codeVerifier!==void 0&&this.clientMetadataUrl!==void 0&&(t=zt.parse({client_id:this.clientMetadataUrl})),this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async loadPersistedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;try{this.cachedDiscoveryState=tu(await Ri(this.encryptedDiscoveryState,wi))}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1)}return this.discoveryStateLoaded=!0,this.inferredScope=bi(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 mt(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await mt(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=Oe.parse({access_token:t??Yd,token_type:Vd,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 b().upsertUpstreamConnection(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var pu=3e4,mu=256*1024,fu=2;function hu(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(hu,"hasUsableAccessToken");var gu="does not support dynamic client registration",yu=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],wu=["HTTP 403 Forbidden","Access Denied","permission to access"];function _u(e){return e instanceof Error&&e.message.includes(gu)}n(_u,"isDynamicClientRegistrationUnsupported");function Ru(e){return e instanceof Error&&yu.some(t=>e.message.includes(t))}n(Ru,"isProtectedResourceMetadataUnavailable");function bu(e){return e instanceof Error&&wu.some(t=>e.message.includes(t))}n(bu,"isUpstreamProviderAccessDenied");function Cu(e){if(e.error instanceof h&&e.error.extensionMembers?.[g]!==void 0)return e.error;if(_u(e.error))return new h({message:`The authorization server for ${e.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register an OAuth client for the gateway manually before retrying.`,extensionMembers:{[g]:"upstream_client_registration_required"}},{cause:e.error});if(Ru(e.error))return new h({message:`The upstream MCP server "${e.upstreamServerId}" does not publish OAuth protected resource metadata at "${e.resourceMetadataUrl}". Configure protectedResourceMetadataUrl to a working metadata document, use a provider-supported legacy client, or contact the provider to approve/allowlist this gateway OAuth client before retrying.`,extensionMembers:{[g]:"upstream_oauth_discovery_unavailable"}},{cause:e.error});if(bu(e.error))return new h({message:`The upstream provider denied access while connecting ${e.upstreamServerId}. Confirm the provider allows this gateway and its OAuth client, then retry.`,extensionMembers:{[g]:"upstream_provider_access_denied"}},{cause:e.error})}n(Cu,"mapUpstreamOAuthSetupError");function vu(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(vu,"readOAuthFetchRequest");function Su(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(Su,"responseLooksJson");function Iu(e,t){let r=e.headers.get("content-type")??"",o=t.trimStart().toLowerCase();return r.includes("html")||o.startsWith("<!doctype html")||o.startsWith("<html")}n(Iu,"responseLooksHtml");function xu(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new h({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[g]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[Te]:e.response.status,[ke]:r,[Ee]:e.request.url.toString(),[Pe]:e.body}})}n(xu,"throwUpstreamHtmlError");function vi(e){return async(t,r)=>{let o=vu(t),i=await Go(t,r,{maxRedirects:fu,maxResponseBytes:mu,problemCode:"upstream_token_exchange_failed",timeoutMs:pu}),a=await i.clone().text();if(!i.ok&&Iu(i,a)&&xu({upstreamServerId:e,request:o,response:i,body:a}),!Su(i,a))return i;try{JSON.parse(a)}catch(s){throw new h({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[g]:"upstream_token_exchange_failed"}},{cause:s})}return i}}n(vi,"createUpstreamOAuthFetch");async function Si(e,t){e.applyChallengeScope(t.requestedScope);try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:vi(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),await Ar(e,r)}catch(r){let o=Cu({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(Si,"runUpstreamOAuth");async function Au(e,t){e.applyChallengeScope(t.requestedScope);let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:vi(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),Ar(e,r)}n(Au,"exchangeUpstreamAuthorizationCode");async function Ii(e,t){let r=await Si(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new h({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new h({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Ii,"requireUpstreamAuthorizationRedirect");async function xi(e){if(!e.forceRefresh&&hu(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await Si(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 h({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new h({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}});return{kind:"connect_required",payload:await Eu({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,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(xi,"authorizeUpstreamOAuthSession");async function Uu(e){let t=await Ft(e.stateToken),r=await b().consumeUpstreamOAuthState({id:t.id,now:R(new Date)}),o=ku(r);return Pu({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),Tu(o),o}n(Uu,"consumeStoredCallbackState");function ku(e){switch(e.kind){case"consumed":throw new h({message:"OAuth state has already been used",extensionMembers:{[g]:"oauth_state_reused"}});case"missing":throw new h({message:"OAuth state is missing or expired",extensionMembers:{[g]:"oauth_state_expired"}});case"available":return e.record}}n(ku,"readConsumedCallbackState");function Pu(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 h({message:"OAuth callback did not match the initiating request",extensionMembers:{[g]:"oauth_callback_mismatch"}})}n(Pu,"assertStoredCallbackStateMatches");function Tu(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new h({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}})}n(Tu,"assertStoredCallbackStateFresh");async function Eu(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),li(r)}let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},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),Zt(t)}n(Eu,"buildOAuthConnectRequiredResponse");async function Ai(e){let t=await Uu({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Pt(t),[o]=await b().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 Ie(i),s=await Au(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 h({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${s}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new h({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Ai,"finishUpstreamOAuthCallback");function Ou(e){return Kt(new URL(e.callbackPath,k(e.requestUrl,e.requestHeaders))).toString()}n(Ou,"buildGatewayOAuthRedirectUri");async function Ui(e){let t=Me(e.upstreamServerId),r=qe(e.upstreamServerId,e.authProfileId),o=Ou({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),i="preloadedConnection"in e?e.preloadedConnection:(await b().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:k(e.request.url,e.request.headers)}}}n(Ui,"prepareUpstreamOAuthRequest");async function ki(e){let t=await Ui(e),r=new Ie({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Ii(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(ki,"startUpstreamConnect");async function Pi(e){let t=await Ui(e),r=new Ie({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return xi({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(Pi,"authorizeUpstreamRequest");async function Le(e){let{routeAuth:t}=e;return Pi({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}})}n(Le,"resolveUpstreamCredentialForRoute");async function Ti(e){let t={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}},r=await ki(t);return{authProfileId:e.connectRequest.authProfileId,authUrl:r,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}n(Ti,"startUpstreamConnectForRequest");async function Ei(e){let r=(await Ft(e.callbackRequest.state)).authProfileId;return Or({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}),Ai({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:Me(e.callbackRequest.upstreamServerId)})}n(Ei,"finishUpstreamCallbackForRequest");function Mu(e){return{upstreamServerId:e.connection.upstreamServerId,operationId:e.operationId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(Mu,"buildRouteAuthBaseFromConnection");function Mi(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:Wn(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(Mi,"buildRouteAuthBaseFromPolicyOptions");function Wt(e,t){let o=J().byOperationId.get(t);if(!o)throw new q(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new q(`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 q(`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 Mu({connection:o.connection,operationId:t})}n(Wt,"resolveRouteAuthBase");function Oi(e,t){switch(e){case"user":return kt(t);case"shared":return Kn()}}n(Oi,"buildOwnerForSubject");function Be(e,t){switch(e.ownerMode){case"shared":return{...e,ownerMode:"shared",owner:Oi(e.ownerMode,t),initiatedBySubjectId:t};case"user":return{...e,ownerMode:"user",owner:Oi(e.ownerMode,t),initiatedBySubjectId:t}}}n(Be,"resolveRouteAuthForSubject");var qu=We.InvalidRequest,Du=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function Hu(e,t){return{credentialType:e.type,forceRefresh:t}}n(Hu,"buildCredentialResolvedAttributes");function zu(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(zu,"connectRequiredReasonCode");function qi(e){x(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:Hu(e.credential,e.forceRefresh===!0)})}n(qi,"emitCredentialResolvedAnalyticsEvent");function Di(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(x(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"connect_required",reasonClass:"auth",attributes:t}),e.payload.state==="reconsent_required"){x(e.context,{eventType:C.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}x(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:zu(e.payload.state),reasonClass:"auth",attributes:t})}n(Di,"emitCredentialMissingAnalyticsEvents");function Lu(e){let t=e.route.raw();return xt.parse(t?.operationId)}n(Lu,"readOperationId");async function Bu(e,t,r,o){let i=await Le({request:e,routeAuth:t});if(i.kind==="connect_required")return Di({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;qi({context:o,credential:a,routeBinding:t});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(Bu,"buildCredentialHeaders");var ju=new Set(["authorization","cookie","cookie2"]);function Nu(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return t&&typeof t=="object"&&!Array.isArray(t)&&"method"in t&&typeof t.method=="string"?t.method:void 0}catch{return}}n(Nu,"readJsonRequestMethod");function Gu(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(Gu,"isJsonResponse");function Zr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Zr,"isRecord");function $u(e){return Array.isArray(e)&&e.length>0}n($u,"hasIconList");function Fu(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=Bt(Bn(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(Fu,"readFallbackServerIcons");function Zu(e){if(!Zr(e.body))return e.body;let t=e.body.result;if(!Zr(t))return e.body;let r=t.serverInfo;return!Zr(r)||$u(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n(Zu,"addMissingServerIcons");function Ku(e,t){let r=new Headers(e.headers);for(let o of ju)r.delete(o);for(let[o,i]of t)r.set(o,i);return new xn(e,{headers:r})}n(Ku,"applyUpstreamHeaders");function Ju(e){let t=new Headers(e.headers);for(let r of Du)t.delete(r);return t}n(Ju,"buildProxyHeaders");async function Wu(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(Wu,"readRetryBody");function Hi(e,t){let r=t.authUrl===void 0?void 0:Ro({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(Mt({id:_o(e),error:{code:r?.code??qu,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(Hi,"connectRequiredJsonRpcResponse");async function Vu(e){let{scope:t}=Eo(e.upstreamResponse),r=await Le({request:e.request,routeAuth:e.routeAuth,forceRefresh:!0,...t===void 0?{}:{requestedScope:t}});if(r.kind==="connect_required")return Di({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;qi({context:e.context,credential:i,routeBinding:e.routeAuth,forceRefresh:!0});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(Vu,"applyRefreshedCredentialHeaders");function Yu(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await Vu({request:e.request,context:e.context,headers:Ju(r),routeAuth:e.routeAuth,upstreamResponse:t});if(o.kind==="connect_required")return Hi(e.requestBody,o.payload);if(o.kind==="response")return o.response;let i=jn({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return Rt.fetch(i.url,i.init)})}n(Yu,"installUpstreamAuthRetryHook");function Xu(e){if(Nu(e.requestBody)!=="initialize")return;let t=Fu({connection:e.connection,context:e.context});t===void 0||t.length===0||e.context.addResponseSendingHook(async r=>{if(!Gu(r))return r;let o;try{o=await r.clone().json()}catch{return r}let i=Zu({body:o,icons:t});if(i===o)return r;let a=new Headers(r.headers);return a.delete("content-length"),new Response(JSON.stringify(i),{status:r.status,statusText:r.statusText,headers:a})})}n(Xu,"installInitializeIconHook");async function Kr(e,t,r){let o=Lu(t),i=await Wu(e),a=Mi({connection:r,operationId:o}),s=_e(e.user,e.url,e.headers);to(t,s);let c=Be(a,s.subjectId),u=await Bu(e,c,r,t);if(!(u instanceof Response)&&u.kind==="connect_required")return Hi(i,u.payload);if(u instanceof Response)return u;let p=Ku(e,u.headers);return Yu({request:p,context:t,requestBody:i,routeAuth:c}),Xu({context:t,requestBody:i,connection:r}),p}n(Kr,"mcpTokenExchangePolicy");var Jr=class extends Ct{static{n(this,"McpTokenExchangeInboundPolicy")}constructor(t,r){let o=Vn(t,r);super(o,r)}async handler(t,r){return bt("policy.inbound.mcp-token-exchange"),Kr(t,r,this.options)}};$();var zi=Symbol("Html");function Qu(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}n(Qu,"escapeHtml");function el(e){return e===null||typeof e!="object"?!1:e[zi]===!0}n(el,"isHtml");function Li(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Li).join(""):el(e)?e.value:Qu(String(e))}n(Li,"renderValue");function ae(e){return{[zi]:!0,value:e}}n(ae,"trustedHtml");var Y=ae("");function v(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=Li(t[o]),r+=e[o+1]??"";return ae(r)}n(v,"html");function je(e){return e.value}n(je,"renderHtml");function Bi(e){return v`<p class="card__description">${e.detail}</p>${e.guidance} ${e.technicalDetails} ${e.action}`}n(Bi,"renderBrowserErrorPage");var Ne=ae('*,: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 Ge(e){return v`<!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{$b as Ye,Ab as Ds,Ac as H,Bb as Hs,Bc as ao,Cb as zs,Cc as so,Db as Ls,Dc as hr,Eb as Bs,Ec as co,Fb as js,Fc as uo,G as Un,Gb as Ns,Gc as gr,H as l,Hb as Gs,Hc as _e,I as kn,Ib as $s,Ic as lo,J as cr,Jb as Fs,Jc as po,K as te,Kb as Bn,Kc as mo,L as Pn,Lb as jn,Lc as fo,M as y,Mb as Nn,Mc as ho,N as ue,Nb as xt,Nc as go,O as vt,Ob as dr,Oc as yo,P as Tn,Pb as At,Pc as b,Q as En,Qb as Ut,Qc as x,R as On,Rb as We,Rc as pe,S as d,Sb as Gn,Sc as U,T as $,Tb as $n,Tc as wo,Ub as Fn,Uc as Zs,Vb as Ve,Vc as Ks,Wb as Zn,Xb as kt,Yb as Kn,Z as Mn,Zb as ur,_b as Jn,a as bt,ac as Pt,bc as Wn,cc as Vn,dc as Yn,ec as Xn,fc as J,gb as we,gc as M,hb as T,hc as Qn,i as ye,ib as qn,ic as eo,j as In,jb as Dn,jc as R,kb as k,kc as ne,l as xn,lb as Hn,lc as Tt,mb as g,mc as B,nb as ke,nc as Z,ob as Pe,oc as to,p as An,pb as Te,pc as ro,qb as Ee,qc as Et,r as Ct,rb as St,rc as no,sb as zn,sc as oe,tb as F,tc as lr,ub as Ln,uc as pr,vb as re,vc as oo,wb as w,wc as Ot,xb as It,xc as mr,yb as D,yc as fr,zb as le,zc as io}from"../chunk-6WKYPMAI.js";import{d as sr}from"../chunk-JRXZBVXH.js";import{a as C}from"../chunk-4SACVMDH.js";import{$ as de,a as n,aa as h,ba as q,ca as Sn,da as Rt}from"../chunk-ZIKV2LUM.js";$();function Js(e){let t=Ut.safeParse(e);return t.success?t.data.id:void 0}n(Js,"parseJsonRpcRequestId");function _o(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Js(t)}catch{return}}n(_o,"readJsonRpcRequestIdFromBody");function Mt(e){return Gn.parse({jsonrpc:At,...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(Mt,"jsonRpcErrorResponse");function Ro(e){return new Fn([$n.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Ro,"urlElicitationRequiredError");var qt=d.record(d.string(),d.unknown()),Ws=d.record(d.string(),d.unknown()),Vs=d.object({name:d.string().min(1),description:d.string().min(1).optional(),annotations:Ws.optional(),_meta:qt.optional()}).strict(),Ys=d.object({name:d.string().min(1),description:d.string().min(1).optional(),_meta:qt.optional()}).strict(),Xs=d.object({uri:d.string().min(1),name:d.string().min(1).optional(),description:d.string().min(1).optional(),mimeType:d.string().min(1).optional(),_meta:qt.optional()}).strict(),Qs=d.object({uriTemplate:d.string().min(1),name:d.string().min(1).optional(),description:d.string().min(1).optional(),mimeType:d.string().min(1).optional(),_meta:qt.optional()}).strict(),ec=d.array(d.union([d.string(),Vs])),tc=d.array(d.union([d.string(),Ys])),rc=d.array(d.union([d.string(),Xs])),nc=d.array(d.union([d.string(),Qs])),oc=d.object({tools:ec.optional(),prompts:tc.optional(),resources:rc.optional(),resourceTemplates:nc.optional()}).strict(),wr=[{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 ic(e,t){return qn(oc,e,`MCP capability filter policy "${t}"`)}n(ic,"parseMcpCapabilityFilterOptions");function z(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(z,"isRecord");function ac(e,t){if(!z(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(ac,"readParamString");function _r(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(_r,"readRequestId");function So(e){return e===void 0?void 0:JSON.stringify(e)}n(So,"requestIdKey");function sc(e){let t={};for(let r of wr){let o=e[r.option];if(o===void 0)continue;let i=new Map;for(let a of o){let s=lc(a,r.itemProperty);s!==void 0&&i.set(s.key,s)}t[r.option]=i}return t}n(sc,"buildProjectionMaps");function Rr(e){return wr.find(t=>t.listMethod===e)}n(Rr,"findListRule");function cc(e){return e.requests.some(t=>{if(!z(t))return!1;let r=Rr(t.method);return r!==void 0&&e.projectionMaps[r.option]!==void 0})}n(cc,"shouldFilterListResponses");function dc(e){for(let t of wr){let r=e.projectionMaps[t.option];if(r!==void 0)for(let o of t.directMethods){if(e.request.method!==o.method)continue;let i=ac(e.request.params,o.paramProperty);if(i!==void 0&&!r.has(i))return{id:_r(e.request)}}}}n(dc,"findDisallowedDirectAccess");function uc(e){return Response.json(Mt({id:e,error:{code:We.MethodNotFound,message:"Method not found"}}))}n(uc,"methodNotFoundResponse");function lc(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!z(e))return;let r=e[t];if(typeof r=="string")return{key:r,overlay:e}}n(lc,"buildProjection");function bo(e){let t=e.base[e.property],r=e.overlay[e.property];return z(r)?z(t)?{...t,...r}:r:t}n(bo,"mergeRecordProperty");function pc(e,t){let r={...e,...t.overlay},o=bo({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let i=bo({base:e,overlay:t.overlay,property:"_meta"});return i!==void 0&&(r._meta=i),r}n(pc,"applyProjection");function Co(e,t,r){if(!z(e))return e;let o=e.result;if(!z(o))return e;let i=o[t.resultProperty];return!Array.isArray(i)||!i.every(a=>z(a)&&typeof a[t.itemProperty]=="string")?e:{...e,result:{...o,[t.resultProperty]:i.flatMap(a=>{if(!z(a))return[];let s=a[t.itemProperty];if(typeof s!="string")return[];let c=r.get(s);return c===void 0?[]:[pc(a,c)]})}}}n(Co,"filterAndProjectItems");function mc(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!z(r))continue;let o=Rr(r.method),i=_r(r),a=So(i);o!==void 0&&a!==void 0&&t.set(a,o)}return t}n(mc,"buildListRulesByResponseId");function fc(e){if(Array.isArray(e.responseBody)){let o=mc(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(i=>{if(!z(i)||"error"in i)return i;let a=So(_r(i)),s=a===void 0?void 0:o.get(a),c=s===void 0?void 0:e.projectionMaps[s.option];return s===void 0||c===void 0?i:Co(i,s,c)})}if(!z(e.requestBody)||!z(e.responseBody)||"error"in e.responseBody)return e.responseBody;let t=Rr(e.requestBody.method),r=t===void 0?void 0:e.projectionMaps[t.option];return t===void 0||r===void 0?e.responseBody:Co(e.responseBody,t,r)}n(fc,"filterJsonRpcResponse");async function vo(e){return e.clone().json()}n(vo,"readJson");function hc(e){return e.headers.get("content-type")?.includes("json")??!1}n(hc,"isJsonResponse");var yr=class extends Ct{static{n(this,"McpCapabilityFilterInboundPolicy")}#e;constructor(t,r){let o=ic(t,r);super(o,r),this.#e=sc(o)}async handler(t,r){bt("policy.inbound.mcp-capability-filter");let o;try{o=await vo(t)}catch{return t}let i=Array.isArray(o)?o:[o];for(let a of i){if(!z(a))continue;let s=dc({request:a,projectionMaps:this.#e});if(s!==void 0)return uc(s.id)}return cc({requests:i,projectionMaps:this.#e})&&r.addResponseSendingHook(async a=>{if(!hc(a))return a;let s;try{s=await vo(a)}catch{return a}let c=fc({requestBody:o,responseBody:s,projectionMaps:this.#e});if(c===s)return a;let u=new Headers(a.headers);return u.delete("content-length"),new Response(JSON.stringify(c),{status:a.status,statusText:a.statusText,headers:u})}),t}};var br;br=globalThis.crypto;async function gc(e){return(await br).getRandomValues(new Uint8Array(e))}n(gc,"getRandomValues");async function yc(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await gc(e-o.length);for(let a of i)a<r&&(o+=t[a%t.length])}return o}n(yc,"random");async function wc(e){return await yc(e)}n(wc,"generateVerifier");async function _c(e){let t=await(await br).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(_c,"generateChallenge");async function Cr(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await wc(e),r=await _c(t);return{code_verifier:t,code_challenge:r}}n(Cr,"pkceChallenge");$();var E=kn().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:En.custom,message:"URL must be parseable",fatal:!0}),Un}).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"}),Dt=vt({resource:l().url(),authorization_servers:y(E).optional(),jwks_uri:l().url().optional(),scopes_supported:y(l()).optional(),bearer_methods_supported:y(l()).optional(),resource_signing_alg_values_supported:y(l()).optional(),resource_name:l().optional(),resource_documentation:l().optional(),resource_policy_uri:l().url().optional(),resource_tos_uri:l().url().optional(),tls_client_certificate_bound_access_tokens:te().optional(),authorization_details_types_supported:y(l()).optional(),dpop_signing_alg_values_supported:y(l()).optional(),dpop_bound_access_tokens_required:te().optional()}),Xe=vt({issuer:l(),authorization_endpoint:E,token_endpoint:E,registration_endpoint:E.optional(),scopes_supported:y(l()).optional(),response_types_supported:y(l()),response_modes_supported:y(l()).optional(),grant_types_supported:y(l()).optional(),token_endpoint_auth_methods_supported:y(l()).optional(),token_endpoint_auth_signing_alg_values_supported:y(l()).optional(),service_documentation:E.optional(),revocation_endpoint:E.optional(),revocation_endpoint_auth_methods_supported:y(l()).optional(),revocation_endpoint_auth_signing_alg_values_supported:y(l()).optional(),introspection_endpoint:l().optional(),introspection_endpoint_auth_methods_supported:y(l()).optional(),introspection_endpoint_auth_signing_alg_values_supported:y(l()).optional(),code_challenge_methods_supported:y(l()).optional(),client_id_metadata_document_supported:te().optional()}),Rc=vt({issuer:l(),authorization_endpoint:E,token_endpoint:E,userinfo_endpoint:E.optional(),jwks_uri:E,registration_endpoint:E.optional(),scopes_supported:y(l()).optional(),response_types_supported:y(l()),response_modes_supported:y(l()).optional(),grant_types_supported:y(l()).optional(),acr_values_supported:y(l()).optional(),subject_types_supported:y(l()),id_token_signing_alg_values_supported:y(l()),id_token_encryption_alg_values_supported:y(l()).optional(),id_token_encryption_enc_values_supported:y(l()).optional(),userinfo_signing_alg_values_supported:y(l()).optional(),userinfo_encryption_alg_values_supported:y(l()).optional(),userinfo_encryption_enc_values_supported:y(l()).optional(),request_object_signing_alg_values_supported:y(l()).optional(),request_object_encryption_alg_values_supported:y(l()).optional(),request_object_encryption_enc_values_supported:y(l()).optional(),token_endpoint_auth_methods_supported:y(l()).optional(),token_endpoint_auth_signing_alg_values_supported:y(l()).optional(),display_values_supported:y(l()).optional(),claim_types_supported:y(l()).optional(),claims_supported:y(l()).optional(),service_documentation:l().optional(),claims_locales_supported:y(l()).optional(),ui_locales_supported:y(l()).optional(),claims_parameter_supported:te().optional(),request_parameter_supported:te().optional(),request_uri_parameter_supported:te().optional(),require_request_uri_registration:te().optional(),op_policy_uri:E.optional(),op_tos_uri:E.optional(),client_id_metadata_document_supported:te().optional()}),Ht=ue({...Rc.shape,...Xe.pick({code_challenge_methods_supported:!0}).shape}),Oe=ue({access_token:l(),id_token:l().optional(),token_type:l(),expires_in:On.number().optional(),scope:l().optional(),refresh_token:l().optional()}).strip(),xo=ue({error:l(),error_description:l().optional(),error_uri:l().optional()}),Io=E.optional().or(Tn("").transform(()=>{})),bc=ue({redirect_uris:y(E),token_endpoint_auth_method:l().optional(),grant_types:y(l()).optional(),response_types:y(l()).optional(),client_name:l().optional(),client_uri:E.optional(),logo_uri:Io,scope:l().optional(),contacts:y(l()).optional(),tos_uri:Io,policy_uri:l().optional(),jwks_uri:E.optional(),jwks:Pn().optional(),software_id:l().optional(),software_version:l().optional(),software_statement:l().optional()}).strip(),zt=ue({client_id:l(),client_secret:l().optional(),client_id_issued_at:cr().optional(),client_secret_expires_at:cr().optional()}).strip(),Qe=bc.merge(zt),Vf=ue({error:l(),error_description:l().optional()}).strip(),Yf=ue({token:l(),token_type_hint:l().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 Uo({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(Uo,"checkResourceAllowed");var A=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}},et=class extends A{static{n(this,"InvalidRequestError")}};et.errorCode="invalid_request";var Re=class extends A{static{n(this,"InvalidClientError")}};Re.errorCode="invalid_client";var be=class extends A{static{n(this,"InvalidGrantError")}};be.errorCode="invalid_grant";var Ce=class extends A{static{n(this,"UnauthorizedClientError")}};Ce.errorCode="unauthorized_client";var tt=class extends A{static{n(this,"UnsupportedGrantTypeError")}};tt.errorCode="unsupported_grant_type";var rt=class extends A{static{n(this,"InvalidScopeError")}};rt.errorCode="invalid_scope";var nt=class extends A{static{n(this,"AccessDeniedError")}};nt.errorCode="access_denied";var ie=class extends A{static{n(this,"ServerError")}};ie.errorCode="server_error";var ot=class extends A{static{n(this,"TemporarilyUnavailableError")}};ot.errorCode="temporarily_unavailable";var it=class extends A{static{n(this,"UnsupportedResponseTypeError")}};it.errorCode="unsupported_response_type";var at=class extends A{static{n(this,"UnsupportedTokenTypeError")}};at.errorCode="unsupported_token_type";var st=class extends A{static{n(this,"InvalidTokenError")}};st.errorCode="invalid_token";var ct=class extends A{static{n(this,"MethodNotAllowedError")}};ct.errorCode="method_not_allowed";var dt=class extends A{static{n(this,"TooManyRequestsError")}};dt.errorCode="too_many_requests";var ve=class extends A{static{n(this,"InvalidClientMetadataError")}};ve.errorCode="invalid_client_metadata";var ut=class extends A{static{n(this,"InsufficientScopeError")}};ut.errorCode="insufficient_scope";var lt=class extends A{static{n(this,"InvalidTargetError")}};lt.errorCode="invalid_target";var ko={[et.errorCode]:et,[Re.errorCode]:Re,[be.errorCode]:be,[Ce.errorCode]:Ce,[tt.errorCode]:tt,[rt.errorCode]:rt,[nt.errorCode]:nt,[ie.errorCode]:ie,[ot.errorCode]:ot,[it.errorCode]:it,[at.errorCode]:at,[st.errorCode]:st,[ct.errorCode]:ct,[dt.errorCode]:dt,[ve.errorCode]:ve,[ut.errorCode]:ut,[lt.errorCode]:lt};function Cc(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(Cc,"isClientAuthMethod");var vr="code",Sr="S256";function vc(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Cc(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(vc,"selectClientAuthMethod");function Sc(e,t,r,o){let{client_id:i,client_secret:a}=t;switch(e){case"client_secret_basic":Ic(i,a,r);return;case"client_secret_post":xc(i,a,o);return;case"none":Ac(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(Sc,"applyClientAuthentication");function Ic(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(Ic,"applyBasicAuth");function xc(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(xc,"applyPostAuth");function Ac(e,t){t.set("client_id",e)}n(Ac,"applyPublicAuth");async function To(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=xo.parse(JSON.parse(r)),{error:i,error_description:a,error_uri:s}=o,c=ko[i]||ie;return new c(a||"",s)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new ie(i)}}n(To,"parseErrorResponse");async function Ar(e,t){try{return await Ir(e,t)}catch(r){if(r instanceof Re||r instanceof Ce)return await e.invalidateCredentials?.("all"),await Ir(e,t);if(r instanceof be)return await e.invalidateCredentials?.("tokens"),await Ir(e,t);throw r}}n(Ar,"auth");async function Ir(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:i,fetchFn:a}){let s=await e.discoveryState?.(),c,u,p,f=i;if(!f&&s?.resourceMetadataUrl&&(f=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(u=s.authorizationServerUrl,c=s.resourceMetadata,p=s.authorizationServerMetadata??await Mo(u,{fetchFn:a}),!c)try{c=await Oo(t,{resourceMetadataUrl:f},a)}catch{}(p!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:f?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}else{let P=await Oc(t,{resourceMetadataUrl:f,fetchFn:a});u=P.authorizationServerUrl,p=P.authorizationServerMetadata,c=P.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:f?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}let _=await Uc(t,e,c),S=o||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,I=await Promise.resolve(e.clientInformation());if(!I){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let P=p?.client_id_metadata_document_supported===!0,O=e.clientMetadataUrl;if(O&&!Ur(O))throw new ve(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${O}`);if(P&&O)I={client_id:O},await e.saveClientInformation?.(I);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let vn=await zc(u,{metadata:p,clientMetadata:e.clientMetadata,scope:S,fetchFn:a});await e.saveClientInformation(vn),I=vn}}let G=!e.redirectUrl;if(r!==void 0||G){let P=await Hc(e,u,{metadata:p,resource:_,authorizationCode:r,fetchFn:a});return await e.saveTokens(P),"AUTHORIZED"}let K=await e.tokens();if(K?.refresh_token)try{let P=await Dc(u,{metadata:p,clientInformation:I,refreshToken:K.refresh_token,resource:_,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(P),"AUTHORIZED"}catch(P){if(!(!(P instanceof A)||P instanceof ie))throw P}let Q=e.state?await e.state():void 0,{authorizationUrl:Je,codeVerifier:ee}=await Mc(u,{metadata:p,clientInformation:I,state:Q,redirectUrl:e.redirectUrl,scope:S,resource:_});return await e.saveCodeVerifier(ee),await e.redirectToAuthorization(Je),"REDIRECT"}n(Ir,"authInternal");function Ur(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(Ur,"isHttpsUrl");async function Uc(e,t,r){let o=Ao(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!Uo({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(Uc,"selectResourceURL");function Eo(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let i=xr(e,"resource_metadata")||void 0,a;if(i)try{a=new URL(i)}catch{}let s=xr(e,"scope")||void 0,c=xr(e,"error")||void 0;return{resourceMetadataUrl:a,scope:s,error:c}}n(Eo,"extractWWWAuthenticateParams");function xr(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(xr,"extractFieldFromWwwAuth");async function Oo(e,t,r=fetch){let o=await Tc(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 Dt.parse(await o.json())}n(Oo,"discoverOAuthProtectedResourceMetadata");async function kr(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?kr(e,void 0,r):void 0;throw o}}n(kr,"fetchWithCorsRetry");function kc(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(kc,"buildWellKnownPath");async function Po(e,t,r=fetch){return await kr(e,{"MCP-Protocol-Version":t},r)}n(Po,"tryMetadataDiscovery");function Pc(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(Pc,"shouldAttemptFallback");async function Tc(e,t,r,o){let i=new URL(e),a=o?.protocolVersion??dr,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let u=kc(t,i.pathname);s=new URL(u,o?.metadataServerUrl??i),s.search=i.search}let c=await Po(s,a,r);if(!o?.metadataUrl&&Pc(c,i.pathname)){let u=new URL(`/.well-known/${t}`,i);c=await Po(u,a,r)}return c}n(Tc,"discoverMetadataWithFallback");function Ec(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(Ec,"buildDiscoveryUrls");async function Mo(e,{fetchFn:t=fetch,protocolVersion:r=dr}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=Ec(e);for(let{url:a,type:s}of i){let c=await kr(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"?Xe.parse(await c.json()):Ht.parse(await c.json())}}}n(Mo,"discoverAuthorizationServerMetadata");async function Oc(e,t){let r,o;try{r=await Oo(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 Mo(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(Oc,"discoverOAuthServerInfo");async function Mc(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(vr))throw new Error(`Incompatible auth server: does not support response type ${vr}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Sr))throw new Error(`Incompatible auth server: does not support code challenge method ${Sr}`)}else c=new URL("/authorize",e);let u=await Cr(),p=u.code_verifier,f=u.code_challenge;return c.searchParams.set("response_type",vr),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",f),c.searchParams.set("code_challenge_method",Sr),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:p}}n(Mc,"startAuthorization");function qc(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(qc,"prepareAuthorizationCodeRequest");async function qo(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),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(a&&r.set("resource",a.href),i)await i(u,r,c,t);else if(o){let f=t?.token_endpoint_auth_methods_supported??[],_=vc(o,f);Sc(_,o,u,r)}let p=await(s??fetch)(c,{method:"POST",headers:u,body:r});if(!p.ok)throw await To(p);return Oe.parse(await p.json())}n(qo,"executeTokenRequest");async function Dc(e,{metadata:t,clientInformation:r,refreshToken:o,resource:i,addClientAuthentication:a,fetchFn:s}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),u=await qo(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:a,resource:i,fetchFn:s});return{refresh_token:o,...u}}n(Dc,"refreshAuthorization");async function Hc(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 p=await e.codeVerifier();c=qc(i,p,e.redirectUrl)}let u=await e.clientInformation();return qo(t,{metadata:r,tokenRequestParams:c,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(Hc,"fetchToken");async function zc(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 To(s);return Qe.parse(await s.json())}n(zc,"registerClient");var Pr="zuplo.com",Lc=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),Bc=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Do(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(Do,"s2FaviconHref");function jc(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(jc,"strictFaviconHref");var Lt=Do(Pr);function Tr(e){let t=e.toLowerCase();return t===Pr||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Do(Pr):jc(e)}n(Tr,"resolveIconHref");function Nc(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(Nc,"hostnameFromHost");function Gc(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(Gc,"isLocalOrAddressHost");function $c(e){let t=Nc(e).toLowerCase().replace(/\.$/,"");if(Gc(t)||Bc.some(a=>t===a.slice(1)||t.endsWith(a)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let o=r.slice(-2).join("."),i=Lc.has(o)?3:2;return r.slice(-i).join(".")}n($c,"inferFaviconDomain");function Er(e){return{src:Tr($c(e)),mimeType:"image/png",sizes:["128x128"]}}n(Er,"resolveMcpFaviconIcon");function Bt(e){try{return Er(new URL(e).host)}catch{return}}n(Bt,"resolveMcpFaviconIconFromUrl");function Me(e){let t=J().connectionsById.get(e);if(!t)throw new q(`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(Me,"getUpstreamServerConfig");function Fc(e){let t=J().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new q(`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(Fc,"resolveUpstreamAuthProfileId");function Or(e){Fc(e);let t=J().connectionsById.get(e.upstreamServerId);if(!t)throw new q(`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(Or,"getUpstreamAuthConfig");function qe(e,t){return Or({upstreamServerId:e,authProfileId:t})}n(qe,"requireUpstreamOAuthConfig");function W(e){return new h({message:e,extensionMembers:{[g]:"invalid_request"}})}n(W,"invalidOutboundUrl");function Zc(){let e=sr.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP??globalThis.process?.env?.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP;return typeof e=="string"&&e==="1"}n(Zc,"isTestOnlyAllowHttpLoopbackIdpEnabled");function Kc(){let e=sr.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_CIMD??globalThis.process?.env?.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_CIMD;return typeof e=="string"&&e==="1"}n(Kc,"isTestOnlyAllowHttpLoopbackCimdEnabled");var Jc=new Set(["undefined","null","nan"]);function qr(e,t){if(!e.hostname)throw W(`Outbound URL has an empty hostname (got ${JSON.stringify(t)}). This typically indicates an unset $env(...) reference or a JS template literal coercing \`undefined\` into a URL. Check the policy options or runtime config that produced this URL.`);if(Jc.has(e.hostname.toLowerCase()))throw W(`Outbound URL hostname is ${JSON.stringify(e.hostname)} (from ${JSON.stringify(t)}). This almost always means an environment variable referenced by $env(...) is unset and a JS value was string-coerced into a URL. Set the missing env var or fix the policy option that produced this URL.`)}n(qr,"assertSafeOutboundHostname");var Wc=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),Vc=[{first:0},{first:10},{first:127},{first:169,secondMin:254,secondMax:254},{first:172,secondMin:16,secondMax:31},{first:192,secondMin:168,secondMax:168},{first:100,secondMin:64,secondMax:127},{first:224,firstMax:239},{first:240,firstMax:255}];function Ho(e){if(!/^\d+\.\d+\.\d+\.\d+$/.test(e))return;let t=e.split(".").map(r=>Number(r));if(!(t.length!==4||t.some(r=>Number.isNaN(r)||r<0||r>255)))return t}n(Ho,"parseIpv4Octets");function Yc([e,t],r){let o=r.firstMax??r.first;return e<r.first||e>o?!1:r.secondMin===void 0||r.secondMax===void 0?!0:t>=r.secondMin&&t<=r.secondMax}n(Yc,"ipv4RangeMatches");function zo(e){let t=Ho(e);return t!==void 0&&Vc.some(r=>Yc(t,r))}n(zo,"isPrivateIpv4");function Mr(e){if(!e||e.length>4)return;let t=Number.parseInt(e,16);return Number.isNaN(t)||t<0||t>65535?void 0:t}n(Mr,"parseIpv6Word");function Xc(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}n(Xc,"formatIpv4FromWords");function Qc(e){let t=e.slice(7),r=Ho(t);if(r!==void 0)return r.join(".");let[o,i,a]=t.split(":"),s=Mr(o),c=Mr(i);return a===void 0&&s!==void 0&&c!==void 0?Xc(s,c):void 0}n(Qc,"parseIpv6MappedIpv4");function ed(e){return Mr(e.split(":").find(Boolean))}n(ed,"readFirstIpv6Hextet");function td(e){let t=we(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let o=Qc(t);return o===void 0||zo(o)}let r=ed(t);return r===void 0?!1:(r&65024)===64512||(r&65472)===65152}n(td,"isPrivateIpv6");function Dr(e){let t=we(e);return Wc.has(t)||t.endsWith(".internal")||zo(t)||td(t)}n(Dr,"isBlockedOutboundHostname");function jt(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw W(`Unsupported outbound protocol: ${t.protocol}`);qr(t,e);let r=T(t);if(t.protocol==="http:"&&!r)throw W("Configured outbound HTTP URLs must target loopback hosts.");let o=we(t.hostname);if(!r&&Dr(o))throw W(`Blocked outbound host: ${o}`);return t}n(jt,"validateConfiguredOutboundUrl");function Lo(e){let t=new URL(e),r=T(t),o=r&&Zc();if(t.protocol!=="https:"&&!o)throw W("Identity provider URLs must use https.");if(t.username||t.password||t.search||t.hash)throw W("Identity provider URLs must not include credentials, query params, or fragments.");qr(t,e);let i=we(t.hostname);if(!r&&Dr(i))throw W(`Blocked identity provider host: ${i}`);return t}n(Lo,"validateIdentityProviderUrl");function Bo(e,t){let r=new URL(e),o=r.protocol==="http:"&&T(r)&&Kc();if(r.protocol!=="https:"&&!o||r.pathname==="/"||r.username||r.password||r.hash)throw W(`CIMD ${t} must be an HTTPS URL with a path and no credentials or fragment.`);if(qr(r,e),!o&&Dr(r.hostname))throw W(`CIMD ${t} points at a blocked host.`);return r}n(Bo,"validateCimdUrl");function Nt(e){return Bo(e,"client_id")}n(Nt,"validateCimdClientMetadataUrl");function Se(e){return Bo(e,"jwks_uri")}n(Se,"validateCimdClientJwksUrl");function jo(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let r=n(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}n(jo,"mergeAbortSignals");async function rd(e){try{await e.cancel()}catch{}}n(rd,"cancelReader");async function Gt(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],i=0,a=await r.read();for(;!a.done;){let u=a.value;if(i+=u.byteLength,i>t.maxBytes)throw await rd(r),t.createLimitError();o.push(u),a=await r.read()}let s=new Uint8Array(i),c=0;for(let u of o)s.set(u,c),c+=u.byteLength;return s}n(Gt,"readBoundedByteStream");var nd=2,od=1024*1024,id=1e4,ad=new Set([301,302,303,307,308]),sd=["authorization","proxy-authorization","cookie","cookie2"];function Hr(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Hr,"readRequestUrl");function De(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(De,"readRequestMethod");function cd(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 new h({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}})}n(cd,"assertContentLengthWithinLimit");async function dd(e,t,r){return cd(e,t,r),Gt(e.body,{maxBytes:t,createLimitError:n(()=>new h({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}}),"createLimitError")})}n(dd,"readBoundedResponseBody");function ud(e,t){let r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}n(ud,"responseFromBufferedBody");function ld(e,t){if(!ad.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(ld,"resolveRedirectUrl");function No(e,t){try{return t.validateUrl(e)}catch(r){throw new h({message:"Outbound URL was not allowed.",extensionMembers:{[g]:t.problemCode}},{cause:r})}}n(No,"validateOutboundUrl");function pd(e,t){throw e instanceof h&&St(e.extensionMembers?.[g])?e:new h({message:"Outbound fetch failed.",extensionMembers:{[g]:t}},{cause:e})}n(pd,"normalizeFetchError");function pt(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[o,i]of Object.entries(t.extra))i!==void 0&&(r[o]=i);t.error!==void 0&&B(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(pt,"logOutboundFailure");async function md(e,t,r,o,i,a,s){let c=De(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";pt(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:i,method:c,host:Z(a),error:u,extra:{abortReason:s()}}),pd(u,i)}}n(md,"fetchWithNormalizedError");function fd(e){if(e.redirects>=e.maxRedirects)throw new h({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[g]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new h({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[g]:e.problemCode}})}n(fd,"assertRedirectAllowed");function hd(e,t){let r=new Headers(e);for(let o of sd)r.delete(o);for(let o of t)r.delete(o);return r}n(hd,"stripCrossOriginHeaders");function gd(e,t,r,o,i){let a={...e,method:t,redirect:"manual",signal:r};return o&&(a.headers=hd(e.headers,i)),a}n(gd,"buildRedirectInit");function yd(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(yd,"buildInitialRequestInit");function wd(e){let t=De(e.currentInput,e.currentInit);fd({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=No(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),i=r.origin!==o.origin,a=r.toString();return{currentInput:a,currentUrl:a,currentInit:gd(e.currentInit,t,e.signal,i,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(wd,"followRedirect");async function zr(e,t,r){let o=r.problemCode??"invalid_request",i=r.maxRedirects??nd,a=r.maxResponseBytes??od,s=r.timeoutMs??id,c=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,f=new AbortController,_=jo(f,t.signal),S=!1,I=setTimeout(()=>{S=!0,f.abort()},s),G=e,K=yd(e,t,f.signal),Q;try{Q=No(Hr(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(ee){throw pt(p,{event:"outbound_url_blocked",problemCode:o,method:De(e,t),host:Z(Hr(e)),error:ee}),clearTimeout(I),_?.(),ee}let Je=0;try{for(;;){let ee=await md(p,c,G,K,o,Q,()=>S?`timeout_after_${s}ms`:void 0),P=ld(ee,Q);if(P!==void 0)try{let O=wd({currentInput:G,currentInit:K,currentUrl:Q,redirectUrl:P,redirects:Je,maxRedirects:i,problemCode:o,validateUrl:r.validateUrl,signal:f.signal,additionalCrossOriginStrippedHeaders:u});G=O.currentInput,K=O.currentInit,Q=O.currentUrl,Je=O.redirects;continue}catch(O){throw pt(p,{event:"outbound_redirect_blocked",problemCode:o,method:De(G,K),host:Z(Q),error:O,extra:{redirects:Je,maxRedirects:i,redirectTargetHost:Z(P)}}),O}try{return ud(ee,await dd(ee,a,o))}catch(O){throw pt(p,{event:"outbound_response_size_exceeded",problemCode:o,method:De(G,K),host:Z(Q),error:O,extra:{maxResponseBytes:a,status:ee.status}}),O}}}finally{clearTimeout(I),_?.()}}n(zr,"runSafeOutboundExchange");async function $t(e,t,r){let o=await zr(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(i){throw pt(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:De(e,t),host:Z(Hr(e)),error:i,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new h({message:"Outbound JSON response could not be parsed.",extensionMembers:{[g]:r.problemCode??"invalid_request"}},{cause:i})}}n($t,"runSafeOutboundJsonExchange");function Go(e,t={},r={}){return zr(e,t,{...r,validateUrl:jt})}n(Go,"fetchConfiguredOutbound");function $o(e,t={},r={}){return $t(e,t,{...r,validateUrl:Lo})}n($o,"fetchIdentityProviderJson");function Fo(e,t={},r={}){return $t(e,t,{...r,validateUrl:Nt})}n(Fo,"fetchCimdClientMetadataJson");function Zo(e,t={},r={}){return $t(e,t,{...r,validateUrl:Se})}n(Zo,"fetchCimdClientJwksJson");$();import{errors as Qo,jwtVerify as ei,SignJWT as ti}from"jose";var L="zuplo-mcp-gateway",j=L,N="HS256";import{base64url as _d}from"jose";var Rd=new TextEncoder,bd="MCP gateway could not initialize secure key material.",Cd=32,Ko=new Map,Jo=new Map,vd;function Sd(){return vd??Sn.instance.authPrivateKey}n(Sd,"readAuthPrivateKey");function Wo(e){return new de(bd,e===void 0?void 0:{cause:e})}n(Wo,"createGeneratedKeyMaterialError");function Vo(e,t){let r=_d.decode(t);if(r.byteLength!==Cd)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(Vo,"decodeJwkKeyField");function Id(e){let t=Sd();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=Vo("d",r.d);Vo("x",r.x);let i=Rd.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(Id,"decodeGeneratedKeyMaterial");function xd(e){let t=Ko.get(e);return t||(t=Id(e),Ko.set(e,t)),t}n(xd,"getMasterKeyMaterial");async function V(e){let t=Jo.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(xd(e.keyMaterialPurpose));return Jo.set(e.purpose,r),r}n(V,"readCachedDerivedKey");var Ad="SHA-256";var Ud="zuplo-mcp-gateway:",kd=new TextEncoder,Yo=new WeakMap;async function me(e,t){let r=Yo.get(e);r||(r=new Map,Yo.set(e,r));let o=r.get(t);if(o)return o;let i=await Pd(e,t);return r.set(t,i),i}n(me,"deriveGatewaySigningKey");async function Pd(e,t){let r=Xo(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=kd.encode(`${Ud}${t}`),a=await crypto.subtle.deriveBits({name:"HKDF",hash:Ad,salt:new Uint8Array,info:Xo(i)},o,32*8);return new Uint8Array(a)}n(Pd,"hkdfExpand");function Xo(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(Xo,"copyToArrayBuffer");var ri=15*60,Td=15*60,Ed=Jn.extend({id:po}),Od=Ed.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ni=ur.extend({id:mo,purpose:d.literal("browser_connect")}),Md=ur.extend({purpose:d.literal("browser_connect")}),qd=ni.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),oi=ri*1e3;async function ii(){return V({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>me(e,"oauth-state"),"derive")})}n(ii,"getOAuthStateKey");async function ai(){return V({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>me(e,"browser-connect"),"derive")})}n(ai,"getBrowserConnectKey");async function si(e){let t=Math.floor(Date.now()/1e3)+ri;return new ti(e).setProtectedHeader({alg:N,typ:"JWT"}).setIssuer(L).setAudience(j).setIssuedAt().setExpirationTime(t).sign(await ii())}n(si,"signOAuthState");async function Ft(e){try{let{payload:t}=await ei(e,await ii(),{algorithms:[N],issuer:L,audience:j});return Od.parse(t)}catch(t){throw t instanceof Qo.JWTExpired?new h({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new h({message:"OAuth state could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(Ft,"verifyOAuthState");async function ci(e){let t=Math.floor(Date.now()/1e3)+Td,r=Md.parse(e),o=ni.parse({...r,id:yo()});return new ti(o).setProtectedHeader({alg:N,typ:"JWT"}).setIssuer(L).setAudience(j).setIssuedAt().setExpirationTime(t).sign(await ai())}n(ci,"signBrowserConnectTicket");async function di(e){try{let{payload:t}=await ei(e,await ai(),{algorithms:[N],issuer:L,audience:j});return qd.parse(t)}catch(t){throw t instanceof Qo.JWTExpired?new h({message:"Browser connect ticket has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new h({message:"Browser connect ticket could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(di,"verifyBrowserConnectTicket");async function ui(e){if((await b().consumeBrowserConnectTicket({id:e.id,expiresAt:R(new Date(e.exp*1e3)),now:R(new Date)})).kind==="consumed")throw new h({message:"Browser connect ticket has already been used",extensionMembers:{[g]:"oauth_state_reused"}})}n(ui,"consumeBrowserConnectTicket");function Dd(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(Dd,"buildConnectRequiredMessage");async function Hd(e){let t=k(e.requestUrl,e.requestHeaders),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 ci({...Ye(e),purpose:"browser_connect"})),r.toString()}n(Hd,"buildGatewayBrowserTicketUrl");function zd(e){return M().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(zd,"buildGatewayConnectPath");async function Lr(e){return Hd({...e,path:zd(e.upstreamServerId),redirect:!0})}n(Lr,"buildGatewayConnectUrl");async function Zt(e){let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},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 Lr(t),message:Dd(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(Zt,"buildRedirectConnectRequiredResponse");function li(e){return Ld({...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(li,"buildAdminConnectRequiredResponse");function Ld(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(Ld,"buildAdminSetupRequiredResponse");$();var pi=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function Bd(e,t){return e&&e.length>0?e.join(t):void 0}n(Bd,"joinOAuthScopes");function jd(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of pi)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(jd,"sanitizeAuthorizationServerMetadata");function Br(e){let t=jd(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(Br,"sanitizeOAuthDiscoveryState");function mi(e){let t=new URL(e);for(let r of pi){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(mi,"normalizeDuplicateSingletonAuthorizationRequestParams");function Kt(e){let t=new URL(e);return T(t)&&we(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(Kt,"normalizeLoopbackOAuthRedirectUri");function fi(e){return Bd(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(fi,"readProtectedResourceMetadataScope");function Nd(e){return`Zuplo MCP Gateway - ${e}`}n(Nd,"buildGatewayOAuthClientName");function Gd(e,t){return e&&e.length>0?e.join(t):void 0}n(Gd,"joinOAuthScopeList");function jr(e){return new URL(M().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(jr,"buildOAuthClientMetadataDocumentUrl");function Nr(e){let t=Me(e.upstreamServerId);return{client_name:Nd(t.displayName),client_uri:new URL("/",e.origin).toString(),redirect_uris:[e.redirectUri],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",...e.scope===void 0?{}:{scope:e.scope},token_endpoint_auth_method:"none"}}n(Nr,"buildGatewayOAuthClientMetadata");function hi(e,t,r){let o=qe(t,r),i=Gd(o.scopes,o.scopeDelimiter);return{client_id:jr({origin:e,upstreamServerId:t}),...Nr({origin:e,upstreamServerId:t,redirectUri:Kt(new URL(o.redirectPath,e)).toString(),scope:i})}}n(hi,"buildOAuthClientMetadataDocument");$();import{base64url as fe}from"jose";var $d="SHA-256",ze="AES-GCM",Fd=12,$r="zuplo-secret",Fr=1,gi="generated:auth_private_key:token-encryption",Zd=d.object({version:d.literal(Fr),keyId:d.literal(gi),algorithm:d.literal(ze),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();function He(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(He,"copyToArrayBuffer");async function Gr(){return V({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest($d,He(e));return crypto.subtle.importKey("raw",t,{name:ze},!1,["encrypt","decrypt"])},"derive")})}n(Gr,"getEncryptionKey");function yi(e){return He(new TextEncoder().encode(`${$r}:v${e.version}:${e.keyId}`))}n(yi,"getAssociatedData");function Kd(e){return`${$r}:v${e.version}:${fe.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(Kd,"encodeEnvelope");function Jd(e){let t=`${$r}:v${Fr}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(fe.decode(r));return Zd.parse(JSON.parse(o))}n(Jd,"decodeEnvelope");async function Jt(e){let t=await Gr(),r=crypto.getRandomValues(new Uint8Array(Fd)),o={version:Fr,keyId:gi},i=await crypto.subtle.encrypt({name:ze,iv:r,additionalData:yi(o)},t,new TextEncoder().encode(e));return Kd({...o,algorithm:ze,iv:fe.encode(r),ciphertext:fe.encode(new Uint8Array(i))})}n(Jt,"encryptSecret");async function mt(e){let t=Jd(e);if(t){let s=await Gr(),c=await crypto.subtle.decrypt({name:ze,iv:He(fe.decode(t.iv)),additionalData:yi(t)},s,He(fe.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,o]=e.split(".");if(!r||!o)throw new de("Encrypted payload is malformed");let i=await Gr(),a=await crypto.subtle.decrypt({name:ze,iv:He(fe.decode(r))},i,He(fe.decode(o)));return new TextDecoder().decode(a)}n(mt,"decryptSecret");var Wd=d.union([Qe,zt]),wi=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:Dt.optional(),authorizationServerMetadata:d.union([Xe,Ht]).optional()}).passthrough(),Vd="Bearer",Yd="__zuplo_refresh_only_upstream_access_token__";function Xd(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Xd,"splitScopes");function Qd(e){return Et.parse(e)}n(Qd,"parsePkceCodeVerifier");function eu(e){if(typeof e.expires_in=="number")return R(new Date(Date.now()+e.expires_in*1e3))}n(eu,"readTokenExpiry");async function _i(e){if(e!==void 0)return Jt(JSON.stringify(e))}n(_i,"encryptJson");async function Ri(e,t){if(!e)return;let r=await mt(e);try{return t.parse(JSON.parse(r))}catch(o){throw new h({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:o})}}n(Ri,"decryptJson");function tu(e){if(e===void 0)return;e=Br(e);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(tu,"toOAuthDiscoveryState");function ru(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(ru,"clientInformationAllowsRedirectUri");function nu(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(nu,"clientInformationMatchesCurrentClientMetadataUrl");function ou(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(ou,"isUrlBasedClientInformation");function iu(e,t){return t===void 0?e:{...e,scope:t}}n(iu,"applyOAuthClientMetadataScope");function bi(e,t){return fi({state:e,delimiter:t})}n(bi,"readResourceMetadataScope");function au(e,t){return e&&e.length>0?e.join(t):void 0}n(au,"joinOAuthScopeList");function su(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new q(`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(su,"buildManualOAuthClientInformation");function cu(e,t){let r=jr({origin:new URL(t).origin,upstreamServerId:e});return Ur(r)?r:void 0}n(cu,"buildClientMetadataUrl");function Ci(e){for(let t of e)if(t!==void 0)return t}n(Ci,"firstDefined");function du(e){let t=qe(e.target.upstreamServerId,e.target.authProfileId),r=au(t.scopes,t.scopeDelimiter),o=Nr({origin:new URL(e.redirectUri).origin,upstreamServerId:e.target.upstreamServerId,redirectUri:e.redirectUri,scope:r});if(t.clientRegistration.mode==="manual")return{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,configuredClientInformation:su({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let i=cu(e.target.upstreamServerId,e.redirectUri);return i===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,clientMetadataUrl:i}}n(du,"buildInitialOAuthClientSetup");function uu(e,t){if(t===void 0)return Ci([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(uu,"readEncryptedClientInformation");function lu(e){return Ci([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}n(lu,"readEncryptedDiscoveryState");var Ie=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=du({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=uu(t,this.configuredClientInformation),this.encryptedDiscoveryState=lu(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return iu(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return si({id:t.id,...Ye({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,!ou({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await _i(t),await this.syncPendingState(!1)))}async discoveryState(){return this.loadPersistedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=Br(wi.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.inferredScope=bi(r,this.scopeDelimiter),this.encryptedDiscoveryState=await _i(r),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Oe.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=r.refresh_token?await Jt(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:Oe.parse({...r,refresh_token:await mt(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let a={id:this.connection?.id??ho(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await Jt(r.access_token),encryptedRefreshToken:i,scopes:Xd(r.scope??this.readEffectiveScope()),expiresAt:eu(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await b().upsertUpstreamConnection(a)}async redirectToAuthorization(t){let r=mi(t);this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:Qd(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new h({message:"OAuth code verifier is missing",extensionMembers:{[g]:"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:go(),...Ye({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()+oi)),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 b().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 Ri(this.encryptedClientInformation,Wd)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&(!ru(t,this.redirectUriValue)||!nu({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl}))){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}return t===void 0&&this.pendingState?.codeVerifier!==void 0&&this.clientMetadataUrl!==void 0&&(t=zt.parse({client_id:this.clientMetadataUrl})),this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async loadPersistedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;try{this.cachedDiscoveryState=tu(await Ri(this.encryptedDiscoveryState,wi))}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1)}return this.discoveryStateLoaded=!0,this.inferredScope=bi(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 mt(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await mt(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=Oe.parse({access_token:t??Yd,token_type:Vd,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 b().upsertUpstreamConnection(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var pu=3e4,mu=256*1024,fu=2;function hu(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(hu,"hasUsableAccessToken");var gu="does not support dynamic client registration",yu=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],wu=["HTTP 403 Forbidden","Access Denied","permission to access"];function _u(e){return e instanceof Error&&e.message.includes(gu)}n(_u,"isDynamicClientRegistrationUnsupported");function Ru(e){return e instanceof Error&&yu.some(t=>e.message.includes(t))}n(Ru,"isProtectedResourceMetadataUnavailable");function bu(e){return e instanceof Error&&wu.some(t=>e.message.includes(t))}n(bu,"isUpstreamProviderAccessDenied");function Cu(e){if(e.error instanceof h&&e.error.extensionMembers?.[g]!==void 0)return e.error;if(_u(e.error))return new h({message:`The authorization server for ${e.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register an OAuth client for the gateway manually before retrying.`,extensionMembers:{[g]:"upstream_client_registration_required"}},{cause:e.error});if(Ru(e.error))return new h({message:`The upstream MCP server "${e.upstreamServerId}" does not publish OAuth protected resource metadata at "${e.resourceMetadataUrl}". Configure protectedResourceMetadataUrl to a working metadata document, use a provider-supported legacy client, or contact the provider to approve/allowlist this gateway OAuth client before retrying.`,extensionMembers:{[g]:"upstream_oauth_discovery_unavailable"}},{cause:e.error});if(bu(e.error))return new h({message:`The upstream provider denied access while connecting ${e.upstreamServerId}. Confirm the provider allows this gateway and its OAuth client, then retry.`,extensionMembers:{[g]:"upstream_provider_access_denied"}},{cause:e.error})}n(Cu,"mapUpstreamOAuthSetupError");function vu(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(vu,"readOAuthFetchRequest");function Su(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(Su,"responseLooksJson");function Iu(e,t){let r=e.headers.get("content-type")??"",o=t.trimStart().toLowerCase();return r.includes("html")||o.startsWith("<!doctype html")||o.startsWith("<html")}n(Iu,"responseLooksHtml");function xu(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new h({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[g]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[Te]:e.response.status,[ke]:r,[Ee]:e.request.url.toString(),[Pe]:e.body}})}n(xu,"throwUpstreamHtmlError");function vi(e){return async(t,r)=>{let o=vu(t),i=await Go(t,r,{maxRedirects:fu,maxResponseBytes:mu,problemCode:"upstream_token_exchange_failed",timeoutMs:pu}),a=await i.clone().text();if(!i.ok&&Iu(i,a)&&xu({upstreamServerId:e,request:o,response:i,body:a}),!Su(i,a))return i;try{JSON.parse(a)}catch(s){throw new h({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[g]:"upstream_token_exchange_failed"}},{cause:s})}return i}}n(vi,"createUpstreamOAuthFetch");async function Si(e,t){e.applyChallengeScope(t.requestedScope);try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:vi(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),await Ar(e,r)}catch(r){let o=Cu({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(Si,"runUpstreamOAuth");async function Au(e,t){e.applyChallengeScope(t.requestedScope);let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:vi(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),Ar(e,r)}n(Au,"exchangeUpstreamAuthorizationCode");async function Ii(e,t){let r=await Si(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new h({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new h({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Ii,"requireUpstreamAuthorizationRedirect");async function xi(e){if(!e.forceRefresh&&hu(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await Si(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 h({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new h({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}});return{kind:"connect_required",payload:await Eu({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,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(xi,"authorizeUpstreamOAuthSession");async function Uu(e){let t=await Ft(e.stateToken),r=await b().consumeUpstreamOAuthState({id:t.id,now:R(new Date)}),o=ku(r);return Pu({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),Tu(o),o}n(Uu,"consumeStoredCallbackState");function ku(e){switch(e.kind){case"consumed":throw new h({message:"OAuth state has already been used",extensionMembers:{[g]:"oauth_state_reused"}});case"missing":throw new h({message:"OAuth state is missing or expired",extensionMembers:{[g]:"oauth_state_expired"}});case"available":return e.record}}n(ku,"readConsumedCallbackState");function Pu(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 h({message:"OAuth callback did not match the initiating request",extensionMembers:{[g]:"oauth_callback_mismatch"}})}n(Pu,"assertStoredCallbackStateMatches");function Tu(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new h({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}})}n(Tu,"assertStoredCallbackStateFresh");async function Eu(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),li(r)}let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},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),Zt(t)}n(Eu,"buildOAuthConnectRequiredResponse");async function Ai(e){let t=await Uu({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Pt(t),[o]=await b().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 Ie(i),s=await Au(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 h({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${s}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new h({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Ai,"finishUpstreamOAuthCallback");function Ou(e){return Kt(new URL(e.callbackPath,k(e.requestUrl,e.requestHeaders))).toString()}n(Ou,"buildGatewayOAuthRedirectUri");async function Ui(e){let t=Me(e.upstreamServerId),r=qe(e.upstreamServerId,e.authProfileId),o=Ou({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),i="preloadedConnection"in e?e.preloadedConnection:(await b().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:k(e.request.url,e.request.headers)}}}n(Ui,"prepareUpstreamOAuthRequest");async function ki(e){let t=await Ui(e),r=new Ie({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Ii(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(ki,"startUpstreamConnect");async function Pi(e){let t=await Ui(e),r=new Ie({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return xi({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(Pi,"authorizeUpstreamRequest");async function Le(e){let{routeAuth:t}=e;return Pi({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}})}n(Le,"resolveUpstreamCredentialForRoute");async function Ti(e){let t={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}},r=await ki(t);return{authProfileId:e.connectRequest.authProfileId,authUrl:r,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}n(Ti,"startUpstreamConnectForRequest");async function Ei(e){let r=(await Ft(e.callbackRequest.state)).authProfileId;return Or({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}),Ai({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:Me(e.callbackRequest.upstreamServerId)})}n(Ei,"finishUpstreamCallbackForRequest");function Mu(e){return{upstreamServerId:e.connection.upstreamServerId,operationId:e.operationId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(Mu,"buildRouteAuthBaseFromConnection");function Mi(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:Wn(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(Mi,"buildRouteAuthBaseFromPolicyOptions");function Wt(e,t){let o=J().byOperationId.get(t);if(!o)throw new q(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new q(`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 q(`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 Mu({connection:o.connection,operationId:t})}n(Wt,"resolveRouteAuthBase");function Oi(e,t){switch(e){case"user":return kt(t);case"shared":return Kn()}}n(Oi,"buildOwnerForSubject");function Be(e,t){switch(e.ownerMode){case"shared":return{...e,ownerMode:"shared",owner:Oi(e.ownerMode,t),initiatedBySubjectId:t};case"user":return{...e,ownerMode:"user",owner:Oi(e.ownerMode,t),initiatedBySubjectId:t}}}n(Be,"resolveRouteAuthForSubject");var qu=We.InvalidRequest,Du=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function Hu(e,t){return{credentialType:e.type,forceRefresh:t}}n(Hu,"buildCredentialResolvedAttributes");function zu(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(zu,"connectRequiredReasonCode");function qi(e){x(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:Hu(e.credential,e.forceRefresh===!0)})}n(qi,"emitCredentialResolvedAnalyticsEvent");function Di(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(x(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"connect_required",reasonClass:"auth",attributes:t}),e.payload.state==="reconsent_required"){x(e.context,{eventType:C.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}x(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:zu(e.payload.state),reasonClass:"auth",attributes:t})}n(Di,"emitCredentialMissingAnalyticsEvents");function Lu(e){let t=e.route.raw();return xt.parse(t?.operationId)}n(Lu,"readOperationId");async function Bu(e,t,r,o){let i=await Le({request:e,routeAuth:t});if(i.kind==="connect_required")return Di({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;qi({context:o,credential:a,routeBinding:t});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(Bu,"buildCredentialHeaders");var ju=new Set(["authorization","cookie","cookie2"]);function Nu(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return t&&typeof t=="object"&&!Array.isArray(t)&&"method"in t&&typeof t.method=="string"?t.method:void 0}catch{return}}n(Nu,"readJsonRequestMethod");function Gu(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(Gu,"isJsonResponse");function Zr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Zr,"isRecord");function $u(e){return Array.isArray(e)&&e.length>0}n($u,"hasIconList");function Fu(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=Bt(Bn(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(Fu,"readFallbackServerIcons");function Zu(e){if(!Zr(e.body))return e.body;let t=e.body.result;if(!Zr(t))return e.body;let r=t.serverInfo;return!Zr(r)||$u(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n(Zu,"addMissingServerIcons");function Ku(e,t){let r=new Headers(e.headers);for(let o of ju)r.delete(o);for(let[o,i]of t)r.set(o,i);return new xn(e,{headers:r})}n(Ku,"applyUpstreamHeaders");function Ju(e){let t=new Headers(e.headers);for(let r of Du)t.delete(r);return t}n(Ju,"buildProxyHeaders");async function Wu(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(Wu,"readRetryBody");function Hi(e,t){let r=t.authUrl===void 0?void 0:Ro({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(Mt({id:_o(e),error:{code:r?.code??qu,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(Hi,"connectRequiredJsonRpcResponse");async function Vu(e){let{scope:t}=Eo(e.upstreamResponse),r=await Le({request:e.request,routeAuth:e.routeAuth,forceRefresh:!0,...t===void 0?{}:{requestedScope:t}});if(r.kind==="connect_required")return Di({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;qi({context:e.context,credential:i,routeBinding:e.routeAuth,forceRefresh:!0});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(Vu,"applyRefreshedCredentialHeaders");function Yu(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await Vu({request:e.request,context:e.context,headers:Ju(r),routeAuth:e.routeAuth,upstreamResponse:t});if(o.kind==="connect_required")return Hi(e.requestBody,o.payload);if(o.kind==="response")return o.response;let i=jn({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return Rt.fetch(i.url,i.init)})}n(Yu,"installUpstreamAuthRetryHook");function Xu(e){if(Nu(e.requestBody)!=="initialize")return;let t=Fu({connection:e.connection,context:e.context});t===void 0||t.length===0||e.context.addResponseSendingHook(async r=>{if(!Gu(r))return r;let o;try{o=await r.clone().json()}catch{return r}let i=Zu({body:o,icons:t});if(i===o)return r;let a=new Headers(r.headers);return a.delete("content-length"),new Response(JSON.stringify(i),{status:r.status,statusText:r.statusText,headers:a})})}n(Xu,"installInitializeIconHook");async function Kr(e,t,r){let o=Lu(t),i=await Wu(e),a=Mi({connection:r,operationId:o}),s=_e(e.user,e.url,e.headers);to(t,s);let c=Be(a,s.subjectId),u=await Bu(e,c,r,t);if(!(u instanceof Response)&&u.kind==="connect_required")return Hi(i,u.payload);if(u instanceof Response)return u;let p=Ku(e,u.headers);return Yu({request:p,context:t,requestBody:i,routeAuth:c}),Xu({context:t,requestBody:i,connection:r}),p}n(Kr,"mcpTokenExchangePolicy");var Jr=class extends Ct{static{n(this,"McpTokenExchangeInboundPolicy")}constructor(t,r){let o=Vn(t,r);super(o,r)}async handler(t,r){return bt("policy.inbound.mcp-token-exchange"),Kr(t,r,this.options)}};$();var zi=Symbol("Html");function Qu(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}n(Qu,"escapeHtml");function el(e){return e===null||typeof e!="object"?!1:e[zi]===!0}n(el,"isHtml");function Li(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Li).join(""):el(e)?e.value:Qu(String(e))}n(Li,"renderValue");function ae(e){return{[zi]:!0,value:e}}n(ae,"trustedHtml");var Y=ae("");function v(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=Li(t[o]),r+=e[o+1]??"";return ae(r)}n(v,"html");function je(e){return e.value}n(je,"renderHtml");function Bi(e){return v`<p class="card__description">${e.detail}</p>${e.guidance} ${e.technicalDetails} ${e.action}`}n(Bi,"renderBrowserErrorPage");var Ne=ae('*,: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 Ge(e){return v`<!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
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(Ge,"renderShell");var tl="text/html; charset=utf-8";function $e(e){try{return new URL(e).host}catch{return""}}n($e,"safeHostFromUrl");function X(e){let t=nl(e.kind??"authorization_failed"),r=rl(e);return new Response(je(Ge({title:e.title??t.title,iconHref:"",styles:Ne,headerIcon:Y,heading:e.title??t.title,subhead:"",body:Bi({detail:e.detail,guidance:v`<p class="card__description">${t.guidance}</p>`,technicalDetails:cl({diagnostic:r,upstreamHtml:e.upstreamHtml}),action:al(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":tl,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(X,"browserErrorPageResponse");function rl(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??ol(t),timestamp:e.diagnostic?.timestamp??new Date().toISOString(),...e.requestId===void 0&&e.diagnostic?.requestId===void 0?{}:{requestId:e.diagnostic?.requestId??e.requestId},...e.diagnostic?.operationId===void 0?{}:{operationId:e.diagnostic.operationId},...e.diagnostic?.routePath===void 0?{}:{routePath:e.diagnostic.routePath},...e.diagnostic?.upstreamServerId===void 0?{}:{upstreamServerId:e.diagnostic.upstreamServerId},...e.diagnostic?.authProfileId===void 0?{}:{authProfileId:e.diagnostic.authProfileId},...e.diagnostic?.upstreamUrl===void 0?{}:{upstreamUrl:e.diagnostic.upstreamUrl},...e.diagnostic?.metadataUrl===void 0?{}:{metadataUrl:e.diagnostic.metadataUrl},...e.diagnostic?.httpStatus===void 0?{}:{httpStatus:e.diagnostic.httpStatus},...e.diagnostic?.contentType===void 0?{}:{contentType:e.diagnostic.contentType},...e.diagnostic?.providerError===void 0?{}:{providerError:e.diagnostic.providerError},...e.diagnostic?.providerErrorDescription===void 0?{}:{providerErrorDescription:e.diagnostic.providerErrorDescription},suggestedFix:e.diagnostic?.suggestedFix??il(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}n(rl,"buildBrowserErrorDiagnostic");function nl(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(nl,"readBrowserErrorPagePresentation");function ol(e){switch(e){case"upstream_oauth_discovery_unavailable":return"upstream_oauth_discovery";case"upstream_client_registration_required":return"upstream_oauth_client_registration";case"upstream_provider_access_denied":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"upstream_token_exchange";case"provider_access_denied":return"upstream_oauth_callback";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"upstream_oauth_state";case"browser_login_verification_failed":return"downstream_browser_login";case"authentication_required":case"identity_context_missing":return"downstream_auth";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"gateway_configuration";case"server_error":case"internal_server_error":return"gateway_internal";default:return"gateway_request"}}n(ol,"readBrowserErrorStage");function il(e){switch(e){case"upstream_oauth_discovery_unavailable":return"Confirm the upstream MCP URL and OAuth protected resource metadata. If the provider requires approval, configure the provider app or contact the provider.";case"upstream_client_registration_required":return"Register an OAuth client with the upstream provider, then configure the gateway to use that client before retrying.";case"upstream_provider_access_denied":return"Confirm the provider allows this gateway, OAuth client, and upstream MCP URL, then retry the connection.";case"upstream_token_exchange_failed":return"Retry the connection. If it repeats, verify the upstream OAuth client, redirect URI, token endpoint, and provider allowlist.";case"upstream_token_response_invalid":return"Verify the upstream token endpoint returns a valid OAuth token response for this gateway client.";case"provider_access_denied":return"Start the connection again if access was denied by mistake. Otherwise, grant the requested upstream provider access.";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"Start a new connection from the MCP client. The previous browser authorization request cannot be resumed.";case"browser_login_verification_failed":return"Retry the browser login flow. If it repeats, verify the downstream login callback configuration.";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"Check the MCP route, upstream server, and auth profile entries in the gateway configuration.";case"authentication_required":case"identity_context_missing":return"Verify the normal Zuplo auth policy runs before the MCP gateway policy and sets request.user.";case"server_error":case"internal_server_error":return"Retry later and check gateway logs with the request ID.";default:return"Check the gateway configuration and request details associated with this error code."}}n(il,"readBrowserErrorSuggestedFix");function al(e){return e===void 0?Y:v`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(al,"renderAction");function sl(e){let t=[["Error code",e.code],["Stage",e.stage],["Request ID",e.requestId],["Time",e.timestamp],["Gateway route",e.routePath],["Operation ID",e.operationId],["Upstream",e.upstreamServerId],["Auth profile",e.authProfileId],["Upstream URL",e.upstreamUrl],["Metadata URL",e.metadataUrl],["HTTP status",e.httpStatus],["Content type",e.contentType],["Provider error",e.providerError],["Provider error description",e.providerErrorDescription],["Suggested fix",e.suggestedFix],["Underlying error",e.underlyingError]].filter(r=>r[1]!==void 0).map(([r,o])=>`${r}: ${o}`).join(`
|
|
28
28
|
`);return v`<pre class="banner__message" style="white-space: pre-wrap; overflow-wrap: anywhere; margin-top: 8px;"><code>${t}</code></pre>`}n(sl,"renderTechnicalPre");function Vt(e){return e.value===void 0||e.value===""?Y:v`<p class="banner__message"><strong>${e.label}:</strong> <code>${e.value}</code></p>`}n(Vt,"renderOptionalTechnicalRow");function cl(e){return v`<section class="banner banner--warning" aria-label="Developer details">
|