@zuplo/cli 6.71.8 → 6.71.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,5 +22,5 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$ as tt,$a as tr,$d as cs,A as I,Aa as Ht,Ad as Ur,B as J,Ba as Pt,Bd as $r,C as K,Ca as St,Cd as kr,D as M,Da as Tt,Dd as Fr,E as N,Ea as Ut,Ed as Lr,F as O,Fa as $t,Fd as Rr,Ga as kt,Gb as hr,Gd as qr,Ha as Ft,Hb as mr,Hd as vr,Ia as Lt,Ib as gr,Id as zr,Ja as Rt,Jb as dr,Jd as Gr,Ka as qt,Kb as ur,Kd as Ir,La as vt,Lb as fr,Ld as Qr,Ma as zt,Mb as xr,Md as Vr,Na as Gt,Nb as yr,Nd as Wr,Oa as It,Ob as wr,Od as Xr,Pa as Jt,Pb as Ar,Pd as Yr,Qa as Kt,Qd as Zr,Ra as Mt,Rd as _r,Sa as Nt,Sd as ts,Ta as Ot,Td as rs,U as Q,Ua as Qt,Ud as ss,V,Va as Vt,Vd as es,W,Wa as Wt,Wd as os,X,Xa as Xt,Xd as as,Y,Ya as Yt,Yd as ns,Z,Za as Zt,Zd as is,_,_a as _t,_d as ps,a as n,aa as rt,ab as rr,ae as hs,b as x,ba as st,bb as sr,be as ms,c as y,ca as et,cb as er,ce as gs,d as w,da as ot,db as or,de as ds,e as A,ea as at,eb as ar,ee as us,f as b,fa as nt,fb as nr,fe as fs,g as l,ga as it,gb as ir,ge as xs,h as j,ha as pt,hb as pr,he as ys,i as B,ia as ct,ib as cr,ie as ws,ja as ht,je as As,k as C,ka as mt,ke as bs,l as D,la as gt,m as E,ma as dt,n as H,na as ut,o as P,oa as ft,pa as xt,pd as br,q as T,qa as yt,qd as lr,r as U,ra as wt,rd as jr,s as $,sa as At,sd as Br,t as k,ta as bt,td as Cr,u as F,ua as lt,ud as Dr,v as L,va as jt,vd as Er,w as R,wa as Bt,wd as Hr,x as q,xa as Ct,xd as Pr,y as v,ya as Dt,yd as Sr,z as G,za as Et,zd as Tr}from"./chunk-LM6CZZF3.js";import{a as S,d as z,e as Jr,f as Kr,g as Mr,h as Nr,i as Or}from"./chunk-DQ4ANJLR.js";import"./chunk-2Y72LML3.js";import{_ as u,a as t,aa as a,ba as f}from"./chunk-L3MZGNQA.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,As 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,bs as BackgroundLoader,Jt as BasicAuthInboundPolicy,Lr 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,rr as DataLossPreventionInboundPolicy,sr as DataLossPreventionOutboundPolicy,st as DynaTraceLoggingPlugin,ht as DynatraceMetricsPlugin,er as FirebaseJwtInboundPolicy,or as FormDataToJsonInboundPolicy,ar as GalileoTracingInboundPolicy,nr as GeoFilterInboundPolicy,k as GoogleCloudLoggingPlugin,ir as GraphqlAnalyticsOutboundPolicy,G as Handler,pr as HttpDeprecationOutboundPolicy,B as HttpProblems,b as HttpStatusCode,Bt as HydrolixRequestLoggerPlugin,U as InboundPolicy,cr as JWTScopeValidationInboundPolicy,ft as JwtServicePlugin,et as LokiLoggingPlugin,L as LookupResult,Er as MTLSAuthInboundPolicy,br as McpAuth0OAuthInboundPolicy,hr as McpClerkOAuthInboundPolicy,mr as McpCognitoOAuthInboundPolicy,gr as McpEntraOAuthInboundPolicy,xt as McpGatewayOAuthProtectedResourcePlugin,dr as McpGoogleOAuthInboundPolicy,ur as McpKeycloakOAuthInboundPolicy,fr as McpLogtoOAuthInboundPolicy,lr as McpOAuthInboundPolicy,xr as McpOktaOAuthInboundPolicy,yr as McpOneLoginOAuthInboundPolicy,wr as McpPingOAuthInboundPolicy,Ar as McpWorkosOAuthInboundPolicy,w as MemoryZoneReadThroughCache,jr as MockApiInboundPolicy,Cr as MoesifInboundPolicy,Dr as MonetizationInboundPolicy,ot as NewRelicLoggingPlugin,mt as NewRelicMetricsPlugin,yt as OAuthProtectedResourcePlugin,gt as OTelMetricsPlugin,Hr as OktaFGAAuthZInboundPolicy,Pr as OktaJwtInboundPolicy,Sr as OpenFGAAuthZInboundPolicy,vt as OpenIdJwtInboundPolicy,Tr as OpenMeterInboundPolicy,$ as OutboundPolicy,j as ProblemResponseFormatter,Ur as PromptInjectionDetectionOutboundPolicy,$r as PropelAuthJwtInboundPolicy,kr as QueryParamToHeaderInboundPolicy,Fr as QuotaInboundPolicy,Lr as RateLimitInboundPolicy,Rr as ReadmeMetricsInboundPolicy,qr as RemoveHeadersInboundPolicy,vr as RemoveHeadersOutboundPolicy,zr as RemoveQueryParamsInboundPolicy,Gr as ReplaceStringOutboundPolicy,Ct as RequestLoggerPlugin,Ir as RequestSizeLimitInboundPolicy,Qr as RequestValidationInboundPolicy,Wr as RequireOriginInboundPolicy,R as ResponseSendingEvent,q as ResponseSentEvent,a as RuntimeError,u as SYSTEM_LOGGER,Vr as SchemaBasedRequestValidation,Xr as SecretMaskingOutboundPolicy,T as SemanticAttributes,Yr as SemanticCacheInboundPolicy,ws as ServiceProviderImpl,Zr as SetBodyInboundPolicy,_r as SetHeadersInboundPolicy,ts as SetHeadersOutboundPolicy,rs as SetQueryParamsInboundPolicy,ss as SetStatusOutboundPolicy,es as SetUpstreamApiKeyInboundPolicy,os as SleepInboundPolicy,at as SplunkLoggingPlugin,A as StreamingZoneCache,as as StripeWebhookVerificationInboundPolicy,nt as SumoLogicLoggingPlugin,ns as SupabaseJwtInboundPolicy,S as SystemRouteName,C as TelemetryPlugin,is as UpstreamAzureAdServiceAuthInboundPolicy,ps as UpstreamFirebaseAdminAuthInboundPolicy,cs as UpstreamFirebaseUserAuthInboundPolicy,ms as UpstreamGcpFederatedAuthInboundPolicy,gs as UpstreamGcpJwtInboundPolicy,ds as UpstreamGcpServiceAuthInboundPolicy,us as UpstreamZuploJwtAuthInboundPolicy,it as VMWareLogInsightLoggingPlugin,fs as ValidateJsonSchemaInbound,xs as WebBotAuthInboundPolicy,ys as XmlToJsonOutboundPolicy,y as ZoneCache,pt as ZuploMcpSdk,D as ZuploRequest,hs as ZuploServices,J as aiGatewayHandler,x as apiServices,M as awsLambdaHandler,jt as defaultGenerateHydrolixEntry,z as environment,Kr as getIdForParameterSchema,Nr as getIdForRefSchema,Mr as getIdForRequestBodySchema,Jr as getRawOperationDataIdentifierName,l as httpStatuses,N as legacyDevPortalHandler,Q as mcpServerHandler,V as openApiSpecHandler,W as redirectHandler,O as redirectLegacyDevPortal,Or 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,$d as cs,A as I,Aa as Ht,Ad as Ur,B as J,Ba as Pt,Bd as $r,C as K,Ca as St,Cd as kr,D as M,Da as Tt,Dd as Fr,E as N,Ea as Ut,Ed as Lr,F as O,Fa as $t,Fd as Rr,Ga as kt,Gb as hr,Gd as qr,Ha as Ft,Hb as mr,Hd as vr,Ia as Lt,Ib as gr,Id as zr,Ja as Rt,Jb as dr,Jd as Gr,Ka as qt,Kb as ur,Kd as Ir,La as vt,Lb as fr,Ld as Qr,Ma as zt,Mb as xr,Md as Vr,Na as Gt,Nb as yr,Nd as Wr,Oa as It,Ob as wr,Od as Xr,Pa as Jt,Pb as Ar,Pd as Yr,Qa as Kt,Qd as Zr,Ra as Mt,Rd as _r,Sa as Nt,Sd as ts,Ta as Ot,Td as rs,U as Q,Ua as Qt,Ud as ss,V,Va as Vt,Vd as es,W,Wa as Wt,Wd as os,X,Xa as Xt,Xd as as,Y,Ya as Yt,Yd as ns,Z,Za as Zt,Zd as is,_,_a as _t,_d as ps,a as n,aa as rt,ab as rr,ae as hs,b as x,ba as st,bb as sr,be as ms,c as y,ca as et,cb as er,ce as gs,d as w,da as ot,db as or,de as ds,e as A,ea as at,eb as ar,ee as us,f as b,fa as nt,fb as nr,fe as fs,g as l,ga as it,gb as ir,ge as xs,h as j,ha as pt,hb as pr,he as ys,i as B,ia as ct,ib as cr,ie as ws,ja as ht,je as As,k as C,ka as mt,ke as bs,l as D,la as gt,m as E,ma as dt,n as H,na as ut,o as P,oa as ft,pa as xt,pd as br,q as T,qa as yt,qd as lr,r as U,ra as wt,rd as jr,s as $,sa as At,sd as Br,t as k,ta as bt,td as Cr,u as F,ua as lt,ud as Dr,v as L,va as jt,vd as Er,w as R,wa as Bt,wd as Hr,x as q,xa as Ct,xd as Pr,y as v,ya as Dt,yd as Sr,z as G,za as Et,zd as Tr}from"./chunk-YVN5OSR4.js";import{a as S,d as z,e as Jr,f as Kr,g as Mr,h as Nr,i as Or}from"./chunk-DQ4ANJLR.js";import"./chunk-2Y72LML3.js";import{_ as u,a as t,aa as a,ba as f}from"./chunk-L3MZGNQA.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,As 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,bs as BackgroundLoader,Jt as BasicAuthInboundPolicy,Lr 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,rr as DataLossPreventionInboundPolicy,sr as DataLossPreventionOutboundPolicy,st as DynaTraceLoggingPlugin,ht as DynatraceMetricsPlugin,er as FirebaseJwtInboundPolicy,or as FormDataToJsonInboundPolicy,ar as GalileoTracingInboundPolicy,nr as GeoFilterInboundPolicy,k as GoogleCloudLoggingPlugin,ir as GraphqlAnalyticsOutboundPolicy,G as Handler,pr as HttpDeprecationOutboundPolicy,B as HttpProblems,b as HttpStatusCode,Bt as HydrolixRequestLoggerPlugin,U as InboundPolicy,cr as JWTScopeValidationInboundPolicy,ft as JwtServicePlugin,et as LokiLoggingPlugin,L as LookupResult,Er as MTLSAuthInboundPolicy,br as McpAuth0OAuthInboundPolicy,hr as McpClerkOAuthInboundPolicy,mr as McpCognitoOAuthInboundPolicy,gr as McpEntraOAuthInboundPolicy,xt as McpGatewayOAuthProtectedResourcePlugin,dr as McpGoogleOAuthInboundPolicy,ur as McpKeycloakOAuthInboundPolicy,fr as McpLogtoOAuthInboundPolicy,lr as McpOAuthInboundPolicy,xr as McpOktaOAuthInboundPolicy,yr as McpOneLoginOAuthInboundPolicy,wr as McpPingOAuthInboundPolicy,Ar as McpWorkosOAuthInboundPolicy,w as MemoryZoneReadThroughCache,jr as MockApiInboundPolicy,Cr as MoesifInboundPolicy,Dr as MonetizationInboundPolicy,ot as NewRelicLoggingPlugin,mt as NewRelicMetricsPlugin,yt as OAuthProtectedResourcePlugin,gt as OTelMetricsPlugin,Hr as OktaFGAAuthZInboundPolicy,Pr as OktaJwtInboundPolicy,Sr as OpenFGAAuthZInboundPolicy,vt as OpenIdJwtInboundPolicy,Tr as OpenMeterInboundPolicy,$ as OutboundPolicy,j as ProblemResponseFormatter,Ur as PromptInjectionDetectionOutboundPolicy,$r as PropelAuthJwtInboundPolicy,kr as QueryParamToHeaderInboundPolicy,Fr as QuotaInboundPolicy,Lr as RateLimitInboundPolicy,Rr as ReadmeMetricsInboundPolicy,qr as RemoveHeadersInboundPolicy,vr as RemoveHeadersOutboundPolicy,zr as RemoveQueryParamsInboundPolicy,Gr as ReplaceStringOutboundPolicy,Ct as RequestLoggerPlugin,Ir as RequestSizeLimitInboundPolicy,Qr as RequestValidationInboundPolicy,Wr as RequireOriginInboundPolicy,R as ResponseSendingEvent,q as ResponseSentEvent,a as RuntimeError,u as SYSTEM_LOGGER,Vr as SchemaBasedRequestValidation,Xr as SecretMaskingOutboundPolicy,T as SemanticAttributes,Yr as SemanticCacheInboundPolicy,ws as ServiceProviderImpl,Zr as SetBodyInboundPolicy,_r as SetHeadersInboundPolicy,ts as SetHeadersOutboundPolicy,rs as SetQueryParamsInboundPolicy,ss as SetStatusOutboundPolicy,es as SetUpstreamApiKeyInboundPolicy,os as SleepInboundPolicy,at as SplunkLoggingPlugin,A as StreamingZoneCache,as as StripeWebhookVerificationInboundPolicy,nt as SumoLogicLoggingPlugin,ns as SupabaseJwtInboundPolicy,S as SystemRouteName,C as TelemetryPlugin,is as UpstreamAzureAdServiceAuthInboundPolicy,ps as UpstreamFirebaseAdminAuthInboundPolicy,cs as UpstreamFirebaseUserAuthInboundPolicy,ms as UpstreamGcpFederatedAuthInboundPolicy,gs as UpstreamGcpJwtInboundPolicy,ds as UpstreamGcpServiceAuthInboundPolicy,us as UpstreamZuploJwtAuthInboundPolicy,it as VMWareLogInsightLoggingPlugin,fs as ValidateJsonSchemaInbound,xs as WebBotAuthInboundPolicy,ys as XmlToJsonOutboundPolicy,y as ZoneCache,pt as ZuploMcpSdk,D as ZuploRequest,hs as ZuploServices,J as aiGatewayHandler,x as apiServices,M as awsLambdaHandler,jt as defaultGenerateHydrolixEntry,z as environment,Kr as getIdForParameterSchema,Nr as getIdForRefSchema,Mr as getIdForRequestBodySchema,Jr as getRawOperationDataIdentifierName,l as httpStatuses,N as legacyDevPortalHandler,Q as mcpServerHandler,V as openApiSpecHandler,W as redirectHandler,O as redirectLegacyDevPortal,Or 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 it,$c as ko,Ab as Qn,Ac as Sr,Bb as se,Bc as Gt,Cb as w,Cc as ct,Db as Ht,Dc as Ge,Eb as B,Ec as _o,Fb as Re,Fc as ue,G as Bn,Gb as pc,Gc as vr,H as l,Hb as mc,Hc as Ar,I as Ln,Ib as fc,Ic as wo,J as Rr,Jb as hc,Jc as Ft,K as ie,Kb as gc,Kc as xr,L as Nn,Lb as yc,Lc as kr,M as _,Mb as _c,Mc as Ro,N as ye,Nb as wc,Nc as E,O as Dt,Ob as Rc,Oc as bo,P as Jn,Pb as bc,Pc as Io,Q as Gn,Qb as eo,Qc as Tr,R as Fn,Rb as to,Rc as Co,S as d,Sb as ro,Sc as So,T as F,Tb as jt,Tc as Ur,Ub as br,Uc as vo,Vb as Bt,Vc as Te,Wb as Lt,Wc as Ao,Xb as at,Xc as dt,Yb as no,Yc as xo,Z as $n,Zb as oo,Zc as $t,_b as ao,_c as ut,a as G,ac as io,ad as To,bc as Ne,bd as Uo,cc as so,cd as Po,dc as Ir,dd as Eo,ec as co,ed as Oo,fc as st,fd as qo,gc as Nt,gd as Zt,hc as uo,hd as Mo,i as ke,ic as lo,id as Do,j as zn,jb as Zn,jc as po,jd as b,kb as $,kc as mo,kd as v,l as Hn,lb as Kn,lc as X,ld as Z,mb as Wn,mc as H,md as le,nb as P,nc as fo,nd as x,ob as Vn,oc as ho,od as Kt,p as jn,pb as He,pc as I,pd as Ic,qb as Yn,qc as ce,qd as Cc,r as Mt,rb as je,rc as Je,sb as g,sc as L,tb as Be,tc as T,ub as Le,uc as go,vb as _e,vc as de,wb as we,wc as yo,xb as zt,xc as be,yb as Xn,yc as Cr,zb as ee,zc as Jt}from"../chunk-LM6CZZF3.js";import"../chunk-DQ4ANJLR.js";import{a as C}from"../chunk-2Y72LML3.js";import{$ as Y,a as n,aa as f,ba as j,ca as Dn,da as qt}from"../chunk-L3MZGNQA.js";F();function Sc(e){let t=Lt.safeParse(e);return t.success?t.data.id:void 0}n(Sc,"parseJsonRpcRequestId");function zo(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Sc(t)}catch{return}}n(zo,"readJsonRpcRequestIdFromBody");function Wt(e){return no.parse({jsonrpc:Bt,...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(Wt,"jsonRpcErrorResponse");function Ho(e){return new ao([oo.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Ho,"urlElicitationRequiredError");var Vt=d.record(d.string(),d.unknown()),vc=d.record(d.string(),d.unknown()),Ac=d.object({name:d.string().min(1),description:d.string().min(1).optional(),annotations:vc.optional(),_meta:Vt.optional()}).strict(),xc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),_meta:Vt.optional()}).strict(),kc=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:Vt.optional()}).strict(),Tc=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:Vt.optional()}).strict(),Uc=d.array(d.union([d.string(),Ac])),Pc=d.array(d.union([d.string(),xc])),Ec=d.array(d.union([d.string(),kc])),Oc=d.array(d.union([d.string(),Tc])),qc=d.object({tools:Uc.optional(),prompts:Pc.optional(),resources:Ec.optional(),resourceTemplates:Oc.optional()}).strict(),Er=[{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 Mc(e,t){return Kn(qc,e,`MCP capability filter policy "${t}"`)}n(Mc,"parseMcpCapabilityFilterOptions");function N(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(N,"isRecord");function Dc(e,t){if(!N(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(Dc,"readParamString");function Or(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(Or,"readRequestId");function No(e){return e===void 0?void 0:JSON.stringify(e)}n(No,"requestIdKey");function zc(e){let t={};for(let r of Er){let o=e[r.option];if(o===void 0)continue;let a=new Map;for(let i of o){let c=Lc(i,r.itemProperty);c!==void 0&&a.set(c.key,c)}t[r.option]=a}return t}n(zc,"buildProjectionMaps");function qr(e){return Er.find(t=>t.listMethod===e)}n(qr,"findListRule");function Hc(e){return e.requests.some(t=>{if(!N(t))return!1;let r=qr(t.method);return r!==void 0&&e.projectionMaps[r.option]!==void 0})}n(Hc,"shouldFilterListResponses");function jc(e){for(let t of Er){let r=e.projectionMaps[t.option];if(r!==void 0)for(let o of t.directMethods){if(e.request.method!==o.method)continue;let a=Dc(e.request.params,o.paramProperty);if(a!==void 0&&!r.has(a))return{id:Or(e.request)}}}}n(jc,"findDisallowedDirectAccess");function Bc(e){return Response.json(Wt({id:e,error:{code:at.MethodNotFound,message:"Method not found"}}))}n(Bc,"methodNotFoundResponse");function Lc(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!N(e))return;let r=e[t];if(typeof r=="string")return{key:r,overlay:e}}n(Lc,"buildProjection");function jo(e){let t=e.base[e.property],r=e.overlay[e.property];return N(r)?N(t)?{...t,...r}:r:t}n(jo,"mergeRecordProperty");function Nc(e,t){let r={...e,...t.overlay},o=jo({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let a=jo({base:e,overlay:t.overlay,property:"_meta"});return a!==void 0&&(r._meta=a),r}n(Nc,"applyProjection");function Bo(e,t,r){if(!N(e))return e;let o=e.result;if(!N(o))return e;let a=o[t.resultProperty];return!Array.isArray(a)||!a.every(i=>N(i)&&typeof i[t.itemProperty]=="string")?e:{...e,result:{...o,[t.resultProperty]:a.flatMap(i=>{if(!N(i))return[];let c=i[t.itemProperty];if(typeof c!="string")return[];let s=r.get(c);return s===void 0?[]:[Nc(i,s)]})}}}n(Bo,"filterAndProjectItems");function Jc(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!N(r))continue;let o=qr(r.method),a=Or(r),i=No(a);o!==void 0&&i!==void 0&&t.set(i,o)}return t}n(Jc,"buildListRulesByResponseId");function Gc(e){if(Array.isArray(e.responseBody)){let o=Jc(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(a=>{if(!N(a)||"error"in a)return a;let i=No(Or(a)),c=i===void 0?void 0:o.get(i),s=c===void 0?void 0:e.projectionMaps[c.option];return c===void 0||s===void 0?a:Bo(a,c,s)})}if(!N(e.requestBody)||!N(e.responseBody)||"error"in e.responseBody)return e.responseBody;let t=qr(e.requestBody.method),r=t===void 0?void 0:e.projectionMaps[t.option];return t===void 0||r===void 0?e.responseBody:Bo(e.responseBody,t,r)}n(Gc,"filterJsonRpcResponse");async function Lo(e){return e.clone().json()}n(Lo,"readJson");function Fc(e){return e.headers.get("content-type")?.includes("json")??!1}n(Fc,"isJsonResponse");var Pr=class extends Mt{static{n(this,"McpCapabilityFilterInboundPolicy")}#e;constructor(t,r){let o=Mc(t,r);super(o,r),this.#e=zc(o)}async handler(t,r){G("policy.inbound.mcp-capability-filter");let o;try{o=await Lo(t)}catch{return t}let a=Array.isArray(o)?o:[o];for(let i of a){if(!N(i))continue;let c=jc({request:i,projectionMaps:this.#e});if(c!==void 0)return Bc(c.id)}return Hc({requests:a,projectionMaps:this.#e})&&r.addResponseSendingHook(async i=>{if(!Fc(i))return i;let c;try{c=await Lo(i)}catch{return i}let s=Gc({requestBody:o,responseBody:c,projectionMaps:this.#e});if(s===c)return i;let u=new Headers(i.headers);return u.delete("content-length"),new Response(JSON.stringify(s),{status:i.status,statusText:i.statusText,headers:u})}),t}};var Mr;Mr=globalThis.crypto;async function $c(e){return(await Mr).getRandomValues(new Uint8Array(e))}n($c,"getRandomValues");async function Zc(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let a=await $c(e-o.length);for(let i of a)i<r&&(o+=t[i%t.length])}return o}n(Zc,"random");async function Kc(e){return await Zc(e)}n(Kc,"generateVerifier");async function Wc(e){let t=await(await Mr).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(Wc,"generateChallenge");async function Dr(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Kc(e),r=await Wc(t);return{code_verifier:t,code_challenge:r}}n(Dr,"pkceChallenge");F();var D=Ln().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Gn.custom,message:"URL must be parseable",fatal:!0}),Bn}).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"}),Yt=Dt({resource:l().url(),authorization_servers:_(D).optional(),jwks_uri:l().url().optional(),scopes_supported:_(l()).optional(),bearer_methods_supported:_(l()).optional(),resource_signing_alg_values_supported:_(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:ie().optional(),authorization_details_types_supported:_(l()).optional(),dpop_signing_alg_values_supported:_(l()).optional(),dpop_bound_access_tokens_required:ie().optional()}),lt=Dt({issuer:l(),authorization_endpoint:D,token_endpoint:D,registration_endpoint:D.optional(),scopes_supported:_(l()).optional(),response_types_supported:_(l()),response_modes_supported:_(l()).optional(),grant_types_supported:_(l()).optional(),token_endpoint_auth_methods_supported:_(l()).optional(),token_endpoint_auth_signing_alg_values_supported:_(l()).optional(),service_documentation:D.optional(),revocation_endpoint:D.optional(),revocation_endpoint_auth_methods_supported:_(l()).optional(),revocation_endpoint_auth_signing_alg_values_supported:_(l()).optional(),introspection_endpoint:l().optional(),introspection_endpoint_auth_methods_supported:_(l()).optional(),introspection_endpoint_auth_signing_alg_values_supported:_(l()).optional(),code_challenge_methods_supported:_(l()).optional(),client_id_metadata_document_supported:ie().optional()}),Vc=Dt({issuer:l(),authorization_endpoint:D,token_endpoint:D,userinfo_endpoint:D.optional(),jwks_uri:D,registration_endpoint:D.optional(),scopes_supported:_(l()).optional(),response_types_supported:_(l()),response_modes_supported:_(l()).optional(),grant_types_supported:_(l()).optional(),acr_values_supported:_(l()).optional(),subject_types_supported:_(l()),id_token_signing_alg_values_supported:_(l()),id_token_encryption_alg_values_supported:_(l()).optional(),id_token_encryption_enc_values_supported:_(l()).optional(),userinfo_signing_alg_values_supported:_(l()).optional(),userinfo_encryption_alg_values_supported:_(l()).optional(),userinfo_encryption_enc_values_supported:_(l()).optional(),request_object_signing_alg_values_supported:_(l()).optional(),request_object_encryption_alg_values_supported:_(l()).optional(),request_object_encryption_enc_values_supported:_(l()).optional(),token_endpoint_auth_methods_supported:_(l()).optional(),token_endpoint_auth_signing_alg_values_supported:_(l()).optional(),display_values_supported:_(l()).optional(),claim_types_supported:_(l()).optional(),claims_supported:_(l()).optional(),service_documentation:l().optional(),claims_locales_supported:_(l()).optional(),ui_locales_supported:_(l()).optional(),claims_parameter_supported:ie().optional(),request_parameter_supported:ie().optional(),request_uri_parameter_supported:ie().optional(),require_request_uri_registration:ie().optional(),op_policy_uri:D.optional(),op_tos_uri:D.optional(),client_id_metadata_document_supported:ie().optional()}),Xt=ye({...Vc.shape,...lt.pick({code_challenge_methods_supported:!0}).shape}),Fe=ye({access_token:l(),id_token:l().optional(),token_type:l(),expires_in:Fn.number().optional(),scope:l().optional(),refresh_token:l().optional()}).strip(),Go=ye({error:l(),error_description:l().optional(),error_uri:l().optional()}),Jo=D.optional().or(Jn("").transform(()=>{})),Yc=ye({redirect_uris:_(D),token_endpoint_auth_method:l().optional(),grant_types:_(l()).optional(),response_types:_(l()).optional(),client_name:l().optional(),client_uri:D.optional(),logo_uri:Jo,scope:l().optional(),contacts:_(l()).optional(),tos_uri:Jo,policy_uri:l().optional(),jwks_uri:D.optional(),jwks:Nn().optional(),software_id:l().optional(),software_version:l().optional(),software_statement:l().optional()}).strip(),Qt=ye({client_id:l(),client_secret:l().optional(),client_id_issued_at:Rr().optional(),client_secret_expires_at:Rr().optional()}).strip(),pt=Yc.merge(Qt),Jh=ye({error:l(),error_description:l().optional()}).strip(),Gh=ye({token:l(),token_type_hint:l().optional()}).strip();function Fo(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(Fo,"resourceUrlFromServerUrl");function $o({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 a=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return a.startsWith(i)}n($o,"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}},mt=class extends A{static{n(this,"InvalidRequestError")}};mt.errorCode="invalid_request";var Ue=class extends A{static{n(this,"InvalidClientError")}};Ue.errorCode="invalid_client";var Pe=class extends A{static{n(this,"InvalidGrantError")}};Pe.errorCode="invalid_grant";var Ee=class extends A{static{n(this,"UnauthorizedClientError")}};Ee.errorCode="unauthorized_client";var ft=class extends A{static{n(this,"UnsupportedGrantTypeError")}};ft.errorCode="unsupported_grant_type";var ht=class extends A{static{n(this,"InvalidScopeError")}};ht.errorCode="invalid_scope";var gt=class extends A{static{n(this,"AccessDeniedError")}};gt.errorCode="access_denied";var pe=class extends A{static{n(this,"ServerError")}};pe.errorCode="server_error";var yt=class extends A{static{n(this,"TemporarilyUnavailableError")}};yt.errorCode="temporarily_unavailable";var _t=class extends A{static{n(this,"UnsupportedResponseTypeError")}};_t.errorCode="unsupported_response_type";var wt=class extends A{static{n(this,"UnsupportedTokenTypeError")}};wt.errorCode="unsupported_token_type";var Rt=class extends A{static{n(this,"InvalidTokenError")}};Rt.errorCode="invalid_token";var bt=class extends A{static{n(this,"MethodNotAllowedError")}};bt.errorCode="method_not_allowed";var It=class extends A{static{n(this,"TooManyRequestsError")}};It.errorCode="too_many_requests";var Oe=class extends A{static{n(this,"InvalidClientMetadataError")}};Oe.errorCode="invalid_client_metadata";var Ct=class extends A{static{n(this,"InsufficientScopeError")}};Ct.errorCode="insufficient_scope";var St=class extends A{static{n(this,"InvalidTargetError")}};St.errorCode="invalid_target";var Zo={[mt.errorCode]:mt,[Ue.errorCode]:Ue,[Pe.errorCode]:Pe,[Ee.errorCode]:Ee,[ft.errorCode]:ft,[ht.errorCode]:ht,[gt.errorCode]:gt,[pe.errorCode]:pe,[yt.errorCode]:yt,[_t.errorCode]:_t,[wt.errorCode]:wt,[Rt.errorCode]:Rt,[bt.errorCode]:bt,[It.errorCode]:It,[Oe.errorCode]:Oe,[Ct.errorCode]:Ct,[St.errorCode]:St};function Xc(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(Xc,"isClientAuthMethod");var zr="code",Hr="S256";function Qc(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Xc(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(Qc,"selectClientAuthMethod");function ed(e,t,r,o){let{client_id:a,client_secret:i}=t;switch(e){case"client_secret_basic":td(a,i,r);return;case"client_secret_post":rd(a,i,o);return;case"none":nd(a,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(ed,"applyClientAuthentication");function td(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(td,"applyBasicAuth");function rd(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(rd,"applyPostAuth");function nd(e,t){t.set("client_id",e)}n(nd,"applyPublicAuth");async function Wo(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Go.parse(JSON.parse(r)),{error:a,error_description:i,error_uri:c}=o,s=Zo[a]||pe;return new s(i||"",c)}catch(o){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new pe(a)}}n(Wo,"parseErrorResponse");async function Lr(e,t){try{return await jr(e,t)}catch(r){if(r instanceof Ue||r instanceof Ee)return await e.invalidateCredentials?.("all"),await jr(e,t);if(r instanceof Pe)return await e.invalidateCredentials?.("tokens"),await jr(e,t);throw r}}n(Lr,"auth");async function jr(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:a,fetchFn:i}){let c=await e.discoveryState?.(),s,u,p,h=a;if(!h&&c?.resourceMetadataUrl&&(h=new URL(c.resourceMetadataUrl)),c?.authorizationServerUrl){if(u=c.authorizationServerUrl,s=c.resourceMetadata,p=c.authorizationServerMetadata??await Xo(u,{fetchFn:i}),!s)try{s=await Yo(t,{resourceMetadataUrl:h},i)}catch{}(p!==c.authorizationServerMetadata||s!==c.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:h?.toString(),resourceMetadata:s,authorizationServerMetadata:p})}else{let M=await dd(t,{resourceMetadataUrl:h,fetchFn:i});u=M.authorizationServerUrl,p=M.authorizationServerMetadata,s=M.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:h?.toString(),resourceMetadata:s,authorizationServerMetadata:p})}let y=await od(t,e,s),U=o||s?.scopes_supported?.join(" ")||e.clientMetadata.scope,R=await Promise.resolve(e.clientInformation());if(!R){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let M=p?.client_id_metadata_document_supported===!0,z=e.clientMetadataUrl;if(z&&!Nr(z))throw new Oe(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${z}`);if(M&&z)R={client_id:z},await e.saveClientInformation?.(R);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Mn=await fd(u,{metadata:p,clientMetadata:e.clientMetadata,scope:U,fetchFn:i});await e.saveClientInformation(Mn),R=Mn}}let q=!e.redirectUrl;if(r!==void 0||q){let M=await md(e,u,{metadata:p,resource:y,authorizationCode:r,fetchFn:i});return await e.saveTokens(M),"AUTHORIZED"}let O=await e.tokens();if(O?.refresh_token)try{let M=await pd(u,{metadata:p,clientInformation:R,refreshToken:O.refresh_token,resource:y,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(M),"AUTHORIZED"}catch(M){if(!(!(M instanceof A)||M instanceof pe))throw M}let oe=e.state?await e.state():void 0,{authorizationUrl:ot,codeVerifier:ae}=await ud(u,{metadata:p,clientInformation:R,state:oe,redirectUrl:e.redirectUrl,scope:U,resource:y});return await e.saveCodeVerifier(ae),await e.redirectToAuthorization(ot),"REDIRECT"}n(jr,"authInternal");function Nr(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(Nr,"isHttpsUrl");async function od(e,t,r){let o=Fo(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!$o({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(od,"selectResourceURL");function Vo(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let a=Br(e,"resource_metadata")||void 0,i;if(a)try{i=new URL(a)}catch{}let c=Br(e,"scope")||void 0,s=Br(e,"error")||void 0;return{resourceMetadataUrl:i,scope:c,error:s}}n(Vo,"extractWWWAuthenticateParams");function Br(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),a=r.match(o);return a?a[1]||a[2]:null}n(Br,"extractFieldFromWwwAuth");async function Yo(e,t,r=fetch){let o=await sd(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 Yt.parse(await o.json())}n(Yo,"discoverOAuthProtectedResourceMetadata");async function Jr(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Jr(e,void 0,r):void 0;throw o}}n(Jr,"fetchWithCorsRetry");function ad(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(ad,"buildWellKnownPath");async function Ko(e,t,r=fetch){return await Jr(e,{"MCP-Protocol-Version":t},r)}n(Ko,"tryMetadataDiscovery");function id(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(id,"shouldAttemptFallback");async function sd(e,t,r,o){let a=new URL(e),i=o?.protocolVersion??br,c;if(o?.metadataUrl)c=new URL(o.metadataUrl);else{let u=ad(t,a.pathname);c=new URL(u,o?.metadataServerUrl??a),c.search=a.search}let s=await Ko(c,i,r);if(!o?.metadataUrl&&id(s,a.pathname)){let u=new URL(`/.well-known/${t}`,a);s=await Ko(u,i,r)}return s}n(sd,"discoverMetadataWithFallback");function cd(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 a=t.pathname;return a.endsWith("/")&&(a=a.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:"oidc"}),o.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(cd,"buildDiscoveryUrls");async function Xo(e,{fetchFn:t=fetch,protocolVersion:r=br}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},a=cd(e);for(let{url:i,type:c}of a){let s=await Jr(i,o,t);if(s){if(!s.ok){if(await s.body?.cancel(),s.status>=400&&s.status<500)continue;throw new Error(`HTTP ${s.status} trying to load ${c==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return c==="oauth"?lt.parse(await s.json()):Xt.parse(await s.json())}}}n(Xo,"discoverAuthorizationServerMetadata");async function dd(e,t){let r,o;try{r=await Yo(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 a=await Xo(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:a,resourceMetadata:r}}n(dd,"discoverOAuthServerInfo");async function ud(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:a,state:i,resource:c}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(zr))throw new Error(`Incompatible auth server: does not support response type ${zr}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Hr))throw new Error(`Incompatible auth server: does not support code challenge method ${Hr}`)}else s=new URL("/authorize",e);let u=await Dr(),p=u.code_verifier,h=u.code_challenge;return s.searchParams.set("response_type",zr),s.searchParams.set("client_id",r.client_id),s.searchParams.set("code_challenge",h),s.searchParams.set("code_challenge_method",Hr),s.searchParams.set("redirect_uri",String(o)),i&&s.searchParams.set("state",i),a&&s.searchParams.set("scope",a),a?.includes("offline_access")&&s.searchParams.append("prompt","consent"),c&&s.searchParams.set("resource",c.href),{authorizationUrl:s,codeVerifier:p}}n(ud,"startAuthorization");function ld(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(ld,"prepareAuthorizationCodeRequest");async function Qo(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:a,resource:i,fetchFn:c}){let s=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(i&&r.set("resource",i.href),a)await a(u,r,s,t);else if(o){let h=t?.token_endpoint_auth_methods_supported??[],y=Qc(o,h);ed(y,o,u,r)}let p=await(c??fetch)(s,{method:"POST",headers:u,body:r});if(!p.ok)throw await Wo(p);return Fe.parse(await p.json())}n(Qo,"executeTokenRequest");async function pd(e,{metadata:t,clientInformation:r,refreshToken:o,resource:a,addClientAuthentication:i,fetchFn:c}){let s=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),u=await Qo(e,{metadata:t,tokenRequestParams:s,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:c});return{refresh_token:o,...u}}n(pd,"refreshAuthorization");async function md(e,t,{metadata:r,resource:o,authorizationCode:a,fetchFn:i}={}){let c=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(c)),!s){if(!a)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();s=ld(a,p,e.redirectUrl)}let u=await e.clientInformation();return Qo(t,{metadata:r,tokenRequestParams:s,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:i})}n(md,"fetchToken");async function fd(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:a}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let c=await(a??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!c.ok)throw await Wo(c);return pt.parse(await c.json())}n(fd,"registerClient");var Gr="zuplo.com",hd=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),gd=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function ea(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(ea,"s2FaviconHref");function yd(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(yd,"strictFaviconHref");var er=ea(Gr);function Fr(e){let t=e.toLowerCase();return t===Gr||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?ea(Gr):yd(e)}n(Fr,"resolveIconHref");function _d(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(_d,"hostnameFromHost");function wd(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(wd,"isLocalOrAddressHost");function Rd(e){let t=_d(e).toLowerCase().replace(/\.$/,"");if(wd(t)||gd.some(i=>t===i.slice(1)||t.endsWith(i)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let o=r.slice(-2).join("."),a=hd.has(o)?3:2;return r.slice(-a).join(".")}n(Rd,"inferFaviconDomain");function $r(e){return{src:Fr(Rd(e)),mimeType:"image/png",sizes:["128x128"]}}n($r,"resolveMcpFaviconIcon");function tr(e){try{return $r(new URL(e).host)}catch{return}}n(tr,"resolveMcpFaviconIconFromUrl");function Ie(e){let t=X().connectionsById.get(e);if(!t)throw new j(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,description:t.description,serverInfo:t.serverInfo,transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}n(Ie,"getUpstreamServerConfig");function rr(e){let t=X().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new j(`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.authConfig}n(rr,"getUpstreamAuthConfig");function $e(e,t){let r=rr({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new j(`Upstream server "${e}" does not use upstream OAuth. Select authMode "shared-oauth" or "user-oauth" before starting an upstream OAuth connection flow.`);return r.oauth}n($e,"requireUpstreamOAuthConfig");function ta(e,t){let r=rr({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new j(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(ta,"requireUpstreamIdJagConfig");function ra(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(ra,"mergeAbortSignals");async function bd(e){try{await e.cancel()}catch{}}n(bd,"cancelReader");async function nr(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],a=0,i=await r.read();for(;!i.done;){let u=i.value;if(a+=u.byteLength,a>t.maxBytes)throw await bd(r),t.createLimitError();o.push(u),i=await r.read()}let c=new Uint8Array(a),s=0;for(let u of o)c.set(u,s),s+=u.byteLength;return c}n(nr,"readBoundedByteStream");var Id=2,Cd=1024*1024,Sd=1e4,vd=new Set([301,302,303,307,308]),Ad=["authorization","proxy-authorization","cookie","cookie2"];function Zr(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Zr,"readRequestUrl");function Ze(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(Ze,"readRequestMethod");function xd(e,t,r){let o=e.headers.get("content-length");if(!o)return;let a=Number.parseInt(o,10);if(Number.isFinite(a)&&a>t)throw new f({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}})}n(xd,"assertContentLengthWithinLimit");async function kd(e,t,r){return xd(e,t,r),nr(e.body,{maxBytes:t,createLimitError:n(()=>new f({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}}),"createLimitError")})}n(kd,"readBoundedResponseBody");function Td(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(Td,"responseFromBufferedBody");function Ud(e,t){if(!vd.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(Ud,"resolveRedirectUrl");function na(e,t){try{return t.validateUrl(e)}catch(r){throw new f({message:"Outbound URL was not allowed.",extensionMembers:{[g]:t.problemCode}},{cause:r})}}n(na,"validateOutboundUrl");function Pd(e,t){throw e instanceof f&&zt(e.extensionMembers?.[g])?e:new f({message:"Outbound fetch failed.",extensionMembers:{[g]:t}},{cause:e})}n(Pd,"normalizeFetchError");function vt(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,a]of Object.entries(t.extra))a!==void 0&&(r[o]=a);t.error!==void 0&&L(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(vt,"logOutboundFailure");async function Ed(e,t,r,o,a,i,c){let s=Ze(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";vt(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:s,host:T(i),error:u,extra:{abortReason:c()}}),Pd(u,a)}}n(Ed,"fetchWithNormalizedError");function Od(e){if(e.redirects>=e.maxRedirects)throw new f({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[g]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new f({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[g]:e.problemCode}})}n(Od,"assertRedirectAllowed");function qd(e,t){let r=new Headers(e);for(let o of Ad)r.delete(o);for(let o of t)r.delete(o);return r}n(qd,"stripCrossOriginHeaders");function Md(e,t,r,o,a){let i={...e,method:t,redirect:"manual",signal:r};return o&&(i.headers=qd(e.headers,a)),i}n(Md,"buildRedirectInit");function Dd(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(Dd,"buildInitialRequestInit");function zd(e){let t=Ze(e.currentInput,e.currentInit);Od({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=na(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),a=r.origin!==o.origin,i=r.toString();return{currentInput:i,currentUrl:i,currentInit:Md(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(zd,"followRedirect");async function Kr(e,t,r){let o=r.problemCode??"invalid_request",a=r.maxRedirects??Id,i=r.maxResponseBytes??Cd,c=r.timeoutMs??Sd,s=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,h=new AbortController,y=ra(h,t.signal),U=!1,R=setTimeout(()=>{U=!0,h.abort()},c),q=e,O=Dd(e,t,h.signal),oe;try{oe=na(Zr(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(ae){throw vt(p,{event:"outbound_url_blocked",problemCode:o,method:Ze(e,t),host:T(Zr(e)),error:ae}),clearTimeout(R),y?.(),ae}let ot=0;try{for(;;){let ae=await Ed(p,s,q,O,o,oe,()=>U?`timeout_after_${c}ms`:void 0),M=Ud(ae,oe);if(M!==void 0)try{let z=zd({currentInput:q,currentInit:O,currentUrl:oe,redirectUrl:M,redirects:ot,maxRedirects:a,problemCode:o,validateUrl:r.validateUrl,signal:h.signal,additionalCrossOriginStrippedHeaders:u});q=z.currentInput,O=z.currentInit,oe=z.currentUrl,ot=z.redirects;continue}catch(z){throw vt(p,{event:"outbound_redirect_blocked",problemCode:o,method:Ze(q,O),host:T(oe),error:z,extra:{redirects:ot,maxRedirects:a,redirectTargetHost:T(M)}}),z}try{return Td(ae,await kd(ae,i,o))}catch(z){throw vt(p,{event:"outbound_response_size_exceeded",problemCode:o,method:Ze(q,O),host:T(oe),error:z,extra:{maxResponseBytes:i,status:ae.status}}),z}}}finally{clearTimeout(R),y?.()}}n(Kr,"runSafeOutboundExchange");async function At(e,t,r){let o=await Kr(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(a){throw vt(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Ze(e,t),host:T(Zr(e)),error:a,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new f({message:"Outbound JSON response could not be parsed.",extensionMembers:{[g]:r.problemCode??"invalid_request"}},{cause:a})}}n(At,"runSafeOutboundJsonExchange");function oa(e,t={},r={}){return Kr(e,t,{...r,validateUrl:dt})}n(oa,"fetchConfiguredOutbound");function aa(e,t={},r={}){return At(e,t,{...r,validateUrl:dt})}n(aa,"fetchConfiguredOutboundJson");function or(e,t={},r={}){return At(e,t,{...r,validateUrl:xo})}n(or,"fetchIdentityProviderJson");function ia(e,t={},r={}){return At(e,t,{...r,validateUrl:$t})}n(ia,"fetchCimdClientMetadataJson");function sa(e,t={},r={}){return At(e,t,{...r,validateUrl:ut})}n(sa,"fetchCimdClientJwksJson");F();import{errors as ma,jwtVerify as fa,SignJWT as ha}from"jose";var J="zuplo-mcp-gateway",K=J,W="HS256";import{base64url as Hd}from"jose";var jd=new TextEncoder,Bd="MCP gateway could not initialize secure key material.",Ld=32,ca=new Map,da=new Map,Nd;function Jd(){return Nd??Dn.instance.authPrivateKey}n(Jd,"readAuthPrivateKey");function ua(e){return new Y(Bd,e===void 0?void 0:{cause:e})}n(ua,"createGeneratedKeyMaterialError");function la(e,t){let r=Hd.decode(t);if(r.byteLength!==Ld)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(la,"decodeJwkKeyField");function Gd(e){let t=Jd();if(!t)throw ua();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=la("d",r.d);la("x",r.x);let a=jd.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),i=new Uint8Array(a.byteLength+o.byteLength);return i.set(a),i.set(o,a.byteLength),i}catch(r){throw ua(r)}}n(Gd,"decodeGeneratedKeyMaterial");function Fd(e){let t=ca.get(e);return t||(t=Gd(e),ca.set(e,t)),t}n(Fd,"getMasterKeyMaterial");async function re(e){let t=da.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Fd(e.keyMaterialPurpose));return da.set(e.purpose,r),r}n(re,"readCachedDerivedKey");var $d="SHA-256",Zd=32,Kd="zuplo-mcp-gateway:",Wd=new TextEncoder,pa=new WeakMap;async function Ce(e,t){let r=pa.get(e);r||(r=new Map,pa.set(e,r));let o=r.get(t);if(o)return o;let a=await Vd(e,t);return r.set(t,a),a}n(Ce,"deriveGatewaySigningKey");async function Vd(e,t){let r=Z(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=Wd.encode(`${Kd}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:$d,salt:new Uint8Array,info:Z(a)},o,Zd*8);return new Uint8Array(i)}n(Vd,"hkdfExpand");var ga=900,Yd=900,Xd=co.extend({id:Eo}),Qd=Xd.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ya=Ir.extend({id:Oo,purpose:d.literal("browser_connect")}),eu=Ir.extend({purpose:d.literal("browser_connect")}),tu=ya.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),_a=ga*1e3;async function wa(){return re({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ce(e,"oauth-state"),"derive")})}n(wa,"getOAuthStateKey");async function Ra(){return re({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ce(e,"browser-connect"),"derive")})}n(Ra,"getBrowserConnectKey");async function ba(e){let t=Math.floor(Date.now()/1e3)+ga;return new ha(e).setProtectedHeader({alg:W,typ:"JWT"}).setIssuer(J).setAudience(K).setIssuedAt().setExpirationTime(t).sign(await wa())}n(ba,"signOAuthState");async function ar(e){try{let{payload:t}=await fa(e,await wa(),{algorithms:[W],issuer:J,audience:K});return Qd.parse(t)}catch(t){throw t instanceof ma.JWTExpired?new f({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new f({message:"OAuth state could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(ar,"verifyOAuthState");async function Ia(e){let t=Math.floor(Date.now()/1e3)+Yd,r=eu.parse(e),o=ya.parse({...r,id:Do()});return new ha(o).setProtectedHeader({alg:W,typ:"JWT"}).setIssuer(J).setAudience(K).setIssuedAt().setExpirationTime(t).sign(await Ra())}n(Ia,"signBrowserConnectTicket");async function Ca(e){try{let{payload:t}=await fa(e,await Ra(),{algorithms:[W],issuer:J,audience:K});return tu.parse(t)}catch(t){throw t instanceof ma.JWTExpired?new f({message:"Browser connect ticket has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new f({message:"Browser connect ticket could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(Ca,"verifyBrowserConnectTicket");async function Sa(e){if((await b().consumeBrowserConnectTicket({id:e.id,expiresAt:I(new Date(e.exp*1e3)),now:I(new Date)})).kind==="consumed")throw new f({message:"Browser connect ticket has already been used",extensionMembers:{[g]:"oauth_state_reused"}})}n(Sa,"consumeBrowserConnectTicket");function ru(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(ru,"buildConnectRequiredMessage");async function nu(e){let t=P(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 Ia({...st(e),purpose:"browser_connect"})),r.toString()}n(nu,"buildGatewayBrowserTicketUrl");function ou(e){return H().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(ou,"buildGatewayConnectPath");async function Wr(e){return nu({...e,path:ou(e.upstreamServerId),redirect:!0})}n(Wr,"buildGatewayConnectUrl");async function ir(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 Wr(t),message:ru(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(ir,"buildRedirectConnectRequiredResponse");function va(e){return au({...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(va,"buildAdminConnectRequiredResponse");function au(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(au,"buildAdminSetupRequiredResponse");F();var Aa=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function iu(e,t){return e&&e.length>0?e.join(t):void 0}n(iu,"joinOAuthScopes");function su(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of Aa)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(su,"sanitizeAuthorizationServerMetadata");function xa(e){let t=su(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(xa,"sanitizeOAuthDiscoveryState");function ka(e){let t=new URL(e);for(let r of Aa){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(ka,"dedupeSingletonAuthorizationRequestParams");function sr(e){let t=new URL(e);return $(t)&&Zn(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(sr,"normalizeLoopbackOAuthRedirectUri");function Ta(e){return iu(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(Ta,"readProtectedResourceMetadataScope");function cu(e){return`Zuplo MCP Gateway - ${e}`}n(cu,"buildGatewayOAuthClientName");function du(e,t){return e&&e.length>0?e.join(t):void 0}n(du,"joinOAuthScopeList");function uu(e){if(e.clientRegistration.mode!=="auto")return du(e.scopes,e.scopeDelimiter)}n(uu,"readPublicClientMetadataScope");function Vr(e){return new URL(H().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Vr,"buildOAuthClientMetadataDocumentUrl");function Yr(e){let t=Ie(e.upstreamServerId);return{client_name:cu(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(Yr,"buildGatewayOAuthClientMetadata");function Ua(e,t,r){let o=$e(t,r),a=uu(o);return{client_id:Vr({origin:e,upstreamServerId:t}),...Yr({origin:e,upstreamServerId:t,redirectUri:sr(new URL(o.redirectPath,e)).toString(),scope:a})}}n(Ua,"buildOAuthClientMetadataDocument");F();import{base64url as Se}from"jose";var lu="SHA-256",Ke="AES-GCM",pu=12,Qr="zuplo-secret",en=1,Pa="generated:auth_private_key:token-encryption",mu=d.object({version:d.literal(en),keyId:d.literal(Pa),algorithm:d.literal(Ke),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();async function Xr(){return re({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(lu,Z(e));return crypto.subtle.importKey("raw",t,{name:Ke},!1,["encrypt","decrypt"])},"derive")})}n(Xr,"getEncryptionKey");function Ea(e){return Z(new TextEncoder().encode(`${Qr}:v${e.version}:${e.keyId}`))}n(Ea,"getAssociatedData");function fu(e){return`${Qr}:v${e.version}:${Se.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(fu,"encodeEnvelope");function hu(e){let t=`${Qr}:v${en}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(Se.decode(r));return mu.parse(JSON.parse(o))}n(hu,"decodeEnvelope");async function me(e){let t=await Xr(),r=crypto.getRandomValues(new Uint8Array(pu)),o={version:en,keyId:Pa},a=await crypto.subtle.encrypt({name:Ke,iv:r,additionalData:Ea(o)},t,new TextEncoder().encode(e));return fu({...o,algorithm:Ke,iv:Se.encode(r),ciphertext:Se.encode(new Uint8Array(a))})}n(me,"encryptSecret");async function ve(e){let t=hu(e);if(t){let c=await Xr(),s=await crypto.subtle.decrypt({name:Ke,iv:Z(Se.decode(t.iv)),additionalData:Ea(t)},c,Z(Se.decode(t.ciphertext)));return new TextDecoder().decode(s)}let[r,o]=e.split(".");if(!r||!o)throw new Y("Encrypted payload is malformed");let a=await Xr(),i=await crypto.subtle.decrypt({name:Ke,iv:Z(Se.decode(r))},a,Z(Se.decode(o)));return new TextDecoder().decode(i)}n(ve,"decryptSecret");var gu=d.union([pt,Qt]),yu=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:Yt.optional(),authorizationServerMetadata:d.union([lt,Xt]).optional()}).passthrough(),_u="Bearer",wu="__zuplo_refresh_only_upstream_access_token__";function Ru(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Ru,"splitScopes");function bu(e){return je.parse(e)}n(bu,"parsePkceCodeVerifier");function Iu(e){if(typeof e.expires_in=="number")return I(new Date(Date.now()+e.expires_in*1e3))}n(Iu,"readTokenExpiry");async function Cu(e){if(e!==void 0)return me(JSON.stringify(e))}n(Cu,"encryptJson");async function Su(e,t){if(!e)return;let r=await ve(e);try{return t.parse(JSON.parse(r))}catch(o){throw new f({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:o})}}n(Su,"decryptJson");function vu(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(vu,"clientInformationAllowsRedirectUri");function Au(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(Au,"clientInformationMatchesCurrentClientMetadataUrl");function xu(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(xu,"isUrlBasedClientInformation");function ku(e,t){return t===void 0?e:{...e,scope:t}}n(ku,"applyOAuthClientMetadataScope");function Tu(e,t){return Ta({state:e,delimiter:t})}n(Tu,"readResourceMetadataScope");function Uu(e,t){return e&&e.length>0?e.join(t):void 0}n(Uu,"joinOAuthScopeList");function Pu(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new j(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return pt.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(Pu,"buildManualOAuthClientInformation");function Eu(e,t){let r=Vr({origin:new URL(t).origin,upstreamServerId:e});return Nr(r)?r:void 0}n(Eu,"buildClientMetadataUrl");function Ou(e){for(let t of e)if(t!==void 0)return t}n(Ou,"firstDefined");function qu(e){let t=$e(e.target.upstreamServerId,e.target.authProfileId),r=Uu(t.scopes,t.scopeDelimiter),o=Yr({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:Pu({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let a=Eu(e.target.upstreamServerId,e.redirectUri);return a===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,clientMetadataUrl:a}}n(qu,"buildInitialOAuthClientSetup");function Mu(e,t){if(t===void 0)return Ou([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(Mu,"readEncryptedClientInformation");var qe=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredScope;scopeDelimiter;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;connection;pendingState;encryptedClientInformation;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;constructor(t){let r=qu({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=Mu(t,this.configuredClientInformation)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return ku(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return ba({id:t.id,...st({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,de()?.info({event:"upstream_oauth_client_registered",upstreamServerId:this.target.upstreamServerId,clientId:"client_id"in t?t.client_id:void 0,redirectUriCount:"redirect_uris"in t?t.redirect_uris.length:void 0},"Upstream OAuth client registered for the gateway"),!xu({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Cu(t),await this.syncPendingState(!1)))}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=xa(yu.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,de()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:T(r.authorizationServerUrl),resourceMetadataHost:T(r.resourceMetadataUrl),resource:r.resourceMetadata?.resource,scopesSupportedCount:r.resourceMetadata?.scopes_supported?.length,hasResourceMetadata:r.resourceMetadata!==void 0},"Upstream OAuth discovery resolved authorization server and resource"),this.inferredScope=Tu(r,this.scopeDelimiter)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Fe.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,a=r.refresh_token?await me(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:Fe.parse({...r,refresh_token:await ve(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let i={id:this.connection?.id??Zt(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await me(r.access_token),encryptedRefreshToken:a,scopes:Ru(r.scope??this.readEffectiveScope()),expiresAt:Iu(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await b().upsertUpstreamConnection(i),de()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionId:this.connection.id,hasRefreshToken:!!a,scopeCount:i.scopes.length,expiresAt:i.expiresAt},"Upstream OAuth tokens persisted; upstream connection is active")}async redirectToAuthorization(t){let r=ka(t);this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:bu(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new f({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",a=t==="all"||t==="discovery",i=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),a&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.challengeScope=void 0,this.inferredScope=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(i),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:Mo(),...st({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:I(new Date(Date.now()+_a)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,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})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await Su(this.encryptedClientInformation,gu)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&(!vu(t,this.redirectUriValue)||!Au({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=Qt.parse({client_id:this.clientMetadataUrl})),this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async readCachedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;this.discoveryStateLoaded=!0}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 ve(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await ve(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=Fe.parse({access_token:t??wu,token_type:_u,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&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var Du=3e4,zu=256*1024,Hu=2;function ju(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(ju,"hasUsableAccessToken");var Bu="does not support dynamic client registration",Lu=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],Nu=["HTTP 403 Forbidden","Access Denied","permission to access"],Ju=new Set(["access_denied","invalid_client","invalid_grant","invalid_request","invalid_scope","invalid_target","unauthorized_client","unsupported_grant_type"]);function Gu(e){return e instanceof Error&&e.message.includes(Bu)}n(Gu,"isDynamicClientRegistrationUnsupported");function Fu(e){return e instanceof Error&&Lu.some(t=>e.message.includes(t))}n(Fu,"isProtectedResourceMetadataUnavailable");function $u(e){return e instanceof Error&&Nu.some(t=>e.message.includes(t))}n($u,"isUpstreamProviderAccessDenied");function Zu(e){return e instanceof A&&Ju.has(e.errorCode)}n(Zu,"isStoredConnectionReconsentError");function Ku(e){if(e.error instanceof f&&e.error.extensionMembers?.[g]!==void 0)return e.error;if(Gu(e.error))return new f({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(Fu(e.error))return new f({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($u(e.error))return new f({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(Ku,"mapUpstreamOAuthSetupError");function Wu(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(Wu,"readOAuthFetchRequest");function Vu(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(Vu,"responseLooksJson");function Yu(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(Yu,"responseLooksHtml");function Xu(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new f({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",[_e]:e.response.status,[Be]:r,[we]:e.request.url.toString(),[Le]:e.body}})}n(Xu,"throwUpstreamHtmlError");function Qu(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return{};let r=t;return{error:typeof r.error=="string"?r.error:void 0,errorDescription:typeof r.error_description=="string"?r.error_description:void 0}}catch{return{}}}n(Qu,"readUpstreamOAuthErrorBody");function el(e){let{error:t,errorDescription:r}=Qu(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.request.method??"GET",host:T(e.request.url),path:e.request.url.pathname,status:e.response.status,oauthError:t,oauthErrorDescription:r?.slice(0,256)},"Upstream OAuth HTTP request returned an error response")}n(el,"logUpstreamOAuthHttpError");function qa(e){return async(t,r)=>{let o=Wu(t),a=de(),i=Date.now(),c=await oa(t,r,{maxRedirects:Hu,maxResponseBytes:zu,problemCode:"upstream_token_exchange_failed",timeoutMs:Du}),s=await c.clone().text();if(a?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:o.method??"GET",host:T(o.url),path:o.url.pathname,status:c.status,durationMs:Date.now()-i,responseChars:s.length},"Upstream OAuth HTTP request completed"),c.ok||el({log:a,upstreamServerId:e,request:o,response:c,body:s}),!c.ok&&Yu(c,s)&&Xu({upstreamServerId:e,request:o,response:c,body:s}),!Vu(c,s))return c;try{JSON.parse(s)}catch(u){throw new f({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[g]:"upstream_token_exchange_failed"}},{cause:u})}return c}}n(qa,"createUpstreamOAuthFetch");function Ma(e){de()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:T(e.serverUrl),resourceMetadataHost:T(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}n(Ma,"logUpstreamOAuthFlowStarted");function Da(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=T(e.serverUrl);r!==void 0&&(t.serverHost=r);let o=e.error instanceof f?e.error.extensionMembers?.[g]:void 0;typeof o=="string"&&(t.code=o),L(t,"error",e.error),de()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(Da,"logUpstreamOAuthFlowFailed");async function za(e,t){e.applyChallengeScope(t.requestedScope),Ma({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:qa(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),await Lr(e,r)}catch(r){Da({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=Ku({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(za,"runUpstreamOAuth");async function tl(e,t){e.applyChallengeScope(t.requestedScope),Ma({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:qa(t.upstreamServerId)};t.requestedScope!==void 0&&(r.scope=t.requestedScope);try{return await Lr(e,r)}catch(o){throw Da({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:o}),o}}n(tl,"exchangeUpstreamAuthorizationCode");async function Ha(e,t){let r=await za(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new f({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new f({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Ha,"requireUpstreamAuthorizationRedirect");async function ja(e){if(!e.forceRefresh&&ju(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t;try{t=await za(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(r){if(e.connection===void 0||!Zu(r))throw r;return de()?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:r.errorCode},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),{kind:"connect_required",payload:await Oa({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}})}}if(t==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(t!=="REDIRECT")throw new f({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new f({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 Oa({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(ja,"authorizeUpstreamOAuthSession");async function rl(e){let t=await ar(e.stateToken),r=await b().consumeUpstreamOAuthState({id:t.id,now:I(new Date)}),o=nl(r);return ol({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),al(o),o}n(rl,"consumeStoredCallbackState");function nl(e){switch(e.kind){case"consumed":throw new f({message:"OAuth state has already been used",extensionMembers:{[g]:"oauth_state_reused"}});case"missing":throw new f({message:"OAuth state is missing or expired",extensionMembers:{[g]:"oauth_state_expired"}});case"available":return e.record}}n(nl,"readConsumedCallbackState");function ol(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 f({message:"OAuth callback did not match the initiating request",extensionMembers:{[g]:"oauth_callback_mismatch"}})}n(ol,"assertStoredCallbackStateMatches");function al(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new f({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}})}n(al,"assertStoredCallbackStateFresh");async function Oa(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),va(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),ir(t)}n(Oa,"buildOAuthConnectRequiredResponse");async function Ba(e){let t=await rl({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Nt(t),[o]=await b().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),a={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&&(a.connection=o);let i=new qe(a),c=await tl(i,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(c==="AUTHORIZED")return t;throw c!=="REDIRECT"?new f({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${c}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new f({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Ba,"finishUpstreamOAuthCallback");F();import{importPKCS8 as il,SignJWT as sl}from"jose";var Na=1e4,Ja=64*1024,Ga=2,cl=300,te=d.string().min(1),dl=d.object({access_token:te,issued_token_type:d.literal(Sr),token_type:d.string().optional(),expires_in:d.number().int().positive().optional(),scope:te.optional()}).passthrough(),ul=d.object({id_token:te,token_type:te.optional(),expires_in:d.number().int().positive().optional(),refresh_token:te.optional(),scope:te.optional()}).passthrough(),ll=d.object({access_token:te,token_type:te,expires_in:d.number().int().positive().optional(),scope:te.optional(),resource:te.optional(),refresh_token:te.optional()}).passthrough();function La(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(La,"formEncodeClientCredential");function pl(e){return e.replaceAll("\\n",`
25
+ import{$b as it,$c as ko,Ab as Qn,Ac as Sr,Bb as se,Bc as Gt,Cb as w,Cc as ct,Db as Ht,Dc as Ge,Eb as B,Ec as _o,Fb as Re,Fc as ue,G as Bn,Gb as pc,Gc as vr,H as l,Hb as mc,Hc as Ar,I as Ln,Ib as fc,Ic as wo,J as Rr,Jb as hc,Jc as Ft,K as ie,Kb as gc,Kc as xr,L as Nn,Lb as yc,Lc as kr,M as _,Mb as _c,Mc as Ro,N as ye,Nb as wc,Nc as E,O as Dt,Ob as Rc,Oc as bo,P as Jn,Pb as bc,Pc as Io,Q as Gn,Qb as eo,Qc as Tr,R as Fn,Rb as to,Rc as Co,S as d,Sb as ro,Sc as So,T as F,Tb as jt,Tc as Ur,Ub as br,Uc as vo,Vb as Bt,Vc as Te,Wb as Lt,Wc as Ao,Xb as at,Xc as dt,Yb as no,Yc as xo,Z as $n,Zb as oo,Zc as $t,_b as ao,_c as ut,a as G,ac as io,ad as To,bc as Ne,bd as Uo,cc as so,cd as Po,dc as Ir,dd as Eo,ec as co,ed as Oo,fc as st,fd as qo,gc as Nt,gd as Zt,hc as uo,hd as Mo,i as ke,ic as lo,id as Do,j as zn,jb as Zn,jc as po,jd as b,kb as $,kc as mo,kd as v,l as Hn,lb as Kn,lc as X,ld as Z,mb as Wn,mc as H,md as le,nb as P,nc as fo,nd as x,ob as Vn,oc as ho,od as Kt,p as jn,pb as He,pc as I,pd as Ic,qb as Yn,qc as ce,qd as Cc,r as Mt,rb as je,rc as Je,sb as g,sc as L,tb as Be,tc as T,ub as Le,uc as go,vb as _e,vc as de,wb as we,wc as yo,xb as zt,xc as be,yb as Xn,yc as Cr,zb as ee,zc as Jt}from"../chunk-YVN5OSR4.js";import"../chunk-DQ4ANJLR.js";import{a as C}from"../chunk-2Y72LML3.js";import{$ as Y,a as n,aa as f,ba as j,ca as Dn,da as qt}from"../chunk-L3MZGNQA.js";F();function Sc(e){let t=Lt.safeParse(e);return t.success?t.data.id:void 0}n(Sc,"parseJsonRpcRequestId");function zo(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Sc(t)}catch{return}}n(zo,"readJsonRpcRequestIdFromBody");function Wt(e){return no.parse({jsonrpc:Bt,...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(Wt,"jsonRpcErrorResponse");function Ho(e){return new ao([oo.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Ho,"urlElicitationRequiredError");var Vt=d.record(d.string(),d.unknown()),vc=d.record(d.string(),d.unknown()),Ac=d.object({name:d.string().min(1),description:d.string().min(1).optional(),annotations:vc.optional(),_meta:Vt.optional()}).strict(),xc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),_meta:Vt.optional()}).strict(),kc=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:Vt.optional()}).strict(),Tc=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:Vt.optional()}).strict(),Uc=d.array(d.union([d.string(),Ac])),Pc=d.array(d.union([d.string(),xc])),Ec=d.array(d.union([d.string(),kc])),Oc=d.array(d.union([d.string(),Tc])),qc=d.object({tools:Uc.optional(),prompts:Pc.optional(),resources:Ec.optional(),resourceTemplates:Oc.optional()}).strict(),Er=[{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 Mc(e,t){return Kn(qc,e,`MCP capability filter policy "${t}"`)}n(Mc,"parseMcpCapabilityFilterOptions");function N(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(N,"isRecord");function Dc(e,t){if(!N(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(Dc,"readParamString");function Or(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(Or,"readRequestId");function No(e){return e===void 0?void 0:JSON.stringify(e)}n(No,"requestIdKey");function zc(e){let t={};for(let r of Er){let o=e[r.option];if(o===void 0)continue;let a=new Map;for(let i of o){let c=Lc(i,r.itemProperty);c!==void 0&&a.set(c.key,c)}t[r.option]=a}return t}n(zc,"buildProjectionMaps");function qr(e){return Er.find(t=>t.listMethod===e)}n(qr,"findListRule");function Hc(e){return e.requests.some(t=>{if(!N(t))return!1;let r=qr(t.method);return r!==void 0&&e.projectionMaps[r.option]!==void 0})}n(Hc,"shouldFilterListResponses");function jc(e){for(let t of Er){let r=e.projectionMaps[t.option];if(r!==void 0)for(let o of t.directMethods){if(e.request.method!==o.method)continue;let a=Dc(e.request.params,o.paramProperty);if(a!==void 0&&!r.has(a))return{id:Or(e.request)}}}}n(jc,"findDisallowedDirectAccess");function Bc(e){return Response.json(Wt({id:e,error:{code:at.MethodNotFound,message:"Method not found"}}))}n(Bc,"methodNotFoundResponse");function Lc(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!N(e))return;let r=e[t];if(typeof r=="string")return{key:r,overlay:e}}n(Lc,"buildProjection");function jo(e){let t=e.base[e.property],r=e.overlay[e.property];return N(r)?N(t)?{...t,...r}:r:t}n(jo,"mergeRecordProperty");function Nc(e,t){let r={...e,...t.overlay},o=jo({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let a=jo({base:e,overlay:t.overlay,property:"_meta"});return a!==void 0&&(r._meta=a),r}n(Nc,"applyProjection");function Bo(e,t,r){if(!N(e))return e;let o=e.result;if(!N(o))return e;let a=o[t.resultProperty];return!Array.isArray(a)||!a.every(i=>N(i)&&typeof i[t.itemProperty]=="string")?e:{...e,result:{...o,[t.resultProperty]:a.flatMap(i=>{if(!N(i))return[];let c=i[t.itemProperty];if(typeof c!="string")return[];let s=r.get(c);return s===void 0?[]:[Nc(i,s)]})}}}n(Bo,"filterAndProjectItems");function Jc(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!N(r))continue;let o=qr(r.method),a=Or(r),i=No(a);o!==void 0&&i!==void 0&&t.set(i,o)}return t}n(Jc,"buildListRulesByResponseId");function Gc(e){if(Array.isArray(e.responseBody)){let o=Jc(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(a=>{if(!N(a)||"error"in a)return a;let i=No(Or(a)),c=i===void 0?void 0:o.get(i),s=c===void 0?void 0:e.projectionMaps[c.option];return c===void 0||s===void 0?a:Bo(a,c,s)})}if(!N(e.requestBody)||!N(e.responseBody)||"error"in e.responseBody)return e.responseBody;let t=qr(e.requestBody.method),r=t===void 0?void 0:e.projectionMaps[t.option];return t===void 0||r===void 0?e.responseBody:Bo(e.responseBody,t,r)}n(Gc,"filterJsonRpcResponse");async function Lo(e){return e.clone().json()}n(Lo,"readJson");function Fc(e){return e.headers.get("content-type")?.includes("json")??!1}n(Fc,"isJsonResponse");var Pr=class extends Mt{static{n(this,"McpCapabilityFilterInboundPolicy")}#e;constructor(t,r){let o=Mc(t,r);super(o,r),this.#e=zc(o)}async handler(t,r){G("policy.inbound.mcp-capability-filter");let o;try{o=await Lo(t)}catch{return t}let a=Array.isArray(o)?o:[o];for(let i of a){if(!N(i))continue;let c=jc({request:i,projectionMaps:this.#e});if(c!==void 0)return Bc(c.id)}return Hc({requests:a,projectionMaps:this.#e})&&r.addResponseSendingHook(async i=>{if(!Fc(i))return i;let c;try{c=await Lo(i)}catch{return i}let s=Gc({requestBody:o,responseBody:c,projectionMaps:this.#e});if(s===c)return i;let u=new Headers(i.headers);return u.delete("content-length"),new Response(JSON.stringify(s),{status:i.status,statusText:i.statusText,headers:u})}),t}};var Mr;Mr=globalThis.crypto;async function $c(e){return(await Mr).getRandomValues(new Uint8Array(e))}n($c,"getRandomValues");async function Zc(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let a=await $c(e-o.length);for(let i of a)i<r&&(o+=t[i%t.length])}return o}n(Zc,"random");async function Kc(e){return await Zc(e)}n(Kc,"generateVerifier");async function Wc(e){let t=await(await Mr).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(Wc,"generateChallenge");async function Dr(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Kc(e),r=await Wc(t);return{code_verifier:t,code_challenge:r}}n(Dr,"pkceChallenge");F();var D=Ln().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Gn.custom,message:"URL must be parseable",fatal:!0}),Bn}).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"}),Yt=Dt({resource:l().url(),authorization_servers:_(D).optional(),jwks_uri:l().url().optional(),scopes_supported:_(l()).optional(),bearer_methods_supported:_(l()).optional(),resource_signing_alg_values_supported:_(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:ie().optional(),authorization_details_types_supported:_(l()).optional(),dpop_signing_alg_values_supported:_(l()).optional(),dpop_bound_access_tokens_required:ie().optional()}),lt=Dt({issuer:l(),authorization_endpoint:D,token_endpoint:D,registration_endpoint:D.optional(),scopes_supported:_(l()).optional(),response_types_supported:_(l()),response_modes_supported:_(l()).optional(),grant_types_supported:_(l()).optional(),token_endpoint_auth_methods_supported:_(l()).optional(),token_endpoint_auth_signing_alg_values_supported:_(l()).optional(),service_documentation:D.optional(),revocation_endpoint:D.optional(),revocation_endpoint_auth_methods_supported:_(l()).optional(),revocation_endpoint_auth_signing_alg_values_supported:_(l()).optional(),introspection_endpoint:l().optional(),introspection_endpoint_auth_methods_supported:_(l()).optional(),introspection_endpoint_auth_signing_alg_values_supported:_(l()).optional(),code_challenge_methods_supported:_(l()).optional(),client_id_metadata_document_supported:ie().optional()}),Vc=Dt({issuer:l(),authorization_endpoint:D,token_endpoint:D,userinfo_endpoint:D.optional(),jwks_uri:D,registration_endpoint:D.optional(),scopes_supported:_(l()).optional(),response_types_supported:_(l()),response_modes_supported:_(l()).optional(),grant_types_supported:_(l()).optional(),acr_values_supported:_(l()).optional(),subject_types_supported:_(l()),id_token_signing_alg_values_supported:_(l()),id_token_encryption_alg_values_supported:_(l()).optional(),id_token_encryption_enc_values_supported:_(l()).optional(),userinfo_signing_alg_values_supported:_(l()).optional(),userinfo_encryption_alg_values_supported:_(l()).optional(),userinfo_encryption_enc_values_supported:_(l()).optional(),request_object_signing_alg_values_supported:_(l()).optional(),request_object_encryption_alg_values_supported:_(l()).optional(),request_object_encryption_enc_values_supported:_(l()).optional(),token_endpoint_auth_methods_supported:_(l()).optional(),token_endpoint_auth_signing_alg_values_supported:_(l()).optional(),display_values_supported:_(l()).optional(),claim_types_supported:_(l()).optional(),claims_supported:_(l()).optional(),service_documentation:l().optional(),claims_locales_supported:_(l()).optional(),ui_locales_supported:_(l()).optional(),claims_parameter_supported:ie().optional(),request_parameter_supported:ie().optional(),request_uri_parameter_supported:ie().optional(),require_request_uri_registration:ie().optional(),op_policy_uri:D.optional(),op_tos_uri:D.optional(),client_id_metadata_document_supported:ie().optional()}),Xt=ye({...Vc.shape,...lt.pick({code_challenge_methods_supported:!0}).shape}),Fe=ye({access_token:l(),id_token:l().optional(),token_type:l(),expires_in:Fn.number().optional(),scope:l().optional(),refresh_token:l().optional()}).strip(),Go=ye({error:l(),error_description:l().optional(),error_uri:l().optional()}),Jo=D.optional().or(Jn("").transform(()=>{})),Yc=ye({redirect_uris:_(D),token_endpoint_auth_method:l().optional(),grant_types:_(l()).optional(),response_types:_(l()).optional(),client_name:l().optional(),client_uri:D.optional(),logo_uri:Jo,scope:l().optional(),contacts:_(l()).optional(),tos_uri:Jo,policy_uri:l().optional(),jwks_uri:D.optional(),jwks:Nn().optional(),software_id:l().optional(),software_version:l().optional(),software_statement:l().optional()}).strip(),Qt=ye({client_id:l(),client_secret:l().optional(),client_id_issued_at:Rr().optional(),client_secret_expires_at:Rr().optional()}).strip(),pt=Yc.merge(Qt),Jh=ye({error:l(),error_description:l().optional()}).strip(),Gh=ye({token:l(),token_type_hint:l().optional()}).strip();function Fo(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(Fo,"resourceUrlFromServerUrl");function $o({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 a=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return a.startsWith(i)}n($o,"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}},mt=class extends A{static{n(this,"InvalidRequestError")}};mt.errorCode="invalid_request";var Ue=class extends A{static{n(this,"InvalidClientError")}};Ue.errorCode="invalid_client";var Pe=class extends A{static{n(this,"InvalidGrantError")}};Pe.errorCode="invalid_grant";var Ee=class extends A{static{n(this,"UnauthorizedClientError")}};Ee.errorCode="unauthorized_client";var ft=class extends A{static{n(this,"UnsupportedGrantTypeError")}};ft.errorCode="unsupported_grant_type";var ht=class extends A{static{n(this,"InvalidScopeError")}};ht.errorCode="invalid_scope";var gt=class extends A{static{n(this,"AccessDeniedError")}};gt.errorCode="access_denied";var pe=class extends A{static{n(this,"ServerError")}};pe.errorCode="server_error";var yt=class extends A{static{n(this,"TemporarilyUnavailableError")}};yt.errorCode="temporarily_unavailable";var _t=class extends A{static{n(this,"UnsupportedResponseTypeError")}};_t.errorCode="unsupported_response_type";var wt=class extends A{static{n(this,"UnsupportedTokenTypeError")}};wt.errorCode="unsupported_token_type";var Rt=class extends A{static{n(this,"InvalidTokenError")}};Rt.errorCode="invalid_token";var bt=class extends A{static{n(this,"MethodNotAllowedError")}};bt.errorCode="method_not_allowed";var It=class extends A{static{n(this,"TooManyRequestsError")}};It.errorCode="too_many_requests";var Oe=class extends A{static{n(this,"InvalidClientMetadataError")}};Oe.errorCode="invalid_client_metadata";var Ct=class extends A{static{n(this,"InsufficientScopeError")}};Ct.errorCode="insufficient_scope";var St=class extends A{static{n(this,"InvalidTargetError")}};St.errorCode="invalid_target";var Zo={[mt.errorCode]:mt,[Ue.errorCode]:Ue,[Pe.errorCode]:Pe,[Ee.errorCode]:Ee,[ft.errorCode]:ft,[ht.errorCode]:ht,[gt.errorCode]:gt,[pe.errorCode]:pe,[yt.errorCode]:yt,[_t.errorCode]:_t,[wt.errorCode]:wt,[Rt.errorCode]:Rt,[bt.errorCode]:bt,[It.errorCode]:It,[Oe.errorCode]:Oe,[Ct.errorCode]:Ct,[St.errorCode]:St};function Xc(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(Xc,"isClientAuthMethod");var zr="code",Hr="S256";function Qc(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Xc(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(Qc,"selectClientAuthMethod");function ed(e,t,r,o){let{client_id:a,client_secret:i}=t;switch(e){case"client_secret_basic":td(a,i,r);return;case"client_secret_post":rd(a,i,o);return;case"none":nd(a,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(ed,"applyClientAuthentication");function td(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(td,"applyBasicAuth");function rd(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(rd,"applyPostAuth");function nd(e,t){t.set("client_id",e)}n(nd,"applyPublicAuth");async function Wo(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Go.parse(JSON.parse(r)),{error:a,error_description:i,error_uri:c}=o,s=Zo[a]||pe;return new s(i||"",c)}catch(o){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new pe(a)}}n(Wo,"parseErrorResponse");async function Lr(e,t){try{return await jr(e,t)}catch(r){if(r instanceof Ue||r instanceof Ee)return await e.invalidateCredentials?.("all"),await jr(e,t);if(r instanceof Pe)return await e.invalidateCredentials?.("tokens"),await jr(e,t);throw r}}n(Lr,"auth");async function jr(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:a,fetchFn:i}){let c=await e.discoveryState?.(),s,u,p,h=a;if(!h&&c?.resourceMetadataUrl&&(h=new URL(c.resourceMetadataUrl)),c?.authorizationServerUrl){if(u=c.authorizationServerUrl,s=c.resourceMetadata,p=c.authorizationServerMetadata??await Xo(u,{fetchFn:i}),!s)try{s=await Yo(t,{resourceMetadataUrl:h},i)}catch{}(p!==c.authorizationServerMetadata||s!==c.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:h?.toString(),resourceMetadata:s,authorizationServerMetadata:p})}else{let M=await dd(t,{resourceMetadataUrl:h,fetchFn:i});u=M.authorizationServerUrl,p=M.authorizationServerMetadata,s=M.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:h?.toString(),resourceMetadata:s,authorizationServerMetadata:p})}let y=await od(t,e,s),U=o||s?.scopes_supported?.join(" ")||e.clientMetadata.scope,R=await Promise.resolve(e.clientInformation());if(!R){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let M=p?.client_id_metadata_document_supported===!0,z=e.clientMetadataUrl;if(z&&!Nr(z))throw new Oe(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${z}`);if(M&&z)R={client_id:z},await e.saveClientInformation?.(R);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Mn=await fd(u,{metadata:p,clientMetadata:e.clientMetadata,scope:U,fetchFn:i});await e.saveClientInformation(Mn),R=Mn}}let q=!e.redirectUrl;if(r!==void 0||q){let M=await md(e,u,{metadata:p,resource:y,authorizationCode:r,fetchFn:i});return await e.saveTokens(M),"AUTHORIZED"}let O=await e.tokens();if(O?.refresh_token)try{let M=await pd(u,{metadata:p,clientInformation:R,refreshToken:O.refresh_token,resource:y,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(M),"AUTHORIZED"}catch(M){if(!(!(M instanceof A)||M instanceof pe))throw M}let oe=e.state?await e.state():void 0,{authorizationUrl:ot,codeVerifier:ae}=await ud(u,{metadata:p,clientInformation:R,state:oe,redirectUrl:e.redirectUrl,scope:U,resource:y});return await e.saveCodeVerifier(ae),await e.redirectToAuthorization(ot),"REDIRECT"}n(jr,"authInternal");function Nr(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(Nr,"isHttpsUrl");async function od(e,t,r){let o=Fo(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!$o({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(od,"selectResourceURL");function Vo(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let a=Br(e,"resource_metadata")||void 0,i;if(a)try{i=new URL(a)}catch{}let c=Br(e,"scope")||void 0,s=Br(e,"error")||void 0;return{resourceMetadataUrl:i,scope:c,error:s}}n(Vo,"extractWWWAuthenticateParams");function Br(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),a=r.match(o);return a?a[1]||a[2]:null}n(Br,"extractFieldFromWwwAuth");async function Yo(e,t,r=fetch){let o=await sd(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 Yt.parse(await o.json())}n(Yo,"discoverOAuthProtectedResourceMetadata");async function Jr(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Jr(e,void 0,r):void 0;throw o}}n(Jr,"fetchWithCorsRetry");function ad(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(ad,"buildWellKnownPath");async function Ko(e,t,r=fetch){return await Jr(e,{"MCP-Protocol-Version":t},r)}n(Ko,"tryMetadataDiscovery");function id(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(id,"shouldAttemptFallback");async function sd(e,t,r,o){let a=new URL(e),i=o?.protocolVersion??br,c;if(o?.metadataUrl)c=new URL(o.metadataUrl);else{let u=ad(t,a.pathname);c=new URL(u,o?.metadataServerUrl??a),c.search=a.search}let s=await Ko(c,i,r);if(!o?.metadataUrl&&id(s,a.pathname)){let u=new URL(`/.well-known/${t}`,a);s=await Ko(u,i,r)}return s}n(sd,"discoverMetadataWithFallback");function cd(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 a=t.pathname;return a.endsWith("/")&&(a=a.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:"oidc"}),o.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(cd,"buildDiscoveryUrls");async function Xo(e,{fetchFn:t=fetch,protocolVersion:r=br}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},a=cd(e);for(let{url:i,type:c}of a){let s=await Jr(i,o,t);if(s){if(!s.ok){if(await s.body?.cancel(),s.status>=400&&s.status<500)continue;throw new Error(`HTTP ${s.status} trying to load ${c==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return c==="oauth"?lt.parse(await s.json()):Xt.parse(await s.json())}}}n(Xo,"discoverAuthorizationServerMetadata");async function dd(e,t){let r,o;try{r=await Yo(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 a=await Xo(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:a,resourceMetadata:r}}n(dd,"discoverOAuthServerInfo");async function ud(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:a,state:i,resource:c}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(zr))throw new Error(`Incompatible auth server: does not support response type ${zr}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Hr))throw new Error(`Incompatible auth server: does not support code challenge method ${Hr}`)}else s=new URL("/authorize",e);let u=await Dr(),p=u.code_verifier,h=u.code_challenge;return s.searchParams.set("response_type",zr),s.searchParams.set("client_id",r.client_id),s.searchParams.set("code_challenge",h),s.searchParams.set("code_challenge_method",Hr),s.searchParams.set("redirect_uri",String(o)),i&&s.searchParams.set("state",i),a&&s.searchParams.set("scope",a),a?.includes("offline_access")&&s.searchParams.append("prompt","consent"),c&&s.searchParams.set("resource",c.href),{authorizationUrl:s,codeVerifier:p}}n(ud,"startAuthorization");function ld(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(ld,"prepareAuthorizationCodeRequest");async function Qo(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:a,resource:i,fetchFn:c}){let s=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(i&&r.set("resource",i.href),a)await a(u,r,s,t);else if(o){let h=t?.token_endpoint_auth_methods_supported??[],y=Qc(o,h);ed(y,o,u,r)}let p=await(c??fetch)(s,{method:"POST",headers:u,body:r});if(!p.ok)throw await Wo(p);return Fe.parse(await p.json())}n(Qo,"executeTokenRequest");async function pd(e,{metadata:t,clientInformation:r,refreshToken:o,resource:a,addClientAuthentication:i,fetchFn:c}){let s=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),u=await Qo(e,{metadata:t,tokenRequestParams:s,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:c});return{refresh_token:o,...u}}n(pd,"refreshAuthorization");async function md(e,t,{metadata:r,resource:o,authorizationCode:a,fetchFn:i}={}){let c=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(c)),!s){if(!a)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();s=ld(a,p,e.redirectUrl)}let u=await e.clientInformation();return Qo(t,{metadata:r,tokenRequestParams:s,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:i})}n(md,"fetchToken");async function fd(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:a}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let c=await(a??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!c.ok)throw await Wo(c);return pt.parse(await c.json())}n(fd,"registerClient");var Gr="zuplo.com",hd=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),gd=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function ea(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(ea,"s2FaviconHref");function yd(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(yd,"strictFaviconHref");var er=ea(Gr);function Fr(e){let t=e.toLowerCase();return t===Gr||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?ea(Gr):yd(e)}n(Fr,"resolveIconHref");function _d(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(_d,"hostnameFromHost");function wd(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(wd,"isLocalOrAddressHost");function Rd(e){let t=_d(e).toLowerCase().replace(/\.$/,"");if(wd(t)||gd.some(i=>t===i.slice(1)||t.endsWith(i)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let o=r.slice(-2).join("."),a=hd.has(o)?3:2;return r.slice(-a).join(".")}n(Rd,"inferFaviconDomain");function $r(e){return{src:Fr(Rd(e)),mimeType:"image/png",sizes:["128x128"]}}n($r,"resolveMcpFaviconIcon");function tr(e){try{return $r(new URL(e).host)}catch{return}}n(tr,"resolveMcpFaviconIconFromUrl");function Ie(e){let t=X().connectionsById.get(e);if(!t)throw new j(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,description:t.description,serverInfo:t.serverInfo,transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}n(Ie,"getUpstreamServerConfig");function rr(e){let t=X().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new j(`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.authConfig}n(rr,"getUpstreamAuthConfig");function $e(e,t){let r=rr({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new j(`Upstream server "${e}" does not use upstream OAuth. Select authMode "shared-oauth" or "user-oauth" before starting an upstream OAuth connection flow.`);return r.oauth}n($e,"requireUpstreamOAuthConfig");function ta(e,t){let r=rr({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new j(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(ta,"requireUpstreamIdJagConfig");function ra(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(ra,"mergeAbortSignals");async function bd(e){try{await e.cancel()}catch{}}n(bd,"cancelReader");async function nr(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],a=0,i=await r.read();for(;!i.done;){let u=i.value;if(a+=u.byteLength,a>t.maxBytes)throw await bd(r),t.createLimitError();o.push(u),i=await r.read()}let c=new Uint8Array(a),s=0;for(let u of o)c.set(u,s),s+=u.byteLength;return c}n(nr,"readBoundedByteStream");var Id=2,Cd=1024*1024,Sd=1e4,vd=new Set([301,302,303,307,308]),Ad=["authorization","proxy-authorization","cookie","cookie2"];function Zr(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Zr,"readRequestUrl");function Ze(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(Ze,"readRequestMethod");function xd(e,t,r){let o=e.headers.get("content-length");if(!o)return;let a=Number.parseInt(o,10);if(Number.isFinite(a)&&a>t)throw new f({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}})}n(xd,"assertContentLengthWithinLimit");async function kd(e,t,r){return xd(e,t,r),nr(e.body,{maxBytes:t,createLimitError:n(()=>new f({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}}),"createLimitError")})}n(kd,"readBoundedResponseBody");function Td(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(Td,"responseFromBufferedBody");function Ud(e,t){if(!vd.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(Ud,"resolveRedirectUrl");function na(e,t){try{return t.validateUrl(e)}catch(r){throw new f({message:"Outbound URL was not allowed.",extensionMembers:{[g]:t.problemCode}},{cause:r})}}n(na,"validateOutboundUrl");function Pd(e,t){throw e instanceof f&&zt(e.extensionMembers?.[g])?e:new f({message:"Outbound fetch failed.",extensionMembers:{[g]:t}},{cause:e})}n(Pd,"normalizeFetchError");function vt(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,a]of Object.entries(t.extra))a!==void 0&&(r[o]=a);t.error!==void 0&&L(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(vt,"logOutboundFailure");async function Ed(e,t,r,o,a,i,c){let s=Ze(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";vt(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:s,host:T(i),error:u,extra:{abortReason:c()}}),Pd(u,a)}}n(Ed,"fetchWithNormalizedError");function Od(e){if(e.redirects>=e.maxRedirects)throw new f({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[g]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new f({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[g]:e.problemCode}})}n(Od,"assertRedirectAllowed");function qd(e,t){let r=new Headers(e);for(let o of Ad)r.delete(o);for(let o of t)r.delete(o);return r}n(qd,"stripCrossOriginHeaders");function Md(e,t,r,o,a){let i={...e,method:t,redirect:"manual",signal:r};return o&&(i.headers=qd(e.headers,a)),i}n(Md,"buildRedirectInit");function Dd(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(Dd,"buildInitialRequestInit");function zd(e){let t=Ze(e.currentInput,e.currentInit);Od({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=na(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),a=r.origin!==o.origin,i=r.toString();return{currentInput:i,currentUrl:i,currentInit:Md(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(zd,"followRedirect");async function Kr(e,t,r){let o=r.problemCode??"invalid_request",a=r.maxRedirects??Id,i=r.maxResponseBytes??Cd,c=r.timeoutMs??Sd,s=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,h=new AbortController,y=ra(h,t.signal),U=!1,R=setTimeout(()=>{U=!0,h.abort()},c),q=e,O=Dd(e,t,h.signal),oe;try{oe=na(Zr(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(ae){throw vt(p,{event:"outbound_url_blocked",problemCode:o,method:Ze(e,t),host:T(Zr(e)),error:ae}),clearTimeout(R),y?.(),ae}let ot=0;try{for(;;){let ae=await Ed(p,s,q,O,o,oe,()=>U?`timeout_after_${c}ms`:void 0),M=Ud(ae,oe);if(M!==void 0)try{let z=zd({currentInput:q,currentInit:O,currentUrl:oe,redirectUrl:M,redirects:ot,maxRedirects:a,problemCode:o,validateUrl:r.validateUrl,signal:h.signal,additionalCrossOriginStrippedHeaders:u});q=z.currentInput,O=z.currentInit,oe=z.currentUrl,ot=z.redirects;continue}catch(z){throw vt(p,{event:"outbound_redirect_blocked",problemCode:o,method:Ze(q,O),host:T(oe),error:z,extra:{redirects:ot,maxRedirects:a,redirectTargetHost:T(M)}}),z}try{return Td(ae,await kd(ae,i,o))}catch(z){throw vt(p,{event:"outbound_response_size_exceeded",problemCode:o,method:Ze(q,O),host:T(oe),error:z,extra:{maxResponseBytes:i,status:ae.status}}),z}}}finally{clearTimeout(R),y?.()}}n(Kr,"runSafeOutboundExchange");async function At(e,t,r){let o=await Kr(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(a){throw vt(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Ze(e,t),host:T(Zr(e)),error:a,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new f({message:"Outbound JSON response could not be parsed.",extensionMembers:{[g]:r.problemCode??"invalid_request"}},{cause:a})}}n(At,"runSafeOutboundJsonExchange");function oa(e,t={},r={}){return Kr(e,t,{...r,validateUrl:dt})}n(oa,"fetchConfiguredOutbound");function aa(e,t={},r={}){return At(e,t,{...r,validateUrl:dt})}n(aa,"fetchConfiguredOutboundJson");function or(e,t={},r={}){return At(e,t,{...r,validateUrl:xo})}n(or,"fetchIdentityProviderJson");function ia(e,t={},r={}){return At(e,t,{...r,validateUrl:$t})}n(ia,"fetchCimdClientMetadataJson");function sa(e,t={},r={}){return At(e,t,{...r,validateUrl:ut})}n(sa,"fetchCimdClientJwksJson");F();import{errors as ma,jwtVerify as fa,SignJWT as ha}from"jose";var J="zuplo-mcp-gateway",K=J,W="HS256";import{base64url as Hd}from"jose";var jd=new TextEncoder,Bd="MCP gateway could not initialize secure key material.",Ld=32,ca=new Map,da=new Map,Nd;function Jd(){return Nd??Dn.instance.authPrivateKey}n(Jd,"readAuthPrivateKey");function ua(e){return new Y(Bd,e===void 0?void 0:{cause:e})}n(ua,"createGeneratedKeyMaterialError");function la(e,t){let r=Hd.decode(t);if(r.byteLength!==Ld)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(la,"decodeJwkKeyField");function Gd(e){let t=Jd();if(!t)throw ua();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=la("d",r.d);la("x",r.x);let a=jd.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),i=new Uint8Array(a.byteLength+o.byteLength);return i.set(a),i.set(o,a.byteLength),i}catch(r){throw ua(r)}}n(Gd,"decodeGeneratedKeyMaterial");function Fd(e){let t=ca.get(e);return t||(t=Gd(e),ca.set(e,t)),t}n(Fd,"getMasterKeyMaterial");async function re(e){let t=da.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Fd(e.keyMaterialPurpose));return da.set(e.purpose,r),r}n(re,"readCachedDerivedKey");var $d="SHA-256",Zd=32,Kd="zuplo-mcp-gateway:",Wd=new TextEncoder,pa=new WeakMap;async function Ce(e,t){let r=pa.get(e);r||(r=new Map,pa.set(e,r));let o=r.get(t);if(o)return o;let a=await Vd(e,t);return r.set(t,a),a}n(Ce,"deriveGatewaySigningKey");async function Vd(e,t){let r=Z(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=Wd.encode(`${Kd}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:$d,salt:new Uint8Array,info:Z(a)},o,Zd*8);return new Uint8Array(i)}n(Vd,"hkdfExpand");var ga=900,Yd=900,Xd=co.extend({id:Eo}),Qd=Xd.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ya=Ir.extend({id:Oo,purpose:d.literal("browser_connect")}),eu=Ir.extend({purpose:d.literal("browser_connect")}),tu=ya.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),_a=ga*1e3;async function wa(){return re({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ce(e,"oauth-state"),"derive")})}n(wa,"getOAuthStateKey");async function Ra(){return re({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ce(e,"browser-connect"),"derive")})}n(Ra,"getBrowserConnectKey");async function ba(e){let t=Math.floor(Date.now()/1e3)+ga;return new ha(e).setProtectedHeader({alg:W,typ:"JWT"}).setIssuer(J).setAudience(K).setIssuedAt().setExpirationTime(t).sign(await wa())}n(ba,"signOAuthState");async function ar(e){try{let{payload:t}=await fa(e,await wa(),{algorithms:[W],issuer:J,audience:K});return Qd.parse(t)}catch(t){throw t instanceof ma.JWTExpired?new f({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new f({message:"OAuth state could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(ar,"verifyOAuthState");async function Ia(e){let t=Math.floor(Date.now()/1e3)+Yd,r=eu.parse(e),o=ya.parse({...r,id:Do()});return new ha(o).setProtectedHeader({alg:W,typ:"JWT"}).setIssuer(J).setAudience(K).setIssuedAt().setExpirationTime(t).sign(await Ra())}n(Ia,"signBrowserConnectTicket");async function Ca(e){try{let{payload:t}=await fa(e,await Ra(),{algorithms:[W],issuer:J,audience:K});return tu.parse(t)}catch(t){throw t instanceof ma.JWTExpired?new f({message:"Browser connect ticket has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new f({message:"Browser connect ticket could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(Ca,"verifyBrowserConnectTicket");async function Sa(e){if((await b().consumeBrowserConnectTicket({id:e.id,expiresAt:I(new Date(e.exp*1e3)),now:I(new Date)})).kind==="consumed")throw new f({message:"Browser connect ticket has already been used",extensionMembers:{[g]:"oauth_state_reused"}})}n(Sa,"consumeBrowserConnectTicket");function ru(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(ru,"buildConnectRequiredMessage");async function nu(e){let t=P(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 Ia({...st(e),purpose:"browser_connect"})),r.toString()}n(nu,"buildGatewayBrowserTicketUrl");function ou(e){return H().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(ou,"buildGatewayConnectPath");async function Wr(e){return nu({...e,path:ou(e.upstreamServerId),redirect:!0})}n(Wr,"buildGatewayConnectUrl");async function ir(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 Wr(t),message:ru(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(ir,"buildRedirectConnectRequiredResponse");function va(e){return au({...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(va,"buildAdminConnectRequiredResponse");function au(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(au,"buildAdminSetupRequiredResponse");F();var Aa=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function iu(e,t){return e&&e.length>0?e.join(t):void 0}n(iu,"joinOAuthScopes");function su(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of Aa)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(su,"sanitizeAuthorizationServerMetadata");function xa(e){let t=su(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(xa,"sanitizeOAuthDiscoveryState");function ka(e){let t=new URL(e);for(let r of Aa){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(ka,"dedupeSingletonAuthorizationRequestParams");function sr(e){let t=new URL(e);return $(t)&&Zn(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(sr,"normalizeLoopbackOAuthRedirectUri");function Ta(e){return iu(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(Ta,"readProtectedResourceMetadataScope");function cu(e){return`Zuplo MCP Gateway - ${e}`}n(cu,"buildGatewayOAuthClientName");function du(e,t){return e&&e.length>0?e.join(t):void 0}n(du,"joinOAuthScopeList");function uu(e){if(e.clientRegistration.mode!=="auto")return du(e.scopes,e.scopeDelimiter)}n(uu,"readPublicClientMetadataScope");function Vr(e){return new URL(H().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Vr,"buildOAuthClientMetadataDocumentUrl");function Yr(e){let t=Ie(e.upstreamServerId);return{client_name:cu(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(Yr,"buildGatewayOAuthClientMetadata");function Ua(e,t,r){let o=$e(t,r),a=uu(o);return{client_id:Vr({origin:e,upstreamServerId:t}),...Yr({origin:e,upstreamServerId:t,redirectUri:sr(new URL(o.redirectPath,e)).toString(),scope:a})}}n(Ua,"buildOAuthClientMetadataDocument");F();import{base64url as Se}from"jose";var lu="SHA-256",Ke="AES-GCM",pu=12,Qr="zuplo-secret",en=1,Pa="generated:auth_private_key:token-encryption",mu=d.object({version:d.literal(en),keyId:d.literal(Pa),algorithm:d.literal(Ke),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();async function Xr(){return re({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(lu,Z(e));return crypto.subtle.importKey("raw",t,{name:Ke},!1,["encrypt","decrypt"])},"derive")})}n(Xr,"getEncryptionKey");function Ea(e){return Z(new TextEncoder().encode(`${Qr}:v${e.version}:${e.keyId}`))}n(Ea,"getAssociatedData");function fu(e){return`${Qr}:v${e.version}:${Se.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(fu,"encodeEnvelope");function hu(e){let t=`${Qr}:v${en}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(Se.decode(r));return mu.parse(JSON.parse(o))}n(hu,"decodeEnvelope");async function me(e){let t=await Xr(),r=crypto.getRandomValues(new Uint8Array(pu)),o={version:en,keyId:Pa},a=await crypto.subtle.encrypt({name:Ke,iv:r,additionalData:Ea(o)},t,new TextEncoder().encode(e));return fu({...o,algorithm:Ke,iv:Se.encode(r),ciphertext:Se.encode(new Uint8Array(a))})}n(me,"encryptSecret");async function ve(e){let t=hu(e);if(t){let c=await Xr(),s=await crypto.subtle.decrypt({name:Ke,iv:Z(Se.decode(t.iv)),additionalData:Ea(t)},c,Z(Se.decode(t.ciphertext)));return new TextDecoder().decode(s)}let[r,o]=e.split(".");if(!r||!o)throw new Y("Encrypted payload is malformed");let a=await Xr(),i=await crypto.subtle.decrypt({name:Ke,iv:Z(Se.decode(r))},a,Z(Se.decode(o)));return new TextDecoder().decode(i)}n(ve,"decryptSecret");var gu=d.union([pt,Qt]),yu=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:Yt.optional(),authorizationServerMetadata:d.union([lt,Xt]).optional()}).passthrough(),_u="Bearer",wu="__zuplo_refresh_only_upstream_access_token__";function Ru(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Ru,"splitScopes");function bu(e){return je.parse(e)}n(bu,"parsePkceCodeVerifier");function Iu(e){if(typeof e.expires_in=="number")return I(new Date(Date.now()+e.expires_in*1e3))}n(Iu,"readTokenExpiry");async function Cu(e){if(e!==void 0)return me(JSON.stringify(e))}n(Cu,"encryptJson");async function Su(e,t){if(!e)return;let r=await ve(e);try{return t.parse(JSON.parse(r))}catch(o){throw new f({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:o})}}n(Su,"decryptJson");function vu(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(vu,"clientInformationAllowsRedirectUri");function Au(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(Au,"clientInformationMatchesCurrentClientMetadataUrl");function xu(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(xu,"isUrlBasedClientInformation");function ku(e,t){return t===void 0?e:{...e,scope:t}}n(ku,"applyOAuthClientMetadataScope");function Tu(e,t){return Ta({state:e,delimiter:t})}n(Tu,"readResourceMetadataScope");function Uu(e,t){return e&&e.length>0?e.join(t):void 0}n(Uu,"joinOAuthScopeList");function Pu(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new j(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return pt.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(Pu,"buildManualOAuthClientInformation");function Eu(e,t){let r=Vr({origin:new URL(t).origin,upstreamServerId:e});return Nr(r)?r:void 0}n(Eu,"buildClientMetadataUrl");function Ou(e){for(let t of e)if(t!==void 0)return t}n(Ou,"firstDefined");function qu(e){let t=$e(e.target.upstreamServerId,e.target.authProfileId),r=Uu(t.scopes,t.scopeDelimiter),o=Yr({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:Pu({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let a=Eu(e.target.upstreamServerId,e.redirectUri);return a===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,clientMetadataUrl:a}}n(qu,"buildInitialOAuthClientSetup");function Mu(e,t){if(t===void 0)return Ou([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(Mu,"readEncryptedClientInformation");var qe=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredScope;scopeDelimiter;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;connection;pendingState;encryptedClientInformation;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;constructor(t){let r=qu({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=Mu(t,this.configuredClientInformation)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return ku(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return ba({id:t.id,...st({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,de()?.info({event:"upstream_oauth_client_registered",upstreamServerId:this.target.upstreamServerId,clientId:"client_id"in t?t.client_id:void 0,redirectUriCount:"redirect_uris"in t?t.redirect_uris.length:void 0},"Upstream OAuth client registered for the gateway"),!xu({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Cu(t),await this.syncPendingState(!1)))}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=xa(yu.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,de()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:T(r.authorizationServerUrl),resourceMetadataHost:T(r.resourceMetadataUrl),resource:r.resourceMetadata?.resource,scopesSupportedCount:r.resourceMetadata?.scopes_supported?.length,hasResourceMetadata:r.resourceMetadata!==void 0},"Upstream OAuth discovery resolved authorization server and resource"),this.inferredScope=Tu(r,this.scopeDelimiter)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Fe.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,a=r.refresh_token?await me(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:Fe.parse({...r,refresh_token:await ve(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let i={id:this.connection?.id??Zt(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await me(r.access_token),encryptedRefreshToken:a,scopes:Ru(r.scope??this.readEffectiveScope()),expiresAt:Iu(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await b().upsertUpstreamConnection(i),de()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionId:this.connection.id,hasRefreshToken:!!a,scopeCount:i.scopes.length,expiresAt:i.expiresAt},"Upstream OAuth tokens persisted; upstream connection is active")}async redirectToAuthorization(t){let r=ka(t);this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:bu(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new f({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",a=t==="all"||t==="discovery",i=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),a&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.challengeScope=void 0,this.inferredScope=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(i),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:Mo(),...st({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:I(new Date(Date.now()+_a)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,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})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await Su(this.encryptedClientInformation,gu)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&(!vu(t,this.redirectUriValue)||!Au({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=Qt.parse({client_id:this.clientMetadataUrl})),this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async readCachedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;this.discoveryStateLoaded=!0}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 ve(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await ve(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=Fe.parse({access_token:t??wu,token_type:_u,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&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var Du=3e4,zu=256*1024,Hu=2;function ju(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(ju,"hasUsableAccessToken");var Bu="does not support dynamic client registration",Lu=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],Nu=["HTTP 403 Forbidden","Access Denied","permission to access"],Ju=new Set(["access_denied","invalid_client","invalid_grant","invalid_request","invalid_scope","invalid_target","unauthorized_client","unsupported_grant_type"]);function Gu(e){return e instanceof Error&&e.message.includes(Bu)}n(Gu,"isDynamicClientRegistrationUnsupported");function Fu(e){return e instanceof Error&&Lu.some(t=>e.message.includes(t))}n(Fu,"isProtectedResourceMetadataUnavailable");function $u(e){return e instanceof Error&&Nu.some(t=>e.message.includes(t))}n($u,"isUpstreamProviderAccessDenied");function Zu(e){return e instanceof A&&Ju.has(e.errorCode)}n(Zu,"isStoredConnectionReconsentError");function Ku(e){if(e.error instanceof f&&e.error.extensionMembers?.[g]!==void 0)return e.error;if(Gu(e.error))return new f({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(Fu(e.error))return new f({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($u(e.error))return new f({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(Ku,"mapUpstreamOAuthSetupError");function Wu(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(Wu,"readOAuthFetchRequest");function Vu(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(Vu,"responseLooksJson");function Yu(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(Yu,"responseLooksHtml");function Xu(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new f({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",[_e]:e.response.status,[Be]:r,[we]:e.request.url.toString(),[Le]:e.body}})}n(Xu,"throwUpstreamHtmlError");function Qu(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return{};let r=t;return{error:typeof r.error=="string"?r.error:void 0,errorDescription:typeof r.error_description=="string"?r.error_description:void 0}}catch{return{}}}n(Qu,"readUpstreamOAuthErrorBody");function el(e){let{error:t,errorDescription:r}=Qu(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.request.method??"GET",host:T(e.request.url),path:e.request.url.pathname,status:e.response.status,oauthError:t,oauthErrorDescription:r?.slice(0,256)},"Upstream OAuth HTTP request returned an error response")}n(el,"logUpstreamOAuthHttpError");function qa(e){return async(t,r)=>{let o=Wu(t),a=de(),i=Date.now(),c=await oa(t,r,{maxRedirects:Hu,maxResponseBytes:zu,problemCode:"upstream_token_exchange_failed",timeoutMs:Du}),s=await c.clone().text();if(a?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:o.method??"GET",host:T(o.url),path:o.url.pathname,status:c.status,durationMs:Date.now()-i,responseChars:s.length},"Upstream OAuth HTTP request completed"),c.ok||el({log:a,upstreamServerId:e,request:o,response:c,body:s}),!c.ok&&Yu(c,s)&&Xu({upstreamServerId:e,request:o,response:c,body:s}),!Vu(c,s))return c;try{JSON.parse(s)}catch(u){throw new f({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[g]:"upstream_token_exchange_failed"}},{cause:u})}return c}}n(qa,"createUpstreamOAuthFetch");function Ma(e){de()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:T(e.serverUrl),resourceMetadataHost:T(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}n(Ma,"logUpstreamOAuthFlowStarted");function Da(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=T(e.serverUrl);r!==void 0&&(t.serverHost=r);let o=e.error instanceof f?e.error.extensionMembers?.[g]:void 0;typeof o=="string"&&(t.code=o),L(t,"error",e.error),de()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(Da,"logUpstreamOAuthFlowFailed");async function za(e,t){e.applyChallengeScope(t.requestedScope),Ma({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:qa(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),await Lr(e,r)}catch(r){Da({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=Ku({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(za,"runUpstreamOAuth");async function tl(e,t){e.applyChallengeScope(t.requestedScope),Ma({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:qa(t.upstreamServerId)};t.requestedScope!==void 0&&(r.scope=t.requestedScope);try{return await Lr(e,r)}catch(o){throw Da({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:o}),o}}n(tl,"exchangeUpstreamAuthorizationCode");async function Ha(e,t){let r=await za(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new f({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new f({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Ha,"requireUpstreamAuthorizationRedirect");async function ja(e){if(!e.forceRefresh&&ju(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t;try{t=await za(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(r){if(e.connection===void 0||!Zu(r))throw r;return de()?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:r.errorCode},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),{kind:"connect_required",payload:await Oa({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}})}}if(t==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(t!=="REDIRECT")throw new f({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new f({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 Oa({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(ja,"authorizeUpstreamOAuthSession");async function rl(e){let t=await ar(e.stateToken),r=await b().consumeUpstreamOAuthState({id:t.id,now:I(new Date)}),o=nl(r);return ol({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),al(o),o}n(rl,"consumeStoredCallbackState");function nl(e){switch(e.kind){case"consumed":throw new f({message:"OAuth state has already been used",extensionMembers:{[g]:"oauth_state_reused"}});case"missing":throw new f({message:"OAuth state is missing or expired",extensionMembers:{[g]:"oauth_state_expired"}});case"available":return e.record}}n(nl,"readConsumedCallbackState");function ol(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 f({message:"OAuth callback did not match the initiating request",extensionMembers:{[g]:"oauth_callback_mismatch"}})}n(ol,"assertStoredCallbackStateMatches");function al(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new f({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}})}n(al,"assertStoredCallbackStateFresh");async function Oa(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),va(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),ir(t)}n(Oa,"buildOAuthConnectRequiredResponse");async function Ba(e){let t=await rl({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Nt(t),[o]=await b().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),a={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&&(a.connection=o);let i=new qe(a),c=await tl(i,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(c==="AUTHORIZED")return t;throw c!=="REDIRECT"?new f({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${c}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new f({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Ba,"finishUpstreamOAuthCallback");F();import{importPKCS8 as il,SignJWT as sl}from"jose";var Na=1e4,Ja=64*1024,Ga=2,cl=300,te=d.string().min(1),dl=d.object({access_token:te,issued_token_type:d.literal(Sr),token_type:d.string().optional(),expires_in:d.number().int().positive().optional(),scope:te.optional()}).passthrough(),ul=d.object({id_token:te,token_type:te.optional(),expires_in:d.number().int().positive().optional(),refresh_token:te.optional(),scope:te.optional()}).passthrough(),ll=d.object({access_token:te,token_type:te,expires_in:d.number().int().positive().optional(),scope:te.optional(),resource:te.optional(),refresh_token:te.optional()}).passthrough();function La(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(La,"formEncodeClientCredential");function pl(e){return e.replaceAll("\\n",`
26
26
  `)}n(pl,"normalizePem");async function ml(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??cl,o=await il(pl(e.clientAuth.privateKeyPem),t),a={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new sl({jti:crypto.randomUUID()}).setProtectedHeader(a).setIssuer(e.clientAuth.clientId).setSubject(e.clientAuth.clientId).setAudience(e.clientAuth.audience??e.tokenUrl).setIssuedAt().setExpirationTime(`${r}s`).sign(o)}n(ml,"createPrivateKeyJwtClientAssertion");async function fl(e){switch(e.clientAuth.method){case"client_secret_post":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_secret",e.clientAuth.clientSecret);return;case"client_secret_basic":{let t=La(e.clientAuth.clientId),r=La(e.clientAuth.clientSecret);e.headers.authorization=`Basic ${btoa(`${t}:${r}`)}`;return}case"private_key_jwt":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_assertion_type",Gt),e.form.set("client_assertion",await ml({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}n(fl,"appendClientAuthentication");async function tn(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await fl({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}n(tn,"buildFormRequest");function Fa(e){return(t,r)=>or(t,r,{context:e,maxRedirects:Ga,maxResponseBytes:Ja,problemCode:"upstream_token_exchange_failed",timeoutMs:Na})}n(Fa,"defaultIdpFetchJson");function hl(e){return(t,r)=>aa(t,r,{context:e,maxRedirects:Ga,maxResponseBytes:Ja,problemCode:"upstream_token_exchange_failed",timeoutMs:Na})}n(hl,"defaultResourceAsFetchJson");function cr(e){let t={[g]:e.code,[we]:e.tokenUrl};return e.response!==void 0&&(t[_e]=e.response.status),new f({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}n(cr,"runtimeError");function rn(e){if(!e.response.ok)throw cr({code:"upstream_token_exchange_failed",message:(()=>{switch(e.stage){case"idp_refresh_token":return"IdP refresh-token grant failed while renewing the upstream ID-JAG subject token.";case"idp_token_exchange":return"IdP token exchange failed while requesting an upstream ID-JAG.";case"resource_as_jwt_bearer":return"Upstream Resource AS rejected the ID-JAG JWT-bearer exchange."}})(),tokenUrl:e.tokenUrl,response:e.response})}n(rn,"assertTokenEndpointSucceeded");function gl(e){let t=ul.safeParse(e.json);if(!t.success)throw cr({code:"upstream_token_response_invalid",message:"IdP refresh-token grant returned an invalid subject-token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={idToken:t.data.id_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),t.data.scope!==void 0&&(r.scope=t.data.scope),r}n(gl,"parseIdpRefreshTokenResponse");function yl(e){let t=dl.safeParse(e.json);if(!t.success)throw cr({code:"upstream_token_response_invalid",message:"IdP token exchange returned an invalid ID-JAG response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={assertion:t.data.access_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),r}n(yl,"parseIdJagTokenExchangeResponse");function _l(e){let t=ll.safeParse(e.json);if(!t.success)throw cr({code:"upstream_token_response_invalid",message:"Upstream Resource AS returned an invalid JWT-bearer token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={accessToken:t.data.access_token,tokenType:t.data.token_type};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),t.data.resource!==void 0&&(r.resource=t.data.resource),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),r}n(_l,"parseAccessTokenResponse");async function $a(e){let t=new URLSearchParams({grant_type:Jt,requested_token_type:Sr,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,audience:e.audience});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope),e.authorizationDetails!==void 0&&t.set("authorization_details",JSON.stringify(e.authorizationDetails));let r=e.fetchJson??Fa(e.context),{response:o,json:a}=await r(e.idp.tokenUrl,await tn({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return rn({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),yl({json:a,response:o,tokenUrl:e.idp.tokenUrl})}n($a,"requestIdJag");async function Za(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??Fa(e.context),{response:o,json:a}=await r(e.idp.tokenUrl,await tn({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return rn({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),gl({json:a,response:o,tokenUrl:e.idp.tokenUrl})}n(Za,"refreshIdpSubjectToken");async function Ka(e){let t=new URLSearchParams({grant_type:be,assertion:e.assertion});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope);let r=e.fetchJson??hl(e.context),{response:o,json:a}=await r(e.resourceAs.tokenUrl,await tn({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return rn({response:o,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),_l({json:a,response:o,tokenUrl:e.resourceAs.tokenUrl})}n(Ka,"exchangeIdJagForAccessToken");function wl(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(wl,"hasUsableAccessToken");function Rl(e){if(e.tokenType.toLowerCase()!=="bearer")throw new f({message:"Upstream Resource AS returned a token type the MCP gateway cannot send as a bearer token.",extensionMembers:{[g]:"upstream_token_response_invalid"}})}n(Rl,"assertBearerToken");function bl(e,t){if(t===Ge)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}n(bl,"hasExpiredSubjectToken");async function Il(e){let t=await ve(e.encryptedSubjectToken);if(e.subjectTokenType!==Ge)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await Za({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});return r.refreshToken===void 0?{connection:e.connection,subjectToken:r.idToken,subjectTokenType:ct}:{connection:await b().upsertUpstreamConnection({id:e.connection.id,ownerMode:e.connection.ownerMode,subjectId:e.connection.subjectId,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,status:"active",encryptedAccessToken:e.connection.encryptedAccessToken,encryptedRefreshToken:e.connection.encryptedRefreshToken,scopes:e.connection.scopes,expiresAt:e.connection.expiresAt,metadata:{...e.connection.metadata??{},encryptedIdpSubjectToken:await me(r.refreshToken),idpSubjectTokenType:Ge,idpSubjectTokenExpiresAt:void 0}}),subjectToken:r.idToken,subjectTokenType:ct}}n(Il,"resolveIdJagSubjectToken");async function Wa(e){let t="preloadedConnection"in e?e.preloadedConnection:(await b().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(!e.forceRefresh&&wl(t))return{kind:"authorized",credential:{type:"bearer_token",token:await ve(t.encryptedAccessToken)}};let r=t?.metadata?.encryptedIdpSubjectToken,o=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||r===void 0||o===void 0||bl(t,o))return{kind:"connect_required",payload:{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,message:`An IdP subject-token binding is required for ${e.upstreamDisplayName} before this tool can use XAA / ID-JAG.`,nextAction:"admin_setup_required"}};let a=Ie(e.upstreamServerId),i=ta(e.upstreamServerId,e.authProfileId),c=i.resourceAs.resource??a.transport.baseUrl,s=e.requestedScope??(i.scopes.length===0?void 0:i.scopes.join(i.scopeDelimiter)),u=await Il({connection:t,encryptedSubjectToken:r,subjectTokenType:o,idp:{tokenUrl:i.idp.tokenUrl},clientAuth:i.idp.clientAuth,context:e.context}),p=await $a({idp:{tokenUrl:i.idp.tokenUrl},subjectToken:u.subjectToken,subjectTokenType:u.subjectTokenType,audience:i.resourceAs.audience,resource:c,scope:s,clientAuth:i.idp.clientAuth,context:e.context}),h=p.scope??s,y=await Ka({resourceAs:{tokenUrl:i.resourceAs.tokenUrl},assertion:p.assertion,resource:c,scope:h,clientAuth:i.resourceAs.clientAuth,context:e.context});if(Rl(y),t!==void 0){let U=y.scope??h;await b().upsertUpstreamConnection({id:u.connection.id,ownerMode:u.connection.ownerMode,subjectId:u.connection.subjectId,upstreamServerId:u.connection.upstreamServerId,authProfileId:u.connection.authProfileId,status:"active",encryptedAccessToken:await me(y.accessToken),encryptedRefreshToken:u.connection.encryptedRefreshToken,scopes:U?.split(/[,\s]+/).filter(Boolean)??[],expiresAt:y.expiresIn===void 0?void 0:I(new Date(Date.now()+y.expiresIn*1e3)),metadata:u.connection.metadata})}return{kind:"authorized",credential:{type:"bearer_token",token:y.accessToken}}}n(Wa,"authorizeUpstreamIdJagRequest");function Cl(e){return sr(new URL(e.callbackPath,P(e.requestUrl,e.requestHeaders))).toString()}n(Cl,"buildGatewayOAuthRedirectUri");async function Va(e){let t=Ie(e.upstreamServerId),r=$e(e.upstreamServerId,e.authProfileId),o=Cl({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),a="preloadedConnection"in e?e.preloadedConnection:(await b().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:a,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,returnTo:e.returnTo},redirectUri:o,returnOrigin:P(e.request.url,e.request.headers)}}}n(Va,"prepareUpstreamOAuthRequest");async function Ya(e){let t=await Va(e),r=new qe({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Ha(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Ya,"startUpstreamConnect");async function Xa(e){let t=await Va(e),r=new qe({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return ja({target:e,provider:r,connection:t.connection,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Xa,"authorizeUpstreamRequest");async function We(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return Xa({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo});case"id-jag":return Wa({request:e.request,context:e.context,authMode:t.authMode,ownerMode:t.ownerMode,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,upstreamDisplayName:t.upstreamDisplayName,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo})}let r=t;throw new Y(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(We,"resolveUpstreamCredentialForRoute");async function Qa(e){if(e.connectRequest.authMode==="id-jag")throw new Y(`Upstream server ${e.connectRequest.upstreamServerId} uses XAA / ID-JAG and does not support browser OAuth connection flows.`);let t=await Ya({request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,operationId:e.connectRequest.operationId,returnTo:e.connectRequest.returnTo});return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}n(Qa,"startUpstreamConnectForRequest");async function ei(e){let r=(await ar(e.callbackRequest.state)).authProfileId;if(rr({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}).mode==="id-jag")throw new Y(`Upstream server ${e.callbackRequest.upstreamServerId} uses XAA / ID-JAG and does not support OAuth callbacks.`);return Ba({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:Ie(e.callbackRequest.upstreamServerId)})}n(ei,"finishUpstreamCallbackForRequest");function Sl(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(Sl,"buildRouteAuthBaseFromConnection");function ti(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:uo(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(ti,"buildRouteAuthBaseFromPolicyOptions");function dr(e,t){let o=X().byOperationId.get(t);if(!o)throw new j(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new j(`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 j(`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 Sl({connection:o.connection,operationId:t})}n(dr,"resolveRouteAuthBase");function nn(e,t){switch(e){case"user":return Ne(t);case"shared":return so()}}n(nn,"buildOwnerForSubject");function Ve(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:nn("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:nn("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:nn("user",t),initiatedBySubjectId:t}}}n(Ve,"resolveRouteAuthForSubject");var vl=at.InvalidRequest,Al=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function xl(e,t){return{credentialType:e.type,forceRefresh:t}}n(xl,"buildCredentialResolvedAttributes");function kl(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(kl,"connectRequiredReasonCode");function ri(e){v(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:xl(e.credential,e.forceRefresh===!0)})}n(ri,"emitCredentialResolvedAnalyticsEvent");function ni(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(v(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"){v(e.context,{eventType:C.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}v(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:kl(e.payload.state),reasonClass:"auth",attributes:t})}n(ni,"emitCredentialMissingAnalyticsEvents");function Tl(e){let t=e.route.raw();return jt.parse(t?.operationId)}n(Tl,"readOperationId");async function Ul(e,t,r,o){let a=await We({request:e,context:o,routeAuth:t});if(a.kind==="connect_required")return ni({context:o,payload:a.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:a.payload};let i=a.credential;if(ri({context:o,credential:i,routeBinding:t}),i.type==="bearer_token")return{kind:"headers",headers:[["authorization",`Bearer ${i.token}`]]};let c=await i.provider.tokens();return c?{kind:"headers",headers:[["authorization",`${c.token_type??"Bearer"} ${c.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(Ul,"buildCredentialHeaders");var Pl=new Set(["authorization","cookie","cookie2"]);function El(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(El,"readJsonRequestMethod");function Ol(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(Ol,"isJsonResponse");function on(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(on,"isRecord");function ql(e){return Array.isArray(e)&&e.length>0}n(ql,"hasIconList");function Ml(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=tr(eo(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(Ml,"readFallbackServerIcons");function Dl(e){if(!on(e.body))return e.body;let t=e.body.result;if(!on(t))return e.body;let r=t.serverInfo;return!on(r)||ql(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n(Dl,"addMissingServerIcons");function zl(e,t){let r=new Headers(e.headers);for(let o of Pl)r.delete(o);for(let[o,a]of t)r.set(o,a);return new Hn(e,{headers:r})}n(zl,"applyUpstreamHeaders");function Hl(e){let t=new Headers(e.headers);for(let r of Al)t.delete(r);return t}n(Hl,"buildProxyHeaders");async function jl(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(jl,"readRetryBody");function oi(e,t){let r=t.authUrl===void 0?void 0:Ho({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(Wt({id:zo(e),error:{code:r?.code??vl,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(oi,"connectRequiredJsonRpcResponse");async function Bl(e){let{scope:t}=Vo(e.upstreamResponse),r=await We({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="connect_required")return ni({context:e.context,payload:r.payload,routeBinding:e.routeAuth,forceRefresh:!0}),{kind:"connect_required",payload:r.payload};let o=new Headers(e.headers),a=r.credential;if(ri({context:e.context,credential:a,routeBinding:e.routeAuth,forceRefresh:!0}),a.type==="bearer_token")return o.set("authorization",`Bearer ${a.token}`),{kind:"headers",headers:o};let i=await a.provider.tokens();return i?(o.set("authorization",`${i.token_type??"Bearer"} ${i.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(Bl,"applyRefreshedCredentialHeaders");function Ll(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await Bl({request:e.request,context:e.context,headers:Hl(r),routeAuth:e.routeAuth,upstreamResponse:t});if(o.kind==="connect_required")return oi(e.requestBody,o.payload);if(o.kind==="response")return o.response;let a=to({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return qt.fetch(a.url,a.init)})}n(Ll,"installUpstreamAuthRetryHook");function Nl(e){if(El(e.requestBody)!=="initialize")return;let t=Ml({connection:e.connection,context:e.context});t===void 0||t.length===0||e.context.addResponseSendingHook(async r=>{if(!Ol(r))return r;let o;try{o=await r.clone().json()}catch{return r}let a=Dl({body:o,icons:t});if(a===o)return r;let i=new Headers(r.headers);return i.delete("content-length"),new Response(JSON.stringify(a),{status:r.status,statusText:r.statusText,headers:i})})}n(Nl,"installInitializeIconHook");async function an(e,t,r){let o=Tl(t),a=await jl(e),i=ti({connection:r,operationId:o}),c=Te(e.user,e.url,e.headers);t.log.setLogProperties?.({requestId:t.requestId}),go(t,c);let s=Ve(i,c.subjectId),u=await Ul(e,s,r,t);if(!(u instanceof Response)&&u.kind==="connect_required")return oi(a,u.payload);if(u instanceof Response)return u;let p=zl(e,u.headers);return Ll({request:p,context:t,requestBody:a,routeAuth:s}),Nl({context:t,requestBody:a,connection:r}),p}n(an,"mcpTokenExchangePolicy");var sn=class extends Mt{static{n(this,"McpTokenExchangeInboundPolicy")}constructor(t,r){let o=lo(t,r);super(o,r)}async handler(t,r){return G("policy.inbound.mcp-token-exchange"),an(t,r,this.options)}};F();var ai=Symbol("Html");function Jl(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n(Jl,"escapeHtml");function Gl(e){return e===null||typeof e!="object"?!1:e[ai]===!0}n(Gl,"isHtml");function ii(e){return e==null||e===!1?"":Array.isArray(e)?e.map(ii).join(""):Gl(e)?e.value:Jl(String(e))}n(ii,"renderValue");function fe(e){return{[ai]:!0,value:e}}n(fe,"trustedHtml");var Q=fe("");function S(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=ii(t[o]),r+=e[o+1]??"";return fe(r)}n(S,"html");function Ye(e){return e.value}n(Ye,"renderHtml");function si(e){return S`<p class="card__description">${e.detail}</p>${e.guidance} ${e.technicalDetails} ${e.action}`}n(si,"renderBrowserErrorPage");var Xe=fe('*,: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 Qe(e){return S`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" href="${e.iconHref}" /><style>
27
27
  ${e.styles}
28
28
  </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(Qe,"renderShell");var Fl="text/html; charset=utf-8";function et(e){try{return new URL(e).host}catch{return""}}n(et,"safeHostFromUrl");function ne(e){let t=Zl(e.kind??"authorization_failed"),r=$l(e);return new Response(Ye(Qe({title:e.title??t.title,iconHref:"",styles:Xe,headerIcon:Q,heading:e.title??t.title,subhead:"",body:si({detail:e.detail,guidance:S`<p class="card__description">${t.guidance}</p>`,technicalDetails:Xl({diagnostic:r,upstreamHtml:e.upstreamHtml}),action:Vl(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":Fl,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(ne,"browserErrorPageResponse");function $l(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??Kl(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??Wl(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}n($l,"buildBrowserErrorDiagnostic");function Zl(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(Zl,"readBrowserErrorPagePresentation");function Kl(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(Kl,"readBrowserErrorStage");function Wl(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(Wl,"readBrowserErrorSuggestedFix");function Vl(e){return e===void 0?Q:S`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(Vl,"renderAction");function Yl(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(`
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
3
  "type": "module",
4
- "version": "6.71.8",
4
+ "version": "6.71.10",
5
5
  "repository": "https://github.com/zuplo/zuplo",
6
6
  "author": "Zuplo, Inc.",
7
7
  "exports": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/cli",
3
- "version": "6.71.8",
3
+ "version": "6.71.10",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "type": "module",
@@ -25,11 +25,12 @@
25
25
  "dependencies": {
26
26
  "@inquirer/prompts": "8.5.2",
27
27
  "@opentelemetry/api": "1.9.0",
28
+ "@opentelemetry/api-logs": "0.201.1",
28
29
  "@swc/core": "1.10.18",
29
- "@zuplo/core": "6.71.8",
30
+ "@zuplo/core": "6.71.10",
30
31
  "@zuplo/editor": "1.0.20821740935",
31
- "@zuplo/openapi-tools": "6.71.8",
32
- "@zuplo/runtime": "6.71.8",
32
+ "@zuplo/openapi-tools": "6.71.10",
33
+ "@zuplo/runtime": "6.71.10",
33
34
  "chalk": "5.4.1",
34
35
  "chokidar": "3.5.3",
35
36
  "cookie": "1.0.2",
@@ -60,12 +61,13 @@
60
61
  "workerd": "1.20241230.0",
61
62
  "yargs": "17.7.2",
62
63
  "zod": "3.25.76",
63
- "@zuplo/graphql": "6.71.8",
64
- "@zuplo/otel": "6.71.8"
64
+ "@zuplo/graphql": "6.71.10",
65
+ "@zuplo/otel": "6.71.10"
65
66
  },
66
67
  "bundleDependencies": [
67
68
  "@inquirer/prompts",
68
69
  "@opentelemetry/api",
70
+ "@opentelemetry/api-logs",
69
71
  "@zuplo/core",
70
72
  "@zuplo/editor",
71
73
  "@zuplo/openapi-tools",