@zuplo/runtime 6.70.56 → 6.70.57

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/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 Er,A as I,Aa as Ht,Ab as cr,Ad as os,B as J,Ba as Pt,Bb as hr,Bd as as,C as K,Ca as St,Cb as mr,Cd as ns,D as M,Da as Tt,Db as gr,Dd as is,E as N,Ea as Ut,Eb as dr,Ed as ps,F as O,Fa as $t,Fb as ur,Fd as cs,Ga as kt,Gb as fr,Gd as hs,Ha as Ft,Hb as xr,Hd as ms,Ia as Lt,Ib as yr,Id as gs,Ja as Rt,Jd as ds,Ka as qt,Kd as us,La as vt,Ld as fs,Ma as zt,Md as xs,Na as Gt,Nd as ys,Oa as It,Pa as Jt,Qa as Kt,Ra as Mt,Sa as Nt,Ta as Ot,Tc as wr,U as Q,Ua as Qt,Uc as Ar,V,Va as Vt,Vc as br,W,Wa as Wt,Wc as lr,X,Xa as Xt,Xc as jr,Y,Ya as Yt,Yc as Br,Z,Za as Zt,Zc as Cr,_,_a as _t,_c as Dr,a as n,aa as rt,ab as rr,ad as Hr,b as x,ba as st,bb as sr,bd as Pr,c as y,ca as et,cb as er,cd as Sr,d as w,da as ot,db as or,dd as Tr,e as A,ea as at,eb as ar,ed as Ur,f as b,fa as nt,fb as nr,fd as $r,g as l,ga as it,gd as kr,h as j,ha as pt,hd as Fr,i as B,ia as ct,id as Lr,ja as ht,jd as Rr,k as C,ka as mt,kd as qr,l as D,la as gt,ld as vr,m as E,ma as dt,md as Mr,n as H,na as ut,nd as Nr,o as P,oa as ft,od as Or,pa as xt,pd as Qr,q as T,qa as yt,qd as Vr,r as U,ra as wt,rd as Wr,s as $,sa as At,sd as Xr,t as k,ta as bt,td as Yr,u as F,ua as lt,ud as Zr,v as L,va as jt,vd as _r,w as R,wa as Bt,wd as ts,x as q,xa as Ct,xd as rs,y as v,ya as Dt,yb as ir,yd as ss,z as G,za as Et,zb as pr,zd as es}from"./chunk-IASCNBZZ.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,wr as McpAuth0OAuthInboundPolicy,ir as McpClerkOAuthInboundPolicy,pr as McpCognitoOAuthInboundPolicy,cr as McpEntraOAuthInboundPolicy,xt as McpGatewayOAuthProtectedResourcePlugin,hr as McpGoogleOAuthInboundPolicy,mr as McpKeycloakOAuthInboundPolicy,gr as McpLogtoOAuthInboundPolicy,dr as McpOAuthInboundPolicy,ur as McpOktaOAuthInboundPolicy,fr as McpOneLoginOAuthInboundPolicy,xr as McpPingOAuthInboundPolicy,yr 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};
25
+ import{$ as tt,$a as tr,$c as Er,A as I,Aa as Ht,Ab as cr,Ad as os,B as J,Ba as Pt,Bb as hr,Bd as as,C as K,Ca as St,Cb as mr,Cd as ns,D as M,Da as Tt,Db as gr,Dd as is,E as N,Ea as Ut,Eb as dr,Ed as ps,F as O,Fa as $t,Fb as ur,Fd as cs,Ga as kt,Gb as fr,Gd as hs,Ha as Ft,Hb as xr,Hd as ms,Ia as Lt,Ib as yr,Id as gs,Ja as Rt,Jd as ds,Ka as qt,Kd as us,La as vt,Ld as fs,Ma as zt,Md as xs,Na as Gt,Nd as ys,Oa as It,Pa as Jt,Qa as Kt,Ra as Mt,Sa as Nt,Ta as Ot,Tc as wr,U as Q,Ua as Qt,Uc as Ar,V,Va as Vt,Vc as br,W,Wa as Wt,Wc as lr,X,Xa as Xt,Xc as jr,Y,Ya as Yt,Yc as Br,Z,Za as Zt,Zc as Cr,_,_a as _t,_c as Dr,a as n,aa as rt,ab as rr,ad as Hr,b as x,ba as st,bb as sr,bd as Pr,c as y,ca as et,cb as er,cd as Sr,d as w,da as ot,db as or,dd as Tr,e as A,ea as at,eb as ar,ed as Ur,f as b,fa as nt,fb as nr,fd as $r,g as l,ga as it,gd as kr,h as j,ha as pt,hd as Fr,i as B,ia as ct,id as Lr,ja as ht,jd as Rr,k as C,ka as mt,kd as qr,l as D,la as gt,ld as vr,m as E,ma as dt,md as Mr,n as H,na as ut,nd as Nr,o as P,oa as ft,od as Or,pa as xt,pd as Qr,q as T,qa as yt,qd as Vr,r as U,ra as wt,rd as Wr,s as $,sa as At,sd as Xr,t as k,ta as bt,td as Yr,u as F,ua as lt,ud as Zr,v as L,va as jt,vd as _r,w as R,wa as Bt,wd as ts,x as q,xa as Ct,xd as rs,y as v,ya as Dt,yb as ir,yd as ss,z as G,za as Et,zb as pr,zd as es}from"./chunk-XAW2AYUG.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,wr as McpAuth0OAuthInboundPolicy,ir as McpClerkOAuthInboundPolicy,pr as McpCognitoOAuthInboundPolicy,cr as McpEntraOAuthInboundPolicy,xt as McpGatewayOAuthProtectedResourcePlugin,hr as McpGoogleOAuthInboundPolicy,mr as McpKeycloakOAuthInboundPolicy,gr as McpLogtoOAuthInboundPolicy,dr as McpOAuthInboundPolicy,ur as McpOktaOAuthInboundPolicy,fr as McpOneLoginOAuthInboundPolicy,xr as McpPingOAuthInboundPolicy,yr 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 kt,Ab as Ds,Ac as oo,Bb as Hs,Bc as io,Cb as zs,Cc as fr,Db as Ls,Dc as ao,Eb as Bs,Ec as so,Fb as js,Fc as hr,G as An,Gb as Ns,Gc as _e,H as l,Hb as Gs,Hc as co,I as Un,Ib as $s,Ic as uo,J as sr,Jb as zn,Jc as lo,K as ee,Kb as Ln,Kc as po,L as kn,Lb as Bn,Lc as mo,M as y,Mb as It,Mc as fo,N as de,Nb as cr,Nc as ho,O as Ct,Ob as xt,Oc as b,P as Pn,Pb as At,Pc as x,Q as Tn,Qb as Je,Qc as le,R as En,Rb as jn,Rc as U,S as d,Sb as Nn,Sc as go,T as G,Tb as Gn,Tc as Fs,Ub as We,Vb as $n,Wb as Ut,Xb as Fn,Yb as dr,Z as On,Zb as Zn,_b as Ve,a as Rt,ac as Kn,bc as Jn,cc as Wn,dc as Vn,ec as K,fc as Yn,gb as ye,gc as Xn,hb as T,hc as R,i as ge,ib as qn,ic as re,j as Sn,jb as g,jc as k,kb as Ue,kc as Pt,l as In,lb as ke,lc as L,mb as Pe,mc as F,nb as Te,nc as Qn,ob as vt,oc as eo,p as xn,pb as Mn,pc as Tt,qb as $,qc as to,r as bt,rb as Dn,rc as ne,sb as te,sc as ur,tb as _,tc as lr,ub as St,uc as ro,vb as M,vc as Et,wb as ue,wc as pr,xb as Hn,xc as mr,yb as qs,yc as no,zb as Ms,zc as D}from"../chunk-IASCNBZZ.js";import{d as ar}from"../chunk-JRXZBVXH.js";import{a as C}from"../chunk-4SACVMDH.js";import{$ as ce,a as n,aa as h,ba as q,ca as vn,da as wt}from"../chunk-ZIKV2LUM.js";G();function Zs(e){let t=At.safeParse(e);return t.success?t.data.id:void 0}n(Zs,"parseJsonRpcRequestId");function yo(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Zs(t)}catch{return}}n(yo,"readJsonRpcRequestIdFromBody");function Ot(e){return jn.parse({jsonrpc:xt,...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(Ot,"jsonRpcErrorResponse");function _o(e){return new Gn([Nn.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(_o,"urlElicitationRequiredError");var qt=d.record(d.string(),d.unknown()),Ks=d.record(d.string(),d.unknown()),Js=d.object({name:d.string().min(1),description:d.string().min(1).optional(),annotations:Ks.optional(),_meta:qt.optional()}).strict(),Ws=d.object({name:d.string().min(1),description:d.string().min(1).optional(),_meta:qt.optional()}).strict(),Vs=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(),Ys=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(),Xs=d.array(d.union([d.string(),Js])),Qs=d.array(d.union([d.string(),Ws])),ec=d.array(d.union([d.string(),Vs])),tc=d.array(d.union([d.string(),Ys])),rc=d.object({tools:Xs.optional(),prompts:Qs.optional(),resources:ec.optional(),resourceTemplates:tc.optional()}).strict(),yr=[{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 nc(e,t){return Hn(rc,e,`MCP capability filter policy "${t}"`)}n(nc,"parseMcpCapabilityFilterOptions");function H(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(H,"isRecord");function oc(e,t){if(!H(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(oc,"readParamString");function _r(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(_r,"readRequestId");function Co(e){return e===void 0?void 0:JSON.stringify(e)}n(Co,"requestIdKey");function ic(e){let t={};for(let r of yr){let o=e[r.option];if(o===void 0)continue;let i=new Map;for(let a of o){let s=dc(a,r.itemProperty);s!==void 0&&i.set(s.key,s)}t[r.option]=i}return t}n(ic,"buildProjectionMaps");function wr(e){return yr.find(t=>t.listMethod===e)}n(wr,"findListRule");function ac(e){return e.requests.some(t=>{if(!H(t))return!1;let r=wr(t.method);return r!==void 0&&e.projectionMaps[r.option]!==void 0})}n(ac,"shouldFilterListResponses");function sc(e){for(let t of yr){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=oc(e.request.params,o.paramProperty);if(i!==void 0&&!r.has(i))return{id:_r(e.request)}}}}n(sc,"findDisallowedDirectAccess");function cc(e){return Response.json(Ot({id:e,error:{code:Je.MethodNotFound,message:"Method not found"}}))}n(cc,"methodNotFoundResponse");function dc(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!H(e))return;let r=e[t];if(typeof r=="string")return{key:r,overlay:e}}n(dc,"buildProjection");function wo(e){let t=e.base[e.property],r=e.overlay[e.property];return H(r)?H(t)?{...t,...r}:r:t}n(wo,"mergeRecordProperty");function uc(e,t){let r={...e,...t.overlay},o=wo({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let i=wo({base:e,overlay:t.overlay,property:"_meta"});return i!==void 0&&(r._meta=i),r}n(uc,"applyProjection");function Ro(e,t,r){if(!H(e))return e;let o=e.result;if(!H(o))return e;let i=o[t.resultProperty];return!Array.isArray(i)||!i.every(a=>H(a)&&typeof a[t.itemProperty]=="string")?e:{...e,result:{...o,[t.resultProperty]:i.flatMap(a=>{if(!H(a))return[];let s=a[t.itemProperty];if(typeof s!="string")return[];let c=r.get(s);return c===void 0?[]:[uc(a,c)]})}}}n(Ro,"filterAndProjectItems");function lc(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!H(r))continue;let o=wr(r.method),i=_r(r),a=Co(i);o!==void 0&&a!==void 0&&t.set(a,o)}return t}n(lc,"buildListRulesByResponseId");function pc(e){if(Array.isArray(e.responseBody)){let o=lc(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(i=>{if(!H(i)||"error"in i)return i;let a=Co(_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:Ro(i,s,c)})}if(!H(e.requestBody)||!H(e.responseBody)||"error"in e.responseBody)return e.responseBody;let t=wr(e.requestBody.method),r=t===void 0?void 0:e.projectionMaps[t.option];return t===void 0||r===void 0?e.responseBody:Ro(e.responseBody,t,r)}n(pc,"filterJsonRpcResponse");async function bo(e){return e.clone().json()}n(bo,"readJson");function mc(e){return e.headers.get("content-type")?.includes("json")??!1}n(mc,"isJsonResponse");var gr=class extends bt{static{n(this,"McpCapabilityFilterInboundPolicy")}#e;constructor(t,r){let o=nc(t,r);super(o,r),this.#e=ic(o)}async handler(t,r){Rt("policy.inbound.mcp-capability-filter");let o;try{o=await bo(t)}catch{return t}let i=Array.isArray(o)?o:[o];for(let a of i){if(!H(a))continue;let s=sc({request:a,projectionMaps:this.#e});if(s!==void 0)return cc(s.id)}return ac({requests:i,projectionMaps:this.#e})&&r.addResponseSendingHook(async a=>{if(!mc(a))return a;let s;try{s=await bo(a)}catch{return a}let c=pc({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 Rr;Rr=globalThis.crypto;async function fc(e){return(await Rr).getRandomValues(new Uint8Array(e))}n(fc,"getRandomValues");async function hc(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await fc(e-o.length);for(let a of i)a<r&&(o+=t[a%t.length])}return o}n(hc,"random");async function gc(e){return await hc(e)}n(gc,"generateVerifier");async function yc(e){let t=await(await Rr).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(yc,"generateChallenge");async function br(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await gc(e),r=await yc(t);return{code_verifier:t,code_challenge:r}}n(br,"pkceChallenge");G();var E=Un().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Tn.custom,message:"URL must be parseable",fatal:!0}),An}).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"}),Mt=Ct({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:ee().optional(),authorization_details_types_supported:y(l()).optional(),dpop_signing_alg_values_supported:y(l()).optional(),dpop_bound_access_tokens_required:ee().optional()}),Ye=Ct({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:ee().optional()}),_c=Ct({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:ee().optional(),request_parameter_supported:ee().optional(),request_uri_parameter_supported:ee().optional(),require_request_uri_registration:ee().optional(),op_policy_uri:E.optional(),op_tos_uri:E.optional(),client_id_metadata_document_supported:ee().optional()}),Dt=de({..._c.shape,...Ye.pick({code_challenge_methods_supported:!0}).shape}),Ee=de({access_token:l(),id_token:l().optional(),token_type:l(),expires_in:En.number().optional(),scope:l().optional(),refresh_token:l().optional()}).strip(),So=de({error:l(),error_description:l().optional(),error_uri:l().optional()}),vo=E.optional().or(Pn("").transform(()=>{})),wc=de({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:vo,scope:l().optional(),contacts:y(l()).optional(),tos_uri:vo,policy_uri:l().optional(),jwks_uri:E.optional(),jwks:kn().optional(),software_id:l().optional(),software_version:l().optional(),software_statement:l().optional()}).strip(),Ht=de({client_id:l(),client_secret:l().optional(),client_id_issued_at:sr().optional(),client_secret_expires_at:sr().optional()}).strip(),Xe=wc.merge(Ht),Kf=de({error:l(),error_description:l().optional()}).strip(),Jf=de({token:l(),token_type_hint:l().optional()}).strip();function Io(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(Io,"resourceUrlFromServerUrl");function xo({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(xo,"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}},Qe=class extends A{static{n(this,"InvalidRequestError")}};Qe.errorCode="invalid_request";var we=class extends A{static{n(this,"InvalidClientError")}};we.errorCode="invalid_client";var Re=class extends A{static{n(this,"InvalidGrantError")}};Re.errorCode="invalid_grant";var be=class extends A{static{n(this,"UnauthorizedClientError")}};be.errorCode="unauthorized_client";var et=class extends A{static{n(this,"UnsupportedGrantTypeError")}};et.errorCode="unsupported_grant_type";var tt=class extends A{static{n(this,"InvalidScopeError")}};tt.errorCode="invalid_scope";var rt=class extends A{static{n(this,"AccessDeniedError")}};rt.errorCode="access_denied";var oe=class extends A{static{n(this,"ServerError")}};oe.errorCode="server_error";var nt=class extends A{static{n(this,"TemporarilyUnavailableError")}};nt.errorCode="temporarily_unavailable";var ot=class extends A{static{n(this,"UnsupportedResponseTypeError")}};ot.errorCode="unsupported_response_type";var it=class extends A{static{n(this,"UnsupportedTokenTypeError")}};it.errorCode="unsupported_token_type";var at=class extends A{static{n(this,"InvalidTokenError")}};at.errorCode="invalid_token";var st=class extends A{static{n(this,"MethodNotAllowedError")}};st.errorCode="method_not_allowed";var ct=class extends A{static{n(this,"TooManyRequestsError")}};ct.errorCode="too_many_requests";var Ce=class extends A{static{n(this,"InvalidClientMetadataError")}};Ce.errorCode="invalid_client_metadata";var dt=class extends A{static{n(this,"InsufficientScopeError")}};dt.errorCode="insufficient_scope";var ut=class extends A{static{n(this,"InvalidTargetError")}};ut.errorCode="invalid_target";var Ao={[Qe.errorCode]:Qe,[we.errorCode]:we,[Re.errorCode]:Re,[be.errorCode]:be,[et.errorCode]:et,[tt.errorCode]:tt,[rt.errorCode]:rt,[oe.errorCode]:oe,[nt.errorCode]:nt,[ot.errorCode]:ot,[it.errorCode]:it,[at.errorCode]:at,[st.errorCode]:st,[ct.errorCode]:ct,[Ce.errorCode]:Ce,[dt.errorCode]:dt,[ut.errorCode]:ut};function Rc(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(Rc,"isClientAuthMethod");var Cr="code",vr="S256";function bc(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Rc(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(bc,"selectClientAuthMethod");function Cc(e,t,r,o){let{client_id:i,client_secret:a}=t;switch(e){case"client_secret_basic":vc(i,a,r);return;case"client_secret_post":Sc(i,a,o);return;case"none":Ic(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(Cc,"applyClientAuthentication");function vc(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(vc,"applyBasicAuth");function Sc(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(Sc,"applyPostAuth");function Ic(e,t){t.set("client_id",e)}n(Ic,"applyPublicAuth");async function ko(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=So.parse(JSON.parse(r)),{error:i,error_description:a,error_uri:s}=o,c=Ao[i]||oe;return new c(a||"",s)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new oe(i)}}n(ko,"parseErrorResponse");async function xr(e,t){try{return await Sr(e,t)}catch(r){if(r instanceof we||r instanceof be)return await e.invalidateCredentials?.("all"),await Sr(e,t);if(r instanceof Re)return await e.invalidateCredentials?.("tokens"),await Sr(e,t);throw r}}n(xr,"auth");async function Sr(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 Eo(u,{fetchFn:a}),!c)try{c=await To(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 Tc(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 w=await xc(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&&!Ar(O))throw new Ce(`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 Cn=await Dc(u,{metadata:p,clientMetadata:e.clientMetadata,scope:S,fetchFn:a});await e.saveClientInformation(Cn),I=Cn}}let N=!e.redirectUrl;if(r!==void 0||N){let P=await Mc(e,u,{metadata:p,resource:w,authorizationCode:r,fetchFn:a});return await e.saveTokens(P),"AUTHORIZED"}let Z=await e.tokens();if(Z?.refresh_token)try{let P=await qc(u,{metadata:p,clientInformation:I,refreshToken:Z.refresh_token,resource:w,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(P),"AUTHORIZED"}catch(P){if(!(!(P instanceof A)||P instanceof oe))throw P}let X=e.state?await e.state():void 0,{authorizationUrl:Ke,codeVerifier:Q}=await Ec(u,{metadata:p,clientInformation:I,state:X,redirectUrl:e.redirectUrl,scope:S,resource:w});return await e.saveCodeVerifier(Q),await e.redirectToAuthorization(Ke),"REDIRECT"}n(Sr,"authInternal");function Ar(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(Ar,"isHttpsUrl");async function xc(e,t,r){let o=Io(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!xo({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(xc,"selectResourceURL");function Po(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let i=Ir(e,"resource_metadata")||void 0,a;if(i)try{a=new URL(i)}catch{}let s=Ir(e,"scope")||void 0,c=Ir(e,"error")||void 0;return{resourceMetadataUrl:a,scope:s,error:c}}n(Po,"extractWWWAuthenticateParams");function Ir(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(Ir,"extractFieldFromWwwAuth");async function To(e,t,r=fetch){let o=await kc(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 Mt.parse(await o.json())}n(To,"discoverOAuthProtectedResourceMetadata");async function Ur(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Ur(e,void 0,r):void 0;throw o}}n(Ur,"fetchWithCorsRetry");function Ac(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(Ac,"buildWellKnownPath");async function Uo(e,t,r=fetch){return await Ur(e,{"MCP-Protocol-Version":t},r)}n(Uo,"tryMetadataDiscovery");function Uc(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(Uc,"shouldAttemptFallback");async function kc(e,t,r,o){let i=new URL(e),a=o?.protocolVersion??cr,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let u=Ac(t,i.pathname);s=new URL(u,o?.metadataServerUrl??i),s.search=i.search}let c=await Uo(s,a,r);if(!o?.metadataUrl&&Uc(c,i.pathname)){let u=new URL(`/.well-known/${t}`,i);c=await Uo(u,a,r)}return c}n(kc,"discoverMetadataWithFallback");function Pc(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(Pc,"buildDiscoveryUrls");async function Eo(e,{fetchFn:t=fetch,protocolVersion:r=cr}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=Pc(e);for(let{url:a,type:s}of i){let c=await Ur(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"?Ye.parse(await c.json()):Dt.parse(await c.json())}}}n(Eo,"discoverAuthorizationServerMetadata");async function Tc(e,t){let r,o;try{r=await To(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 Eo(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(Tc,"discoverOAuthServerInfo");async function Ec(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(Cr))throw new Error(`Incompatible auth server: does not support response type ${Cr}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(vr))throw new Error(`Incompatible auth server: does not support code challenge method ${vr}`)}else c=new URL("/authorize",e);let u=await br(),p=u.code_verifier,f=u.code_challenge;return c.searchParams.set("response_type",Cr),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",f),c.searchParams.set("code_challenge_method",vr),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(Ec,"startAuthorization");function Oc(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(Oc,"prepareAuthorizationCodeRequest");async function Oo(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??[],w=bc(o,f);Cc(w,o,u,r)}let p=await(s??fetch)(c,{method:"POST",headers:u,body:r});if(!p.ok)throw await ko(p);return Ee.parse(await p.json())}n(Oo,"executeTokenRequest");async function qc(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 Oo(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:a,resource:i,fetchFn:s});return{refresh_token:o,...u}}n(qc,"refreshAuthorization");async function Mc(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=Oc(i,p,e.redirectUrl)}let u=await e.clientInformation();return Oo(t,{metadata:r,tokenRequestParams:c,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(Mc,"fetchToken");async function Dc(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 ko(s);return Xe.parse(await s.json())}n(Dc,"registerClient");var kr="zuplo.com",Hc=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),zc=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function qo(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(qo,"s2FaviconHref");function Lc(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(Lc,"strictFaviconHref");var zt=qo(kr);function Pr(e){let t=e.toLowerCase();return t===kr||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?qo(kr):Lc(e)}n(Pr,"resolveIconHref");function Bc(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(Bc,"hostnameFromHost");function jc(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(jc,"isLocalOrAddressHost");function Nc(e){let t=Bc(e).toLowerCase().replace(/\.$/,"");if(jc(t)||zc.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=Hc.has(o)?3:2;return r.slice(-i).join(".")}n(Nc,"inferFaviconDomain");function Tr(e){return{src:Pr(Nc(e)),mimeType:"image/png",sizes:["128x128"]}}n(Tr,"resolveMcpFaviconIcon");function Lt(e){try{return Tr(new URL(e).host)}catch{return}}n(Lt,"resolveMcpFaviconIconFromUrl");function Oe(e){let t=K().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(Oe,"getUpstreamServerConfig");function Gc(e){let t=K().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(Gc,"resolveUpstreamAuthProfileId");function Er(e){Gc(e);let t=K().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(Er,"getUpstreamAuthConfig");function qe(e,t){return Er({upstreamServerId:e,authProfileId:t})}n(qe,"requireUpstreamOAuthConfig");function J(e){return new h({message:e,extensionMembers:{[g]:"invalid_request"}})}n(J,"invalidOutboundUrl");function $c(){let e=ar.__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($c,"isTestOnlyAllowHttpLoopbackIdpEnabled");function Fc(){let e=ar.__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(Fc,"isTestOnlyAllowHttpLoopbackCimdEnabled");var Zc=new Set(["undefined","null","nan"]);function qr(e,t){if(!e.hostname)throw J(`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(Zc.has(e.hostname.toLowerCase()))throw J(`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 Kc=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),Jc=[{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 Mo(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(Mo,"parseIpv4Octets");function Wc([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(Wc,"ipv4RangeMatches");function Do(e){let t=Mo(e);return t!==void 0&&Jc.some(r=>Wc(t,r))}n(Do,"isPrivateIpv4");function Or(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(Or,"parseIpv6Word");function Vc(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}n(Vc,"formatIpv4FromWords");function Yc(e){let t=e.slice(7),r=Mo(t);if(r!==void 0)return r.join(".");let[o,i,a]=t.split(":"),s=Or(o),c=Or(i);return a===void 0&&s!==void 0&&c!==void 0?Vc(s,c):void 0}n(Yc,"parseIpv6MappedIpv4");function Xc(e){return Or(e.split(":").find(Boolean))}n(Xc,"readFirstIpv6Hextet");function Qc(e){let t=ye(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let o=Yc(t);return o===void 0||Do(o)}let r=Xc(t);return r===void 0?!1:(r&65024)===64512||(r&65472)===65152}n(Qc,"isPrivateIpv6");function Mr(e){let t=ye(e);return Kc.has(t)||t.endsWith(".internal")||Do(t)||Qc(t)}n(Mr,"isBlockedOutboundHostname");function Bt(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw J(`Unsupported outbound protocol: ${t.protocol}`);qr(t,e);let r=T(t);if(t.protocol==="http:"&&!r)throw J("Configured outbound HTTP URLs must target loopback hosts.");let o=ye(t.hostname);if(!r&&Mr(o))throw J(`Blocked outbound host: ${o}`);return t}n(Bt,"validateConfiguredOutboundUrl");function Ho(e){let t=new URL(e),r=T(t),o=r&&$c();if(t.protocol!=="https:"&&!o)throw J("Identity provider URLs must use https.");if(t.username||t.password||t.search||t.hash)throw J("Identity provider URLs must not include credentials, query params, or fragments.");qr(t,e);let i=ye(t.hostname);if(!r&&Mr(i))throw J(`Blocked identity provider host: ${i}`);return t}n(Ho,"validateIdentityProviderUrl");function zo(e,t){let r=new URL(e),o=r.protocol==="http:"&&T(r)&&Fc();if(r.protocol!=="https:"&&!o||r.pathname==="/"||r.username||r.password||r.hash)throw J(`CIMD ${t} must be an HTTPS URL with a path and no credentials or fragment.`);if(qr(r,e),!o&&Mr(r.hostname))throw J(`CIMD ${t} points at a blocked host.`);return r}n(zo,"validateCimdUrl");function jt(e){return zo(e,"client_id")}n(jt,"validateCimdClientMetadataUrl");function ve(e){return zo(e,"jwks_uri")}n(ve,"validateCimdClientJwksUrl");function Lo(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(Lo,"mergeAbortSignals");async function ed(e){try{await e.cancel()}catch{}}n(ed,"cancelReader");async function Nt(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 ed(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(Nt,"readBoundedByteStream");var td=2,rd=1024*1024,nd=1e4,od=new Set([301,302,303,307,308]),id=["authorization","proxy-authorization","cookie","cookie2"];function Dr(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Dr,"readRequestUrl");function Me(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(Me,"readRequestMethod");function ad(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(ad,"assertContentLengthWithinLimit");async function sd(e,t,r){return ad(e,t,r),Nt(e.body,{maxBytes:t,createLimitError:n(()=>new h({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}}),"createLimitError")})}n(sd,"readBoundedResponseBody");function cd(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(cd,"responseFromBufferedBody");function dd(e,t){if(!od.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(dd,"resolveRedirectUrl");function Bo(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(Bo,"validateOutboundUrl");function ud(e,t){throw e instanceof h&&vt(e.extensionMembers?.[g])?e:new h({message:"Outbound fetch failed.",extensionMembers:{[g]:t}},{cause:e})}n(ud,"normalizeFetchError");function lt(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&&L(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(lt,"logOutboundFailure");async function ld(e,t,r,o,i,a,s){let c=Me(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";lt(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:i,method:c,host:F(a),error:u,extra:{abortReason:s()}}),ud(u,i)}}n(ld,"fetchWithNormalizedError");function pd(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(pd,"assertRedirectAllowed");function md(e,t){let r=new Headers(e);for(let o of id)r.delete(o);for(let o of t)r.delete(o);return r}n(md,"stripCrossOriginHeaders");function fd(e,t,r,o,i){let a={...e,method:t,redirect:"manual",signal:r};return o&&(a.headers=md(e.headers,i)),a}n(fd,"buildRedirectInit");function hd(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(hd,"buildInitialRequestInit");function gd(e){let t=Me(e.currentInput,e.currentInit);pd({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=Bo(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:fd(e.currentInit,t,e.signal,i,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(gd,"followRedirect");async function Hr(e,t,r){let o=r.problemCode??"invalid_request",i=r.maxRedirects??td,a=r.maxResponseBytes??rd,s=r.timeoutMs??nd,c=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,f=new AbortController,w=Lo(f,t.signal),S=!1,I=setTimeout(()=>{S=!0,f.abort()},s),N=e,Z=hd(e,t,f.signal),X;try{X=Bo(Dr(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(Q){throw lt(p,{event:"outbound_url_blocked",problemCode:o,method:Me(e,t),host:F(Dr(e)),error:Q}),clearTimeout(I),w?.(),Q}let Ke=0;try{for(;;){let Q=await ld(p,c,N,Z,o,X,()=>S?`timeout_after_${s}ms`:void 0),P=dd(Q,X);if(P!==void 0)try{let O=gd({currentInput:N,currentInit:Z,currentUrl:X,redirectUrl:P,redirects:Ke,maxRedirects:i,problemCode:o,validateUrl:r.validateUrl,signal:f.signal,additionalCrossOriginStrippedHeaders:u});N=O.currentInput,Z=O.currentInit,X=O.currentUrl,Ke=O.redirects;continue}catch(O){throw lt(p,{event:"outbound_redirect_blocked",problemCode:o,method:Me(N,Z),host:F(X),error:O,extra:{redirects:Ke,maxRedirects:i,redirectTargetHost:F(P)}}),O}try{return cd(Q,await sd(Q,a,o))}catch(O){throw lt(p,{event:"outbound_response_size_exceeded",problemCode:o,method:Me(N,Z),host:F(X),error:O,extra:{maxResponseBytes:a,status:Q.status}}),O}}}finally{clearTimeout(I),w?.()}}n(Hr,"runSafeOutboundExchange");async function Gt(e,t,r){let o=await Hr(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(i){throw lt(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Me(e,t),host:F(Dr(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(Gt,"runSafeOutboundJsonExchange");function jo(e,t={},r={}){return Hr(e,t,{...r,validateUrl:Bt})}n(jo,"fetchConfiguredOutbound");function No(e,t={},r={}){return Gt(e,t,{...r,validateUrl:Ho})}n(No,"fetchIdentityProviderJson");function Go(e,t={},r={}){return Gt(e,t,{...r,validateUrl:jt})}n(Go,"fetchCimdClientMetadataJson");function $o(e,t={},r={}){return Gt(e,t,{...r,validateUrl:ve})}n($o,"fetchCimdClientJwksJson");G();import{errors as Yo,jwtVerify as Xo,SignJWT as Qo}from"jose";var z="zuplo-mcp-gateway",B=z,j="HS256";import{base64url as yd}from"jose";var _d=new TextEncoder,wd="MCP gateway could not initialize secure key material.",Rd=32,Fo=new Map,Zo=new Map,bd;function Cd(){return bd??vn.instance.authPrivateKey}n(Cd,"readAuthPrivateKey");function Ko(e){return new ce(wd,e===void 0?void 0:{cause:e})}n(Ko,"createGeneratedKeyMaterialError");function Jo(e,t){let r=yd.decode(t);if(r.byteLength!==Rd)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(Jo,"decodeJwkKeyField");function vd(e){let t=Cd();if(!t)throw Ko();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=Jo("d",r.d);Jo("x",r.x);let i=_d.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 Ko(r)}}n(vd,"decodeGeneratedKeyMaterial");function Sd(e){let t=Fo.get(e);return t||(t=vd(e),Fo.set(e,t)),t}n(Sd,"getMasterKeyMaterial");async function W(e){let t=Zo.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Sd(e.keyMaterialPurpose));return Zo.set(e.purpose,r),r}n(W,"readCachedDerivedKey");var Id="SHA-256";var xd="zuplo-mcp-gateway:",Ad=new TextEncoder,Wo=new WeakMap;async function pe(e,t){let r=Wo.get(e);r||(r=new Map,Wo.set(e,r));let o=r.get(t);if(o)return o;let i=await Ud(e,t);return r.set(t,i),i}n(pe,"deriveGatewaySigningKey");async function Ud(e,t){let r=Vo(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=Ad.encode(`${xd}${t}`),a=await crypto.subtle.deriveBits({name:"HKDF",hash:Id,salt:new Uint8Array,info:Vo(i)},o,32*8);return new Uint8Array(a)}n(Ud,"hkdfExpand");function Vo(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(Vo,"copyToArrayBuffer");var ei=15*60,kd=15*60,Pd=Zn.extend({id:uo}),Td=Pd.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ti=dr.extend({id:lo,purpose:d.literal("browser_connect")}),Ed=dr.extend({purpose:d.literal("browser_connect")}),Od=ti.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ri=ei*1e3;async function ni(){return W({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>pe(e,"oauth-state"),"derive")})}n(ni,"getOAuthStateKey");async function oi(){return W({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>pe(e,"browser-connect"),"derive")})}n(oi,"getBrowserConnectKey");async function ii(e){let t=Math.floor(Date.now()/1e3)+ei;return new Qo(e).setProtectedHeader({alg:j,typ:"JWT"}).setIssuer(z).setAudience(B).setIssuedAt().setExpirationTime(t).sign(await ni())}n(ii,"signOAuthState");async function $t(e){try{let{payload:t}=await Xo(e,await ni(),{algorithms:[j],issuer:z,audience:B});return Td.parse(t)}catch(t){throw t instanceof Yo.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($t,"verifyOAuthState");async function ai(e){let t=Math.floor(Date.now()/1e3)+kd,r=Ed.parse(e),o=ti.parse({...r,id:ho()});return new Qo(o).setProtectedHeader({alg:j,typ:"JWT"}).setIssuer(z).setAudience(B).setIssuedAt().setExpirationTime(t).sign(await oi())}n(ai,"signBrowserConnectTicket");async function si(e){try{let{payload:t}=await Xo(e,await oi(),{algorithms:[j],issuer:z,audience:B});return Od.parse(t)}catch(t){throw t instanceof Yo.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(si,"verifyBrowserConnectTicket");async function ci(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(ci,"consumeBrowserConnectTicket");function qd(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(qd,"buildConnectRequiredMessage");async function Md(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 ai({...Ve(e),purpose:"browser_connect"})),r.toString()}n(Md,"buildGatewayBrowserTicketUrl");function Dd(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}n(Dd,"buildGatewayConnectPath");async function zr(e){return Md({...e,path:Dd(e.upstreamServerId),redirect:!0})}n(zr,"buildGatewayConnectUrl");async function Ft(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 zr(t),message:qd(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(Ft,"buildRedirectConnectRequiredResponse");function di(e){return Hd({...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(di,"buildAdminConnectRequiredResponse");function Hd(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(Hd,"buildAdminSetupRequiredResponse");G();var ui=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function zd(e,t){return e&&e.length>0?e.join(t):void 0}n(zd,"joinOAuthScopes");function Ld(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of ui)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(Ld,"sanitizeAuthorizationServerMetadata");function Lr(e){let t=Ld(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(Lr,"sanitizeOAuthDiscoveryState");function li(e){let t=new URL(e);for(let r of ui){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(li,"normalizeDuplicateSingletonAuthorizationRequestParams");function Zt(e){let t=new URL(e);return T(t)&&ye(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(Zt,"normalizeLoopbackOAuthRedirectUri");function pi(e){return zd(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(pi,"readProtectedResourceMetadataScope");function Bd(e){return`Zuplo MCP Gateway - ${e}`}n(Bd,"buildGatewayOAuthClientName");function jd(e,t){return e&&e.length>0?e.join(t):void 0}n(jd,"joinOAuthScopeList");function Br(e){return new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin).toString()}n(Br,"buildOAuthClientMetadataDocumentUrl");function jr(e){let t=Oe(e.upstreamServerId);return{client_name:Bd(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(jr,"buildGatewayOAuthClientMetadata");function mi(e,t,r){let o=qe(t,r),i=jd(o.scopes,o.scopeDelimiter);return{client_id:Br({origin:e,upstreamServerId:t}),...jr({origin:e,upstreamServerId:t,redirectUri:Zt(new URL(o.redirectPath,e)).toString(),scope:i})}}n(mi,"buildOAuthClientMetadataDocument");G();import{base64url as me}from"jose";var Nd="SHA-256",He="AES-GCM",Gd=12,Gr="zuplo-secret",$r=1,fi="generated:auth_private_key:token-encryption",$d=d.object({version:d.literal($r),keyId:d.literal(fi),algorithm:d.literal(He),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();function De(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(De,"copyToArrayBuffer");async function Nr(){return W({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(Nd,De(e));return crypto.subtle.importKey("raw",t,{name:He},!1,["encrypt","decrypt"])},"derive")})}n(Nr,"getEncryptionKey");function hi(e){return De(new TextEncoder().encode(`${Gr}:v${e.version}:${e.keyId}`))}n(hi,"getAssociatedData");function Fd(e){return`${Gr}:v${e.version}:${me.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(Fd,"encodeEnvelope");function Zd(e){let t=`${Gr}:v${$r}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(me.decode(r));return $d.parse(JSON.parse(o))}n(Zd,"decodeEnvelope");async function Kt(e){let t=await Nr(),r=crypto.getRandomValues(new Uint8Array(Gd)),o={version:$r,keyId:fi},i=await crypto.subtle.encrypt({name:He,iv:r,additionalData:hi(o)},t,new TextEncoder().encode(e));return Fd({...o,algorithm:He,iv:me.encode(r),ciphertext:me.encode(new Uint8Array(i))})}n(Kt,"encryptSecret");async function pt(e){let t=Zd(e);if(t){let s=await Nr(),c=await crypto.subtle.decrypt({name:He,iv:De(me.decode(t.iv)),additionalData:hi(t)},s,De(me.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,o]=e.split(".");if(!r||!o)throw new ce("Encrypted payload is malformed");let i=await Nr(),a=await crypto.subtle.decrypt({name:He,iv:De(me.decode(r))},i,De(me.decode(o)));return new TextDecoder().decode(a)}n(pt,"decryptSecret");var Kd=d.union([Xe,Ht]),gi=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:Mt.optional(),authorizationServerMetadata:d.union([Ye,Dt]).optional()}).passthrough(),Jd="Bearer",Wd="__zuplo_refresh_only_upstream_access_token__";function Vd(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Vd,"splitScopes");function Yd(e){return Tt.parse(e)}n(Yd,"parsePkceCodeVerifier");function Xd(e){if(typeof e.expires_in=="number")return R(new Date(Date.now()+e.expires_in*1e3))}n(Xd,"readTokenExpiry");async function yi(e){if(e!==void 0)return Kt(JSON.stringify(e))}n(yi,"encryptJson");async function _i(e,t){if(!e)return;let r=await pt(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(_i,"decryptJson");function Qd(e){if(e===void 0)return;e=Lr(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(Qd,"toOAuthDiscoveryState");function eu(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(eu,"clientInformationAllowsRedirectUri");function tu(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(tu,"clientInformationMatchesCurrentClientMetadataUrl");function ru(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(ru,"isUrlBasedClientInformation");function nu(e,t){return t===void 0?e:{...e,scope:t}}n(nu,"applyOAuthClientMetadataScope");function wi(e,t){return pi({state:e,delimiter:t})}n(wi,"readResourceMetadataScope");function ou(e,t){return e&&e.length>0?e.join(t):void 0}n(ou,"joinOAuthScopeList");function iu(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 Xe.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(iu,"buildManualOAuthClientInformation");function au(e,t){let r=Br({origin:new URL(t).origin,upstreamServerId:e});return Ar(r)?r:void 0}n(au,"buildClientMetadataUrl");function Ri(e){for(let t of e)if(t!==void 0)return t}n(Ri,"firstDefined");function su(e){let t=qe(e.target.upstreamServerId,e.target.authProfileId),r=ou(t.scopes,t.scopeDelimiter),o=jr({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:iu({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let i=au(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(su,"buildInitialOAuthClientSetup");function cu(e,t){if(t===void 0)return Ri([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(cu,"readEncryptedClientInformation");function du(e){return Ri([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}n(du,"readEncryptedDiscoveryState");var Se=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=su({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=cu(t,this.configuredClientInformation),this.encryptedDiscoveryState=du(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return nu(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return ii({id:t.id,...Ve({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,!ru({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await yi(t),await this.syncPendingState(!1)))}async discoveryState(){return this.loadPersistedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=Lr(gi.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.inferredScope=wi(r,this.scopeDelimiter),this.encryptedDiscoveryState=await yi(r),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Ee.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=r.refresh_token?await Kt(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:Ee.parse({...r,refresh_token:await pt(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let a={id:this.connection?.id??mo(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await Kt(r.access_token),encryptedRefreshToken:i,scopes:Vd(r.scope??this.readEffectiveScope()),expiresAt:Xd(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=li(t);this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:Yd(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:fo(),...Ve({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()+ri)),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 _i(this.encryptedClientInformation,Kd)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&(!eu(t,this.redirectUriValue)||!tu({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=Ht.parse({client_id:this.clientMetadataUrl})),this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async loadPersistedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;try{this.cachedDiscoveryState=Qd(await _i(this.encryptedDiscoveryState,gi))}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1)}return this.discoveryStateLoaded=!0,this.inferredScope=wi(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 pt(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await pt(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=Ee.parse({access_token:t??Wd,token_type:Jd,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 uu=3e4,lu=256*1024,pu=2;function mu(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(mu,"hasUsableAccessToken");var fu="does not support dynamic client registration",hu=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],gu=["HTTP 403 Forbidden","Access Denied","permission to access"];function yu(e){return e instanceof Error&&e.message.includes(fu)}n(yu,"isDynamicClientRegistrationUnsupported");function _u(e){return e instanceof Error&&hu.some(t=>e.message.includes(t))}n(_u,"isProtectedResourceMetadataUnavailable");function wu(e){return e instanceof Error&&gu.some(t=>e.message.includes(t))}n(wu,"isUpstreamProviderAccessDenied");function Ru(e){if(e.error instanceof h&&e.error.extensionMembers?.[g]!==void 0)return e.error;if(yu(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(_u(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(wu(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(Ru,"mapUpstreamOAuthSetupError");function bu(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(bu,"readOAuthFetchRequest");function Cu(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(Cu,"responseLooksJson");function vu(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(vu,"responseLooksHtml");function Su(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",[Pe]:e.response.status,[Ue]:r,[Te]:e.request.url.toString(),[ke]:e.body}})}n(Su,"throwUpstreamHtmlError");function bi(e){return async(t,r)=>{let o=bu(t),i=await jo(t,r,{maxRedirects:pu,maxResponseBytes:lu,problemCode:"upstream_token_exchange_failed",timeoutMs:uu}),a=await i.clone().text();if(!i.ok&&vu(i,a)&&Su({upstreamServerId:e,request:o,response:i,body:a}),!Cu(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(bi,"createUpstreamOAuthFetch");async function Ci(e,t){e.applyChallengeScope(t.requestedScope);try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:bi(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),await xr(e,r)}catch(r){let o=Ru({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(Ci,"runUpstreamOAuth");async function Iu(e,t){e.applyChallengeScope(t.requestedScope);let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:bi(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),xr(e,r)}n(Iu,"exchangeUpstreamAuthorizationCode");async function vi(e,t){let r=await Ci(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(vi,"requireUpstreamAuthorizationRedirect");async function Si(e){if(!e.forceRefresh&&mu(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await Ci(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 Pu({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(Si,"authorizeUpstreamOAuthSession");async function xu(e){let t=await $t(e.stateToken),r=await b().consumeUpstreamOAuthState({id:t.id,now:R(new Date)}),o=Au(r);return Uu({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),ku(o),o}n(xu,"consumeStoredCallbackState");function Au(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(Au,"readConsumedCallbackState");function Uu(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(Uu,"assertStoredCallbackStateMatches");function ku(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new h({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}})}n(ku,"assertStoredCallbackStateFresh");async function Pu(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),di(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),Ft(t)}n(Pu,"buildOAuthConnectRequiredResponse");async function Ii(e){let t=await xu({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=kt(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 Se(i),s=await Iu(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(Ii,"finishUpstreamOAuthCallback");function Tu(e){return Zt(new URL(e.callbackPath,k(e.requestUrl,e.requestHeaders))).toString()}n(Tu,"buildGatewayOAuthRedirectUri");async function xi(e){let t=Oe(e.upstreamServerId),r=qe(e.upstreamServerId,e.authProfileId),o=Tu({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(xi,"prepareUpstreamOAuthRequest");async function Ai(e){let t=await xi(e),r=new Se({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return vi(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Ai,"startUpstreamConnect");async function Ui(e){let t=await xi(e),r=new Se({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return Si({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(Ui,"authorizeUpstreamRequest");async function ze(e){let{routeAuth:t}=e;return Ui({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(ze,"resolveUpstreamCredentialForRoute");async function ki(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 Ai(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(ki,"startUpstreamConnectForRequest");async function Pi(e){let r=(await $t(e.callbackRequest.state)).authProfileId;return Er({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}),Ii({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:Oe(e.callbackRequest.upstreamServerId)})}n(Pi,"finishUpstreamCallbackForRequest");function Eu(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(Eu,"buildRouteAuthBaseFromConnection");function Ei(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:Kn(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(Ei,"buildRouteAuthBaseFromPolicyOptions");function Jt(e,t){let o=K().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 Eu({connection:o.connection,operationId:t})}n(Jt,"resolveRouteAuthBase");function Ti(e,t){switch(e){case"user":return Ut(t);case"shared":return Fn()}}n(Ti,"buildOwnerForSubject");function Le(e,t){switch(e.ownerMode){case"shared":return{...e,ownerMode:"shared",owner:Ti(e.ownerMode,t),initiatedBySubjectId:t};case"user":return{...e,ownerMode:"user",owner:Ti(e.ownerMode,t),initiatedBySubjectId:t}}}n(Le,"resolveRouteAuthForSubject");var Ou=Je.InvalidRequest,qu=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function Mu(e,t){return{credentialType:e.type,forceRefresh:t}}n(Mu,"buildCredentialResolvedAttributes");function Du(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(Du,"connectRequiredReasonCode");function Oi(e){x(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:Mu(e.credential,e.forceRefresh===!0)})}n(Oi,"emitCredentialResolvedAnalyticsEvent");function qi(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:Du(e.payload.state),reasonClass:"auth",attributes:t})}n(qi,"emitCredentialMissingAnalyticsEvents");function Hu(e){let t=e.route.raw();return It.parse(t?.operationId)}n(Hu,"readOperationId");async function zu(e,t,r,o){let i=await ze({request:e,routeAuth:t});if(i.kind==="connect_required")return qi({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;Oi({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(zu,"buildCredentialHeaders");var Lu=new Set(["authorization","cookie","cookie2"]);function Bu(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(Bu,"readJsonRequestMethod");function ju(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(ju,"isJsonResponse");function Fr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Fr,"isRecord");function Nu(e){return Array.isArray(e)&&e.length>0}n(Nu,"hasIconList");function Gu(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=Lt(zn(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(Gu,"readFallbackServerIcons");function $u(e){if(!Fr(e.body))return e.body;let t=e.body.result;if(!Fr(t))return e.body;let r=t.serverInfo;return!Fr(r)||Nu(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n($u,"addMissingServerIcons");function Fu(e,t){let r=new Headers(e.headers);for(let o of Lu)r.delete(o);for(let[o,i]of t)r.set(o,i);return new In(e,{headers:r})}n(Fu,"applyUpstreamHeaders");function Zu(e){let t=new Headers(e.headers);for(let r of qu)t.delete(r);return t}n(Zu,"buildProxyHeaders");async function Ku(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(Ku,"readRetryBody");function Mi(e,t){let r=t.authUrl===void 0?void 0:_o({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(Ot({id:yo(e),error:{code:r?.code??Ou,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(Mi,"connectRequiredJsonRpcResponse");async function Ju(e){let{scope:t}=Po(e.upstreamResponse),r=await ze({request:e.request,routeAuth:e.routeAuth,forceRefresh:!0,...t===void 0?{}:{requestedScope:t}});if(r.kind==="connect_required")return qi({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;Oi({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(Ju,"applyRefreshedCredentialHeaders");function Wu(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await Ju({request:e.request,context:e.context,headers:Zu(r),routeAuth:e.routeAuth,upstreamResponse:t});if(o.kind==="connect_required")return Mi(e.requestBody,o.payload);if(o.kind==="response")return o.response;let i=Ln({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return wt.fetch(i.url,i.init)})}n(Wu,"installUpstreamAuthRetryHook");function Vu(e){if(Bu(e.requestBody)!=="initialize")return;let t=Gu({connection:e.connection,context:e.context});t===void 0||t.length===0||e.context.addResponseSendingHook(async r=>{if(!ju(r))return r;let o;try{o=await r.clone().json()}catch{return r}let i=$u({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(Vu,"installInitializeIconHook");async function Zr(e,t,r){let o=Hu(t),i=await Ku(e),a=Ei({connection:r,operationId:o}),s=_e(e.user,e.url,e.headers);Qn(t,s);let c=Le(a,s.subjectId),u=await zu(e,c,r,t);if(!(u instanceof Response)&&u.kind==="connect_required")return Mi(i,u.payload);if(u instanceof Response)return u;let p=Fu(e,u.headers);return Wu({request:p,context:t,requestBody:i,routeAuth:c}),Vu({context:t,requestBody:i,connection:r}),p}n(Zr,"mcpTokenExchangePolicy");var Kr=class extends bt{static{n(this,"McpTokenExchangeInboundPolicy")}constructor(t,r){let o=Jn(t,r);super(o,r)}async handler(t,r){return Rt("policy.inbound.mcp-token-exchange"),Zr(t,r,this.options)}};G();var Di=Symbol("Html");function Yu(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n(Yu,"escapeHtml");function Xu(e){return e===null||typeof e!="object"?!1:e[Di]===!0}n(Xu,"isHtml");function Hi(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Hi).join(""):Xu(e)?e.value:Yu(String(e))}n(Hi,"renderValue");function ie(e){return{[Di]:!0,value:e}}n(ie,"trustedHtml");var V=ie("");function v(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=Hi(t[o]),r+=e[o+1]??"";return ie(r)}n(v,"html");function Be(e){return e.value}n(Be,"renderHtml");function zi(e){return v`<p class="card__description">${e.detail}</p>${e.guidance} ${e.technicalDetails} ${e.action}`}n(zi,"renderBrowserErrorPage");var je=ie('*,: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 Ne(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 kt,Ab as Ds,Ac as oo,Bb as Hs,Bc as io,Cb as zs,Cc as fr,Db as Ls,Dc as ao,Eb as Bs,Ec as so,Fb as js,Fc as hr,G as An,Gb as Ns,Gc as _e,H as l,Hb as Gs,Hc as co,I as Un,Ib as $s,Ic as uo,J as sr,Jb as zn,Jc as lo,K as ee,Kb as Ln,Kc as po,L as kn,Lb as Bn,Lc as mo,M as y,Mb as It,Mc as fo,N as de,Nb as cr,Nc as ho,O as Ct,Ob as xt,Oc as b,P as Pn,Pb as At,Pc as x,Q as Tn,Qb as Je,Qc as le,R as En,Rb as jn,Rc as U,S as d,Sb as Nn,Sc as go,T as G,Tb as Gn,Tc as Fs,Ub as We,Vb as $n,Wb as Ut,Xb as Fn,Yb as dr,Z as On,Zb as Zn,_b as Ve,a as Rt,ac as Kn,bc as Jn,cc as Wn,dc as Vn,ec as K,fc as Yn,gb as ye,gc as Xn,hb as T,hc as R,i as ge,ib as qn,ic as re,j as Sn,jb as g,jc as k,kb as Ue,kc as Pt,l as In,lb as ke,lc as L,mb as Pe,mc as F,nb as Te,nc as Qn,ob as vt,oc as eo,p as xn,pb as Mn,pc as Tt,qb as $,qc as to,r as bt,rb as Dn,rc as ne,sb as te,sc as ur,tb as _,tc as lr,ub as St,uc as ro,vb as M,vc as Et,wb as ue,wc as pr,xb as Hn,xc as mr,yb as qs,yc as no,zb as Ms,zc as D}from"../chunk-XAW2AYUG.js";import{d as ar}from"../chunk-JRXZBVXH.js";import{a as C}from"../chunk-4SACVMDH.js";import{$ as ce,a as n,aa as h,ba as q,ca as vn,da as wt}from"../chunk-ZIKV2LUM.js";G();function Zs(e){let t=At.safeParse(e);return t.success?t.data.id:void 0}n(Zs,"parseJsonRpcRequestId");function yo(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Zs(t)}catch{return}}n(yo,"readJsonRpcRequestIdFromBody");function Ot(e){return jn.parse({jsonrpc:xt,...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(Ot,"jsonRpcErrorResponse");function _o(e){return new Gn([Nn.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(_o,"urlElicitationRequiredError");var qt=d.record(d.string(),d.unknown()),Ks=d.record(d.string(),d.unknown()),Js=d.object({name:d.string().min(1),description:d.string().min(1).optional(),annotations:Ks.optional(),_meta:qt.optional()}).strict(),Ws=d.object({name:d.string().min(1),description:d.string().min(1).optional(),_meta:qt.optional()}).strict(),Vs=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(),Ys=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(),Xs=d.array(d.union([d.string(),Js])),Qs=d.array(d.union([d.string(),Ws])),ec=d.array(d.union([d.string(),Vs])),tc=d.array(d.union([d.string(),Ys])),rc=d.object({tools:Xs.optional(),prompts:Qs.optional(),resources:ec.optional(),resourceTemplates:tc.optional()}).strict(),yr=[{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 nc(e,t){return Hn(rc,e,`MCP capability filter policy "${t}"`)}n(nc,"parseMcpCapabilityFilterOptions");function H(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(H,"isRecord");function oc(e,t){if(!H(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(oc,"readParamString");function _r(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(_r,"readRequestId");function Co(e){return e===void 0?void 0:JSON.stringify(e)}n(Co,"requestIdKey");function ic(e){let t={};for(let r of yr){let o=e[r.option];if(o===void 0)continue;let i=new Map;for(let a of o){let s=dc(a,r.itemProperty);s!==void 0&&i.set(s.key,s)}t[r.option]=i}return t}n(ic,"buildProjectionMaps");function wr(e){return yr.find(t=>t.listMethod===e)}n(wr,"findListRule");function ac(e){return e.requests.some(t=>{if(!H(t))return!1;let r=wr(t.method);return r!==void 0&&e.projectionMaps[r.option]!==void 0})}n(ac,"shouldFilterListResponses");function sc(e){for(let t of yr){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=oc(e.request.params,o.paramProperty);if(i!==void 0&&!r.has(i))return{id:_r(e.request)}}}}n(sc,"findDisallowedDirectAccess");function cc(e){return Response.json(Ot({id:e,error:{code:Je.MethodNotFound,message:"Method not found"}}))}n(cc,"methodNotFoundResponse");function dc(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!H(e))return;let r=e[t];if(typeof r=="string")return{key:r,overlay:e}}n(dc,"buildProjection");function wo(e){let t=e.base[e.property],r=e.overlay[e.property];return H(r)?H(t)?{...t,...r}:r:t}n(wo,"mergeRecordProperty");function uc(e,t){let r={...e,...t.overlay},o=wo({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let i=wo({base:e,overlay:t.overlay,property:"_meta"});return i!==void 0&&(r._meta=i),r}n(uc,"applyProjection");function Ro(e,t,r){if(!H(e))return e;let o=e.result;if(!H(o))return e;let i=o[t.resultProperty];return!Array.isArray(i)||!i.every(a=>H(a)&&typeof a[t.itemProperty]=="string")?e:{...e,result:{...o,[t.resultProperty]:i.flatMap(a=>{if(!H(a))return[];let s=a[t.itemProperty];if(typeof s!="string")return[];let c=r.get(s);return c===void 0?[]:[uc(a,c)]})}}}n(Ro,"filterAndProjectItems");function lc(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!H(r))continue;let o=wr(r.method),i=_r(r),a=Co(i);o!==void 0&&a!==void 0&&t.set(a,o)}return t}n(lc,"buildListRulesByResponseId");function pc(e){if(Array.isArray(e.responseBody)){let o=lc(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(i=>{if(!H(i)||"error"in i)return i;let a=Co(_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:Ro(i,s,c)})}if(!H(e.requestBody)||!H(e.responseBody)||"error"in e.responseBody)return e.responseBody;let t=wr(e.requestBody.method),r=t===void 0?void 0:e.projectionMaps[t.option];return t===void 0||r===void 0?e.responseBody:Ro(e.responseBody,t,r)}n(pc,"filterJsonRpcResponse");async function bo(e){return e.clone().json()}n(bo,"readJson");function mc(e){return e.headers.get("content-type")?.includes("json")??!1}n(mc,"isJsonResponse");var gr=class extends bt{static{n(this,"McpCapabilityFilterInboundPolicy")}#e;constructor(t,r){let o=nc(t,r);super(o,r),this.#e=ic(o)}async handler(t,r){Rt("policy.inbound.mcp-capability-filter");let o;try{o=await bo(t)}catch{return t}let i=Array.isArray(o)?o:[o];for(let a of i){if(!H(a))continue;let s=sc({request:a,projectionMaps:this.#e});if(s!==void 0)return cc(s.id)}return ac({requests:i,projectionMaps:this.#e})&&r.addResponseSendingHook(async a=>{if(!mc(a))return a;let s;try{s=await bo(a)}catch{return a}let c=pc({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 Rr;Rr=globalThis.crypto;async function fc(e){return(await Rr).getRandomValues(new Uint8Array(e))}n(fc,"getRandomValues");async function hc(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await fc(e-o.length);for(let a of i)a<r&&(o+=t[a%t.length])}return o}n(hc,"random");async function gc(e){return await hc(e)}n(gc,"generateVerifier");async function yc(e){let t=await(await Rr).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(yc,"generateChallenge");async function br(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await gc(e),r=await yc(t);return{code_verifier:t,code_challenge:r}}n(br,"pkceChallenge");G();var E=Un().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Tn.custom,message:"URL must be parseable",fatal:!0}),An}).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"}),Mt=Ct({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:ee().optional(),authorization_details_types_supported:y(l()).optional(),dpop_signing_alg_values_supported:y(l()).optional(),dpop_bound_access_tokens_required:ee().optional()}),Ye=Ct({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:ee().optional()}),_c=Ct({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:ee().optional(),request_parameter_supported:ee().optional(),request_uri_parameter_supported:ee().optional(),require_request_uri_registration:ee().optional(),op_policy_uri:E.optional(),op_tos_uri:E.optional(),client_id_metadata_document_supported:ee().optional()}),Dt=de({..._c.shape,...Ye.pick({code_challenge_methods_supported:!0}).shape}),Ee=de({access_token:l(),id_token:l().optional(),token_type:l(),expires_in:En.number().optional(),scope:l().optional(),refresh_token:l().optional()}).strip(),So=de({error:l(),error_description:l().optional(),error_uri:l().optional()}),vo=E.optional().or(Pn("").transform(()=>{})),wc=de({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:vo,scope:l().optional(),contacts:y(l()).optional(),tos_uri:vo,policy_uri:l().optional(),jwks_uri:E.optional(),jwks:kn().optional(),software_id:l().optional(),software_version:l().optional(),software_statement:l().optional()}).strip(),Ht=de({client_id:l(),client_secret:l().optional(),client_id_issued_at:sr().optional(),client_secret_expires_at:sr().optional()}).strip(),Xe=wc.merge(Ht),Kf=de({error:l(),error_description:l().optional()}).strip(),Jf=de({token:l(),token_type_hint:l().optional()}).strip();function Io(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(Io,"resourceUrlFromServerUrl");function xo({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(xo,"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}},Qe=class extends A{static{n(this,"InvalidRequestError")}};Qe.errorCode="invalid_request";var we=class extends A{static{n(this,"InvalidClientError")}};we.errorCode="invalid_client";var Re=class extends A{static{n(this,"InvalidGrantError")}};Re.errorCode="invalid_grant";var be=class extends A{static{n(this,"UnauthorizedClientError")}};be.errorCode="unauthorized_client";var et=class extends A{static{n(this,"UnsupportedGrantTypeError")}};et.errorCode="unsupported_grant_type";var tt=class extends A{static{n(this,"InvalidScopeError")}};tt.errorCode="invalid_scope";var rt=class extends A{static{n(this,"AccessDeniedError")}};rt.errorCode="access_denied";var oe=class extends A{static{n(this,"ServerError")}};oe.errorCode="server_error";var nt=class extends A{static{n(this,"TemporarilyUnavailableError")}};nt.errorCode="temporarily_unavailable";var ot=class extends A{static{n(this,"UnsupportedResponseTypeError")}};ot.errorCode="unsupported_response_type";var it=class extends A{static{n(this,"UnsupportedTokenTypeError")}};it.errorCode="unsupported_token_type";var at=class extends A{static{n(this,"InvalidTokenError")}};at.errorCode="invalid_token";var st=class extends A{static{n(this,"MethodNotAllowedError")}};st.errorCode="method_not_allowed";var ct=class extends A{static{n(this,"TooManyRequestsError")}};ct.errorCode="too_many_requests";var Ce=class extends A{static{n(this,"InvalidClientMetadataError")}};Ce.errorCode="invalid_client_metadata";var dt=class extends A{static{n(this,"InsufficientScopeError")}};dt.errorCode="insufficient_scope";var ut=class extends A{static{n(this,"InvalidTargetError")}};ut.errorCode="invalid_target";var Ao={[Qe.errorCode]:Qe,[we.errorCode]:we,[Re.errorCode]:Re,[be.errorCode]:be,[et.errorCode]:et,[tt.errorCode]:tt,[rt.errorCode]:rt,[oe.errorCode]:oe,[nt.errorCode]:nt,[ot.errorCode]:ot,[it.errorCode]:it,[at.errorCode]:at,[st.errorCode]:st,[ct.errorCode]:ct,[Ce.errorCode]:Ce,[dt.errorCode]:dt,[ut.errorCode]:ut};function Rc(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(Rc,"isClientAuthMethod");var Cr="code",vr="S256";function bc(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Rc(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(bc,"selectClientAuthMethod");function Cc(e,t,r,o){let{client_id:i,client_secret:a}=t;switch(e){case"client_secret_basic":vc(i,a,r);return;case"client_secret_post":Sc(i,a,o);return;case"none":Ic(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(Cc,"applyClientAuthentication");function vc(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(vc,"applyBasicAuth");function Sc(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(Sc,"applyPostAuth");function Ic(e,t){t.set("client_id",e)}n(Ic,"applyPublicAuth");async function ko(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=So.parse(JSON.parse(r)),{error:i,error_description:a,error_uri:s}=o,c=Ao[i]||oe;return new c(a||"",s)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new oe(i)}}n(ko,"parseErrorResponse");async function xr(e,t){try{return await Sr(e,t)}catch(r){if(r instanceof we||r instanceof be)return await e.invalidateCredentials?.("all"),await Sr(e,t);if(r instanceof Re)return await e.invalidateCredentials?.("tokens"),await Sr(e,t);throw r}}n(xr,"auth");async function Sr(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 Eo(u,{fetchFn:a}),!c)try{c=await To(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 Tc(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 w=await xc(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&&!Ar(O))throw new Ce(`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 Cn=await Dc(u,{metadata:p,clientMetadata:e.clientMetadata,scope:S,fetchFn:a});await e.saveClientInformation(Cn),I=Cn}}let N=!e.redirectUrl;if(r!==void 0||N){let P=await Mc(e,u,{metadata:p,resource:w,authorizationCode:r,fetchFn:a});return await e.saveTokens(P),"AUTHORIZED"}let Z=await e.tokens();if(Z?.refresh_token)try{let P=await qc(u,{metadata:p,clientInformation:I,refreshToken:Z.refresh_token,resource:w,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(P),"AUTHORIZED"}catch(P){if(!(!(P instanceof A)||P instanceof oe))throw P}let X=e.state?await e.state():void 0,{authorizationUrl:Ke,codeVerifier:Q}=await Ec(u,{metadata:p,clientInformation:I,state:X,redirectUrl:e.redirectUrl,scope:S,resource:w});return await e.saveCodeVerifier(Q),await e.redirectToAuthorization(Ke),"REDIRECT"}n(Sr,"authInternal");function Ar(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(Ar,"isHttpsUrl");async function xc(e,t,r){let o=Io(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!xo({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(xc,"selectResourceURL");function Po(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let i=Ir(e,"resource_metadata")||void 0,a;if(i)try{a=new URL(i)}catch{}let s=Ir(e,"scope")||void 0,c=Ir(e,"error")||void 0;return{resourceMetadataUrl:a,scope:s,error:c}}n(Po,"extractWWWAuthenticateParams");function Ir(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(Ir,"extractFieldFromWwwAuth");async function To(e,t,r=fetch){let o=await kc(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 Mt.parse(await o.json())}n(To,"discoverOAuthProtectedResourceMetadata");async function Ur(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Ur(e,void 0,r):void 0;throw o}}n(Ur,"fetchWithCorsRetry");function Ac(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(Ac,"buildWellKnownPath");async function Uo(e,t,r=fetch){return await Ur(e,{"MCP-Protocol-Version":t},r)}n(Uo,"tryMetadataDiscovery");function Uc(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(Uc,"shouldAttemptFallback");async function kc(e,t,r,o){let i=new URL(e),a=o?.protocolVersion??cr,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let u=Ac(t,i.pathname);s=new URL(u,o?.metadataServerUrl??i),s.search=i.search}let c=await Uo(s,a,r);if(!o?.metadataUrl&&Uc(c,i.pathname)){let u=new URL(`/.well-known/${t}`,i);c=await Uo(u,a,r)}return c}n(kc,"discoverMetadataWithFallback");function Pc(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(Pc,"buildDiscoveryUrls");async function Eo(e,{fetchFn:t=fetch,protocolVersion:r=cr}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=Pc(e);for(let{url:a,type:s}of i){let c=await Ur(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"?Ye.parse(await c.json()):Dt.parse(await c.json())}}}n(Eo,"discoverAuthorizationServerMetadata");async function Tc(e,t){let r,o;try{r=await To(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 Eo(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(Tc,"discoverOAuthServerInfo");async function Ec(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(Cr))throw new Error(`Incompatible auth server: does not support response type ${Cr}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(vr))throw new Error(`Incompatible auth server: does not support code challenge method ${vr}`)}else c=new URL("/authorize",e);let u=await br(),p=u.code_verifier,f=u.code_challenge;return c.searchParams.set("response_type",Cr),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",f),c.searchParams.set("code_challenge_method",vr),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(Ec,"startAuthorization");function Oc(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(Oc,"prepareAuthorizationCodeRequest");async function Oo(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??[],w=bc(o,f);Cc(w,o,u,r)}let p=await(s??fetch)(c,{method:"POST",headers:u,body:r});if(!p.ok)throw await ko(p);return Ee.parse(await p.json())}n(Oo,"executeTokenRequest");async function qc(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 Oo(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:a,resource:i,fetchFn:s});return{refresh_token:o,...u}}n(qc,"refreshAuthorization");async function Mc(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=Oc(i,p,e.redirectUrl)}let u=await e.clientInformation();return Oo(t,{metadata:r,tokenRequestParams:c,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(Mc,"fetchToken");async function Dc(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 ko(s);return Xe.parse(await s.json())}n(Dc,"registerClient");var kr="zuplo.com",Hc=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),zc=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function qo(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(qo,"s2FaviconHref");function Lc(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(Lc,"strictFaviconHref");var zt=qo(kr);function Pr(e){let t=e.toLowerCase();return t===kr||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?qo(kr):Lc(e)}n(Pr,"resolveIconHref");function Bc(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(Bc,"hostnameFromHost");function jc(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(jc,"isLocalOrAddressHost");function Nc(e){let t=Bc(e).toLowerCase().replace(/\.$/,"");if(jc(t)||zc.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=Hc.has(o)?3:2;return r.slice(-i).join(".")}n(Nc,"inferFaviconDomain");function Tr(e){return{src:Pr(Nc(e)),mimeType:"image/png",sizes:["128x128"]}}n(Tr,"resolveMcpFaviconIcon");function Lt(e){try{return Tr(new URL(e).host)}catch{return}}n(Lt,"resolveMcpFaviconIconFromUrl");function Oe(e){let t=K().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(Oe,"getUpstreamServerConfig");function Gc(e){let t=K().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(Gc,"resolveUpstreamAuthProfileId");function Er(e){Gc(e);let t=K().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(Er,"getUpstreamAuthConfig");function qe(e,t){return Er({upstreamServerId:e,authProfileId:t})}n(qe,"requireUpstreamOAuthConfig");function J(e){return new h({message:e,extensionMembers:{[g]:"invalid_request"}})}n(J,"invalidOutboundUrl");function $c(){let e=ar.__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($c,"isTestOnlyAllowHttpLoopbackIdpEnabled");function Fc(){let e=ar.__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(Fc,"isTestOnlyAllowHttpLoopbackCimdEnabled");var Zc=new Set(["undefined","null","nan"]);function qr(e,t){if(!e.hostname)throw J(`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(Zc.has(e.hostname.toLowerCase()))throw J(`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 Kc=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),Jc=[{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 Mo(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(Mo,"parseIpv4Octets");function Wc([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(Wc,"ipv4RangeMatches");function Do(e){let t=Mo(e);return t!==void 0&&Jc.some(r=>Wc(t,r))}n(Do,"isPrivateIpv4");function Or(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(Or,"parseIpv6Word");function Vc(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}n(Vc,"formatIpv4FromWords");function Yc(e){let t=e.slice(7),r=Mo(t);if(r!==void 0)return r.join(".");let[o,i,a]=t.split(":"),s=Or(o),c=Or(i);return a===void 0&&s!==void 0&&c!==void 0?Vc(s,c):void 0}n(Yc,"parseIpv6MappedIpv4");function Xc(e){return Or(e.split(":").find(Boolean))}n(Xc,"readFirstIpv6Hextet");function Qc(e){let t=ye(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let o=Yc(t);return o===void 0||Do(o)}let r=Xc(t);return r===void 0?!1:(r&65024)===64512||(r&65472)===65152}n(Qc,"isPrivateIpv6");function Mr(e){let t=ye(e);return Kc.has(t)||t.endsWith(".internal")||Do(t)||Qc(t)}n(Mr,"isBlockedOutboundHostname");function Bt(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw J(`Unsupported outbound protocol: ${t.protocol}`);qr(t,e);let r=T(t);if(t.protocol==="http:"&&!r)throw J("Configured outbound HTTP URLs must target loopback hosts.");let o=ye(t.hostname);if(!r&&Mr(o))throw J(`Blocked outbound host: ${o}`);return t}n(Bt,"validateConfiguredOutboundUrl");function Ho(e){let t=new URL(e),r=T(t),o=r&&$c();if(t.protocol!=="https:"&&!o)throw J("Identity provider URLs must use https.");if(t.username||t.password||t.search||t.hash)throw J("Identity provider URLs must not include credentials, query params, or fragments.");qr(t,e);let i=ye(t.hostname);if(!r&&Mr(i))throw J(`Blocked identity provider host: ${i}`);return t}n(Ho,"validateIdentityProviderUrl");function zo(e,t){let r=new URL(e),o=r.protocol==="http:"&&T(r)&&Fc();if(r.protocol!=="https:"&&!o||r.pathname==="/"||r.username||r.password||r.hash)throw J(`CIMD ${t} must be an HTTPS URL with a path and no credentials or fragment.`);if(qr(r,e),!o&&Mr(r.hostname))throw J(`CIMD ${t} points at a blocked host.`);return r}n(zo,"validateCimdUrl");function jt(e){return zo(e,"client_id")}n(jt,"validateCimdClientMetadataUrl");function ve(e){return zo(e,"jwks_uri")}n(ve,"validateCimdClientJwksUrl");function Lo(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(Lo,"mergeAbortSignals");async function ed(e){try{await e.cancel()}catch{}}n(ed,"cancelReader");async function Nt(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 ed(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(Nt,"readBoundedByteStream");var td=2,rd=1024*1024,nd=1e4,od=new Set([301,302,303,307,308]),id=["authorization","proxy-authorization","cookie","cookie2"];function Dr(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Dr,"readRequestUrl");function Me(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(Me,"readRequestMethod");function ad(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(ad,"assertContentLengthWithinLimit");async function sd(e,t,r){return ad(e,t,r),Nt(e.body,{maxBytes:t,createLimitError:n(()=>new h({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}}),"createLimitError")})}n(sd,"readBoundedResponseBody");function cd(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(cd,"responseFromBufferedBody");function dd(e,t){if(!od.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(dd,"resolveRedirectUrl");function Bo(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(Bo,"validateOutboundUrl");function ud(e,t){throw e instanceof h&&vt(e.extensionMembers?.[g])?e:new h({message:"Outbound fetch failed.",extensionMembers:{[g]:t}},{cause:e})}n(ud,"normalizeFetchError");function lt(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&&L(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(lt,"logOutboundFailure");async function ld(e,t,r,o,i,a,s){let c=Me(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";lt(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:i,method:c,host:F(a),error:u,extra:{abortReason:s()}}),ud(u,i)}}n(ld,"fetchWithNormalizedError");function pd(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(pd,"assertRedirectAllowed");function md(e,t){let r=new Headers(e);for(let o of id)r.delete(o);for(let o of t)r.delete(o);return r}n(md,"stripCrossOriginHeaders");function fd(e,t,r,o,i){let a={...e,method:t,redirect:"manual",signal:r};return o&&(a.headers=md(e.headers,i)),a}n(fd,"buildRedirectInit");function hd(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(hd,"buildInitialRequestInit");function gd(e){let t=Me(e.currentInput,e.currentInit);pd({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=Bo(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:fd(e.currentInit,t,e.signal,i,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(gd,"followRedirect");async function Hr(e,t,r){let o=r.problemCode??"invalid_request",i=r.maxRedirects??td,a=r.maxResponseBytes??rd,s=r.timeoutMs??nd,c=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,f=new AbortController,w=Lo(f,t.signal),S=!1,I=setTimeout(()=>{S=!0,f.abort()},s),N=e,Z=hd(e,t,f.signal),X;try{X=Bo(Dr(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(Q){throw lt(p,{event:"outbound_url_blocked",problemCode:o,method:Me(e,t),host:F(Dr(e)),error:Q}),clearTimeout(I),w?.(),Q}let Ke=0;try{for(;;){let Q=await ld(p,c,N,Z,o,X,()=>S?`timeout_after_${s}ms`:void 0),P=dd(Q,X);if(P!==void 0)try{let O=gd({currentInput:N,currentInit:Z,currentUrl:X,redirectUrl:P,redirects:Ke,maxRedirects:i,problemCode:o,validateUrl:r.validateUrl,signal:f.signal,additionalCrossOriginStrippedHeaders:u});N=O.currentInput,Z=O.currentInit,X=O.currentUrl,Ke=O.redirects;continue}catch(O){throw lt(p,{event:"outbound_redirect_blocked",problemCode:o,method:Me(N,Z),host:F(X),error:O,extra:{redirects:Ke,maxRedirects:i,redirectTargetHost:F(P)}}),O}try{return cd(Q,await sd(Q,a,o))}catch(O){throw lt(p,{event:"outbound_response_size_exceeded",problemCode:o,method:Me(N,Z),host:F(X),error:O,extra:{maxResponseBytes:a,status:Q.status}}),O}}}finally{clearTimeout(I),w?.()}}n(Hr,"runSafeOutboundExchange");async function Gt(e,t,r){let o=await Hr(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(i){throw lt(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Me(e,t),host:F(Dr(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(Gt,"runSafeOutboundJsonExchange");function jo(e,t={},r={}){return Hr(e,t,{...r,validateUrl:Bt})}n(jo,"fetchConfiguredOutbound");function No(e,t={},r={}){return Gt(e,t,{...r,validateUrl:Ho})}n(No,"fetchIdentityProviderJson");function Go(e,t={},r={}){return Gt(e,t,{...r,validateUrl:jt})}n(Go,"fetchCimdClientMetadataJson");function $o(e,t={},r={}){return Gt(e,t,{...r,validateUrl:ve})}n($o,"fetchCimdClientJwksJson");G();import{errors as Yo,jwtVerify as Xo,SignJWT as Qo}from"jose";var z="zuplo-mcp-gateway",B=z,j="HS256";import{base64url as yd}from"jose";var _d=new TextEncoder,wd="MCP gateway could not initialize secure key material.",Rd=32,Fo=new Map,Zo=new Map,bd;function Cd(){return bd??vn.instance.authPrivateKey}n(Cd,"readAuthPrivateKey");function Ko(e){return new ce(wd,e===void 0?void 0:{cause:e})}n(Ko,"createGeneratedKeyMaterialError");function Jo(e,t){let r=yd.decode(t);if(r.byteLength!==Rd)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(Jo,"decodeJwkKeyField");function vd(e){let t=Cd();if(!t)throw Ko();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=Jo("d",r.d);Jo("x",r.x);let i=_d.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 Ko(r)}}n(vd,"decodeGeneratedKeyMaterial");function Sd(e){let t=Fo.get(e);return t||(t=vd(e),Fo.set(e,t)),t}n(Sd,"getMasterKeyMaterial");async function W(e){let t=Zo.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Sd(e.keyMaterialPurpose));return Zo.set(e.purpose,r),r}n(W,"readCachedDerivedKey");var Id="SHA-256";var xd="zuplo-mcp-gateway:",Ad=new TextEncoder,Wo=new WeakMap;async function pe(e,t){let r=Wo.get(e);r||(r=new Map,Wo.set(e,r));let o=r.get(t);if(o)return o;let i=await Ud(e,t);return r.set(t,i),i}n(pe,"deriveGatewaySigningKey");async function Ud(e,t){let r=Vo(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=Ad.encode(`${xd}${t}`),a=await crypto.subtle.deriveBits({name:"HKDF",hash:Id,salt:new Uint8Array,info:Vo(i)},o,32*8);return new Uint8Array(a)}n(Ud,"hkdfExpand");function Vo(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(Vo,"copyToArrayBuffer");var ei=15*60,kd=15*60,Pd=Zn.extend({id:uo}),Td=Pd.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ti=dr.extend({id:lo,purpose:d.literal("browser_connect")}),Ed=dr.extend({purpose:d.literal("browser_connect")}),Od=ti.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ri=ei*1e3;async function ni(){return W({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>pe(e,"oauth-state"),"derive")})}n(ni,"getOAuthStateKey");async function oi(){return W({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>pe(e,"browser-connect"),"derive")})}n(oi,"getBrowserConnectKey");async function ii(e){let t=Math.floor(Date.now()/1e3)+ei;return new Qo(e).setProtectedHeader({alg:j,typ:"JWT"}).setIssuer(z).setAudience(B).setIssuedAt().setExpirationTime(t).sign(await ni())}n(ii,"signOAuthState");async function $t(e){try{let{payload:t}=await Xo(e,await ni(),{algorithms:[j],issuer:z,audience:B});return Td.parse(t)}catch(t){throw t instanceof Yo.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($t,"verifyOAuthState");async function ai(e){let t=Math.floor(Date.now()/1e3)+kd,r=Ed.parse(e),o=ti.parse({...r,id:ho()});return new Qo(o).setProtectedHeader({alg:j,typ:"JWT"}).setIssuer(z).setAudience(B).setIssuedAt().setExpirationTime(t).sign(await oi())}n(ai,"signBrowserConnectTicket");async function si(e){try{let{payload:t}=await Xo(e,await oi(),{algorithms:[j],issuer:z,audience:B});return Od.parse(t)}catch(t){throw t instanceof Yo.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(si,"verifyBrowserConnectTicket");async function ci(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(ci,"consumeBrowserConnectTicket");function qd(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(qd,"buildConnectRequiredMessage");async function Md(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 ai({...Ve(e),purpose:"browser_connect"})),r.toString()}n(Md,"buildGatewayBrowserTicketUrl");function Dd(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}n(Dd,"buildGatewayConnectPath");async function zr(e){return Md({...e,path:Dd(e.upstreamServerId),redirect:!0})}n(zr,"buildGatewayConnectUrl");async function Ft(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 zr(t),message:qd(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(Ft,"buildRedirectConnectRequiredResponse");function di(e){return Hd({...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(di,"buildAdminConnectRequiredResponse");function Hd(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(Hd,"buildAdminSetupRequiredResponse");G();var ui=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function zd(e,t){return e&&e.length>0?e.join(t):void 0}n(zd,"joinOAuthScopes");function Ld(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of ui)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(Ld,"sanitizeAuthorizationServerMetadata");function Lr(e){let t=Ld(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(Lr,"sanitizeOAuthDiscoveryState");function li(e){let t=new URL(e);for(let r of ui){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(li,"normalizeDuplicateSingletonAuthorizationRequestParams");function Zt(e){let t=new URL(e);return T(t)&&ye(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(Zt,"normalizeLoopbackOAuthRedirectUri");function pi(e){return zd(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(pi,"readProtectedResourceMetadataScope");function Bd(e){return`Zuplo MCP Gateway - ${e}`}n(Bd,"buildGatewayOAuthClientName");function jd(e,t){return e&&e.length>0?e.join(t):void 0}n(jd,"joinOAuthScopeList");function Br(e){return new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin).toString()}n(Br,"buildOAuthClientMetadataDocumentUrl");function jr(e){let t=Oe(e.upstreamServerId);return{client_name:Bd(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(jr,"buildGatewayOAuthClientMetadata");function mi(e,t,r){let o=qe(t,r),i=jd(o.scopes,o.scopeDelimiter);return{client_id:Br({origin:e,upstreamServerId:t}),...jr({origin:e,upstreamServerId:t,redirectUri:Zt(new URL(o.redirectPath,e)).toString(),scope:i})}}n(mi,"buildOAuthClientMetadataDocument");G();import{base64url as me}from"jose";var Nd="SHA-256",He="AES-GCM",Gd=12,Gr="zuplo-secret",$r=1,fi="generated:auth_private_key:token-encryption",$d=d.object({version:d.literal($r),keyId:d.literal(fi),algorithm:d.literal(He),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();function De(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(De,"copyToArrayBuffer");async function Nr(){return W({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(Nd,De(e));return crypto.subtle.importKey("raw",t,{name:He},!1,["encrypt","decrypt"])},"derive")})}n(Nr,"getEncryptionKey");function hi(e){return De(new TextEncoder().encode(`${Gr}:v${e.version}:${e.keyId}`))}n(hi,"getAssociatedData");function Fd(e){return`${Gr}:v${e.version}:${me.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(Fd,"encodeEnvelope");function Zd(e){let t=`${Gr}:v${$r}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(me.decode(r));return $d.parse(JSON.parse(o))}n(Zd,"decodeEnvelope");async function Kt(e){let t=await Nr(),r=crypto.getRandomValues(new Uint8Array(Gd)),o={version:$r,keyId:fi},i=await crypto.subtle.encrypt({name:He,iv:r,additionalData:hi(o)},t,new TextEncoder().encode(e));return Fd({...o,algorithm:He,iv:me.encode(r),ciphertext:me.encode(new Uint8Array(i))})}n(Kt,"encryptSecret");async function pt(e){let t=Zd(e);if(t){let s=await Nr(),c=await crypto.subtle.decrypt({name:He,iv:De(me.decode(t.iv)),additionalData:hi(t)},s,De(me.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,o]=e.split(".");if(!r||!o)throw new ce("Encrypted payload is malformed");let i=await Nr(),a=await crypto.subtle.decrypt({name:He,iv:De(me.decode(r))},i,De(me.decode(o)));return new TextDecoder().decode(a)}n(pt,"decryptSecret");var Kd=d.union([Xe,Ht]),gi=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:Mt.optional(),authorizationServerMetadata:d.union([Ye,Dt]).optional()}).passthrough(),Jd="Bearer",Wd="__zuplo_refresh_only_upstream_access_token__";function Vd(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Vd,"splitScopes");function Yd(e){return Tt.parse(e)}n(Yd,"parsePkceCodeVerifier");function Xd(e){if(typeof e.expires_in=="number")return R(new Date(Date.now()+e.expires_in*1e3))}n(Xd,"readTokenExpiry");async function yi(e){if(e!==void 0)return Kt(JSON.stringify(e))}n(yi,"encryptJson");async function _i(e,t){if(!e)return;let r=await pt(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(_i,"decryptJson");function Qd(e){if(e===void 0)return;e=Lr(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(Qd,"toOAuthDiscoveryState");function eu(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(eu,"clientInformationAllowsRedirectUri");function tu(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(tu,"clientInformationMatchesCurrentClientMetadataUrl");function ru(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(ru,"isUrlBasedClientInformation");function nu(e,t){return t===void 0?e:{...e,scope:t}}n(nu,"applyOAuthClientMetadataScope");function wi(e,t){return pi({state:e,delimiter:t})}n(wi,"readResourceMetadataScope");function ou(e,t){return e&&e.length>0?e.join(t):void 0}n(ou,"joinOAuthScopeList");function iu(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 Xe.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(iu,"buildManualOAuthClientInformation");function au(e,t){let r=Br({origin:new URL(t).origin,upstreamServerId:e});return Ar(r)?r:void 0}n(au,"buildClientMetadataUrl");function Ri(e){for(let t of e)if(t!==void 0)return t}n(Ri,"firstDefined");function su(e){let t=qe(e.target.upstreamServerId,e.target.authProfileId),r=ou(t.scopes,t.scopeDelimiter),o=jr({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:iu({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let i=au(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(su,"buildInitialOAuthClientSetup");function cu(e,t){if(t===void 0)return Ri([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(cu,"readEncryptedClientInformation");function du(e){return Ri([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}n(du,"readEncryptedDiscoveryState");var Se=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=su({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=cu(t,this.configuredClientInformation),this.encryptedDiscoveryState=du(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return nu(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return ii({id:t.id,...Ve({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,!ru({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await yi(t),await this.syncPendingState(!1)))}async discoveryState(){return this.loadPersistedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=Lr(gi.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,this.inferredScope=wi(r,this.scopeDelimiter),this.encryptedDiscoveryState=await yi(r),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Ee.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=r.refresh_token?await Kt(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:Ee.parse({...r,refresh_token:await pt(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let a={id:this.connection?.id??mo(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await Kt(r.access_token),encryptedRefreshToken:i,scopes:Vd(r.scope??this.readEffectiveScope()),expiresAt:Xd(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=li(t);this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:Yd(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:fo(),...Ve({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()+ri)),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 _i(this.encryptedClientInformation,Kd)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&(!eu(t,this.redirectUriValue)||!tu({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=Ht.parse({client_id:this.clientMetadataUrl})),this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async loadPersistedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;try{this.cachedDiscoveryState=Qd(await _i(this.encryptedDiscoveryState,gi))}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1)}return this.discoveryStateLoaded=!0,this.inferredScope=wi(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 pt(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await pt(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=Ee.parse({access_token:t??Wd,token_type:Jd,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 uu=3e4,lu=256*1024,pu=2;function mu(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(mu,"hasUsableAccessToken");var fu="does not support dynamic client registration",hu=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],gu=["HTTP 403 Forbidden","Access Denied","permission to access"];function yu(e){return e instanceof Error&&e.message.includes(fu)}n(yu,"isDynamicClientRegistrationUnsupported");function _u(e){return e instanceof Error&&hu.some(t=>e.message.includes(t))}n(_u,"isProtectedResourceMetadataUnavailable");function wu(e){return e instanceof Error&&gu.some(t=>e.message.includes(t))}n(wu,"isUpstreamProviderAccessDenied");function Ru(e){if(e.error instanceof h&&e.error.extensionMembers?.[g]!==void 0)return e.error;if(yu(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(_u(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(wu(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(Ru,"mapUpstreamOAuthSetupError");function bu(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(bu,"readOAuthFetchRequest");function Cu(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(Cu,"responseLooksJson");function vu(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(vu,"responseLooksHtml");function Su(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",[Pe]:e.response.status,[Ue]:r,[Te]:e.request.url.toString(),[ke]:e.body}})}n(Su,"throwUpstreamHtmlError");function bi(e){return async(t,r)=>{let o=bu(t),i=await jo(t,r,{maxRedirects:pu,maxResponseBytes:lu,problemCode:"upstream_token_exchange_failed",timeoutMs:uu}),a=await i.clone().text();if(!i.ok&&vu(i,a)&&Su({upstreamServerId:e,request:o,response:i,body:a}),!Cu(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(bi,"createUpstreamOAuthFetch");async function Ci(e,t){e.applyChallengeScope(t.requestedScope);try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:bi(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),await xr(e,r)}catch(r){let o=Ru({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(Ci,"runUpstreamOAuth");async function Iu(e,t){e.applyChallengeScope(t.requestedScope);let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:bi(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),xr(e,r)}n(Iu,"exchangeUpstreamAuthorizationCode");async function vi(e,t){let r=await Ci(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(vi,"requireUpstreamAuthorizationRedirect");async function Si(e){if(!e.forceRefresh&&mu(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await Ci(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 Pu({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(Si,"authorizeUpstreamOAuthSession");async function xu(e){let t=await $t(e.stateToken),r=await b().consumeUpstreamOAuthState({id:t.id,now:R(new Date)}),o=Au(r);return Uu({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),ku(o),o}n(xu,"consumeStoredCallbackState");function Au(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(Au,"readConsumedCallbackState");function Uu(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(Uu,"assertStoredCallbackStateMatches");function ku(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new h({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}})}n(ku,"assertStoredCallbackStateFresh");async function Pu(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),di(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),Ft(t)}n(Pu,"buildOAuthConnectRequiredResponse");async function Ii(e){let t=await xu({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=kt(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 Se(i),s=await Iu(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(Ii,"finishUpstreamOAuthCallback");function Tu(e){return Zt(new URL(e.callbackPath,k(e.requestUrl,e.requestHeaders))).toString()}n(Tu,"buildGatewayOAuthRedirectUri");async function xi(e){let t=Oe(e.upstreamServerId),r=qe(e.upstreamServerId,e.authProfileId),o=Tu({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(xi,"prepareUpstreamOAuthRequest");async function Ai(e){let t=await xi(e),r=new Se({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return vi(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Ai,"startUpstreamConnect");async function Ui(e){let t=await xi(e),r=new Se({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return Si({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(Ui,"authorizeUpstreamRequest");async function ze(e){let{routeAuth:t}=e;return Ui({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(ze,"resolveUpstreamCredentialForRoute");async function ki(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 Ai(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(ki,"startUpstreamConnectForRequest");async function Pi(e){let r=(await $t(e.callbackRequest.state)).authProfileId;return Er({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}),Ii({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:Oe(e.callbackRequest.upstreamServerId)})}n(Pi,"finishUpstreamCallbackForRequest");function Eu(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(Eu,"buildRouteAuthBaseFromConnection");function Ei(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:Kn(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(Ei,"buildRouteAuthBaseFromPolicyOptions");function Jt(e,t){let o=K().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 Eu({connection:o.connection,operationId:t})}n(Jt,"resolveRouteAuthBase");function Ti(e,t){switch(e){case"user":return Ut(t);case"shared":return Fn()}}n(Ti,"buildOwnerForSubject");function Le(e,t){switch(e.ownerMode){case"shared":return{...e,ownerMode:"shared",owner:Ti(e.ownerMode,t),initiatedBySubjectId:t};case"user":return{...e,ownerMode:"user",owner:Ti(e.ownerMode,t),initiatedBySubjectId:t}}}n(Le,"resolveRouteAuthForSubject");var Ou=Je.InvalidRequest,qu=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function Mu(e,t){return{credentialType:e.type,forceRefresh:t}}n(Mu,"buildCredentialResolvedAttributes");function Du(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(Du,"connectRequiredReasonCode");function Oi(e){x(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:Mu(e.credential,e.forceRefresh===!0)})}n(Oi,"emitCredentialResolvedAnalyticsEvent");function qi(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:Du(e.payload.state),reasonClass:"auth",attributes:t})}n(qi,"emitCredentialMissingAnalyticsEvents");function Hu(e){let t=e.route.raw();return It.parse(t?.operationId)}n(Hu,"readOperationId");async function zu(e,t,r,o){let i=await ze({request:e,routeAuth:t});if(i.kind==="connect_required")return qi({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;Oi({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(zu,"buildCredentialHeaders");var Lu=new Set(["authorization","cookie","cookie2"]);function Bu(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(Bu,"readJsonRequestMethod");function ju(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(ju,"isJsonResponse");function Fr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(Fr,"isRecord");function Nu(e){return Array.isArray(e)&&e.length>0}n(Nu,"hasIconList");function Gu(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=Lt(zn(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(Gu,"readFallbackServerIcons");function $u(e){if(!Fr(e.body))return e.body;let t=e.body.result;if(!Fr(t))return e.body;let r=t.serverInfo;return!Fr(r)||Nu(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n($u,"addMissingServerIcons");function Fu(e,t){let r=new Headers(e.headers);for(let o of Lu)r.delete(o);for(let[o,i]of t)r.set(o,i);return new In(e,{headers:r})}n(Fu,"applyUpstreamHeaders");function Zu(e){let t=new Headers(e.headers);for(let r of qu)t.delete(r);return t}n(Zu,"buildProxyHeaders");async function Ku(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(Ku,"readRetryBody");function Mi(e,t){let r=t.authUrl===void 0?void 0:_o({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(Ot({id:yo(e),error:{code:r?.code??Ou,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(Mi,"connectRequiredJsonRpcResponse");async function Ju(e){let{scope:t}=Po(e.upstreamResponse),r=await ze({request:e.request,routeAuth:e.routeAuth,forceRefresh:!0,...t===void 0?{}:{requestedScope:t}});if(r.kind==="connect_required")return qi({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;Oi({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(Ju,"applyRefreshedCredentialHeaders");function Wu(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await Ju({request:e.request,context:e.context,headers:Zu(r),routeAuth:e.routeAuth,upstreamResponse:t});if(o.kind==="connect_required")return Mi(e.requestBody,o.payload);if(o.kind==="response")return o.response;let i=Ln({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return wt.fetch(i.url,i.init)})}n(Wu,"installUpstreamAuthRetryHook");function Vu(e){if(Bu(e.requestBody)!=="initialize")return;let t=Gu({connection:e.connection,context:e.context});t===void 0||t.length===0||e.context.addResponseSendingHook(async r=>{if(!ju(r))return r;let o;try{o=await r.clone().json()}catch{return r}let i=$u({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(Vu,"installInitializeIconHook");async function Zr(e,t,r){let o=Hu(t),i=await Ku(e),a=Ei({connection:r,operationId:o}),s=_e(e.user,e.url,e.headers);Qn(t,s);let c=Le(a,s.subjectId),u=await zu(e,c,r,t);if(!(u instanceof Response)&&u.kind==="connect_required")return Mi(i,u.payload);if(u instanceof Response)return u;let p=Fu(e,u.headers);return Wu({request:p,context:t,requestBody:i,routeAuth:c}),Vu({context:t,requestBody:i,connection:r}),p}n(Zr,"mcpTokenExchangePolicy");var Kr=class extends bt{static{n(this,"McpTokenExchangeInboundPolicy")}constructor(t,r){let o=Jn(t,r);super(o,r)}async handler(t,r){return Rt("policy.inbound.mcp-token-exchange"),Zr(t,r,this.options)}};G();var Di=Symbol("Html");function Yu(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n(Yu,"escapeHtml");function Xu(e){return e===null||typeof e!="object"?!1:e[Di]===!0}n(Xu,"isHtml");function Hi(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Hi).join(""):Xu(e)?e.value:Yu(String(e))}n(Hi,"renderValue");function ie(e){return{[Di]:!0,value:e}}n(ie,"trustedHtml");var V=ie("");function v(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=Hi(t[o]),r+=e[o+1]??"";return ie(r)}n(v,"html");function Be(e){return e.value}n(Be,"renderHtml");function zi(e){return v`<p class="card__description">${e.detail}</p>${e.guidance} ${e.technicalDetails} ${e.action}`}n(zi,"renderBrowserErrorPage");var je=ie('*,: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 Ne(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(Ne,"renderShell");var Qu="text/html; charset=utf-8";function Ge(e){try{return new URL(e).host}catch{return""}}n(Ge,"safeHostFromUrl");function Y(e){let t=tl(e.kind??"authorization_failed"),r=el(e);return new Response(Be(Ne({title:e.title??t.title,iconHref:"",styles:je,headerIcon:V,heading:e.title??t.title,subhead:"",body:zi({detail:e.detail,guidance:v`<p class="card__description">${t.guidance}</p>`,technicalDetails:al({diagnostic:r,upstreamHtml:e.upstreamHtml}),action:ol(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":Qu,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(Y,"browserErrorPageResponse");function el(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??rl(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??nl(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}n(el,"buildBrowserErrorDiagnostic");function tl(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(tl,"readBrowserErrorPagePresentation");function rl(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(rl,"readBrowserErrorStage");function nl(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(nl,"readBrowserErrorSuggestedFix");function ol(e){return e===void 0?V:v`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(ol,"renderAction");function il(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(il,"renderTechnicalPre");function Wt(e){return e.value===void 0||e.value===""?V:v`<p class="banner__message"><strong>${e.label}:</strong> <code>${e.value}</code></p>`}n(Wt,"renderOptionalTechnicalRow");function al(e){return v`<section class="banner banner--warning" aria-label="Developer details">
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
3
  "type": "module",
4
- "version": "6.70.56",
4
+ "version": "6.70.57",
5
5
  "repository": "https://github.com/zuplo/zuplo",
6
6
  "author": "Zuplo, Inc.",
7
7
  "exports": {