@zuplo/cli 6.72.0 → 6.72.1

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.
Files changed (99) hide show
  1. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-json-stringify/.github/dependabot.yml +42 -2
  2. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-json-stringify/README.md +5 -5
  3. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-json-stringify/index.js +4 -7
  4. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-json-stringify/package.json +3 -3
  5. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-json-stringify/test/additionalProperties.test.js +47 -0
  6. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-json-stringify/test/const.test.js +20 -0
  7. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-json-stringify/test/patternProperties.test.js +24 -0
  8. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/.gitattributes +2 -0
  9. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/.github/dependabot.yml +53 -0
  10. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/.github/workflows/ci.yml +154 -0
  11. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/.github/workflows/lock-threads.yml +19 -0
  12. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/LICENSE +30 -0
  13. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/README.md +152 -0
  14. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/benchmark/benchmark.mjs +159 -0
  15. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/benchmark/encoder.mjs +54 -0
  16. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/benchmark/equal.mjs +51 -0
  17. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/benchmark/non-simple-domain.mjs +22 -0
  18. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/benchmark/package.json +17 -0
  19. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/benchmark/string-array-to-hex-stripped.mjs +24 -0
  20. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/benchmark/ws-is-secure.mjs +65 -0
  21. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/eslint.config.js +6 -0
  22. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/index.js +405 -0
  23. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/lib/schemes.js +267 -0
  24. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/lib/utils.js +585 -0
  25. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/package.json +68 -0
  26. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/test/ajv.test.js +43 -0
  27. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/test/equal.test.js +168 -0
  28. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/test/fixtures/uri-js-parse.json +501 -0
  29. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/test/fixtures/uri-js-serialize.json +120 -0
  30. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/test/parse.test.js +325 -0
  31. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/test/query-fragment-normalization.test.js +33 -0
  32. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/test/resolve.test.js +87 -0
  33. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/test/rfc-3986.test.js +90 -0
  34. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/test/scheme-normalization.test.js +16 -0
  35. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/test/security-normalization.test.js +39 -0
  36. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/test/security-utf8-encoding.test.js +0 -0
  37. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/test/security.test.js +161 -0
  38. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/test/serialize.test.js +151 -0
  39. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/test/uri-js-compatibility.test.js +33 -0
  40. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/test/uri-js.test.js +912 -0
  41. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/test/util.test.js +47 -0
  42. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/tsconfig.json +10 -0
  43. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/types/index.d.ts +51 -0
  44. package/node_modules/@fastify/fast-json-stringify-compiler/node_modules/fast-uri/types/index.tst.ts +15 -0
  45. package/node_modules/@posthog/core/dist/index.d.ts +3 -0
  46. package/node_modules/@posthog/core/dist/index.d.ts.map +1 -1
  47. package/node_modules/@posthog/core/dist/index.js +133 -93
  48. package/node_modules/@posthog/core/dist/index.mjs +2 -1
  49. package/node_modules/@posthog/core/dist/metrics/index.d.ts +61 -0
  50. package/node_modules/@posthog/core/dist/metrics/index.d.ts.map +1 -0
  51. package/node_modules/@posthog/core/dist/metrics/index.js +326 -0
  52. package/node_modules/@posthog/core/dist/metrics/index.mjs +283 -0
  53. package/node_modules/@posthog/core/dist/metrics/metrics-utils.d.ts +41 -0
  54. package/node_modules/@posthog/core/dist/metrics/metrics-utils.d.ts.map +1 -0
  55. package/node_modules/@posthog/core/dist/metrics/metrics-utils.js +117 -0
  56. package/node_modules/@posthog/core/dist/metrics/metrics-utils.mjs +68 -0
  57. package/node_modules/@posthog/core/dist/metrics/types.d.ts +69 -0
  58. package/node_modules/@posthog/core/dist/metrics/types.d.ts.map +1 -0
  59. package/node_modules/@posthog/core/dist/metrics/types.js +18 -0
  60. package/node_modules/@posthog/core/dist/metrics/types.mjs +0 -0
  61. package/node_modules/@posthog/core/dist/posthog-core-stateless.d.ts +2 -0
  62. package/node_modules/@posthog/core/dist/posthog-core-stateless.d.ts.map +1 -1
  63. package/node_modules/@posthog/core/dist/posthog-core-stateless.js +16 -1
  64. package/node_modules/@posthog/core/dist/posthog-core-stateless.mjs +16 -1
  65. package/node_modules/@posthog/core/package.json +2 -2
  66. package/node_modules/@posthog/core/src/index.ts +20 -0
  67. package/node_modules/@posthog/core/src/metrics/index.spec.ts +459 -0
  68. package/node_modules/@posthog/core/src/metrics/index.ts +414 -0
  69. package/node_modules/@posthog/core/src/metrics/metrics-utils.ts +100 -0
  70. package/node_modules/@posthog/core/src/metrics/types.ts +89 -0
  71. package/node_modules/@posthog/core/src/posthog-core-stateless.ts +26 -0
  72. package/node_modules/@posthog/types/dist/capture-metric.d.ts +122 -0
  73. package/node_modules/@posthog/types/dist/capture-metric.d.ts.map +1 -0
  74. package/node_modules/@posthog/types/dist/capture-metric.js +36 -0
  75. package/node_modules/@posthog/types/dist/capture-metric.mjs +2 -0
  76. package/node_modules/@posthog/types/dist/index.d.ts +3 -1
  77. package/node_modules/@posthog/types/dist/index.d.ts.map +1 -1
  78. package/node_modules/@posthog/types/dist/index.js +19 -1
  79. package/node_modules/@posthog/types/dist/index.mjs +2 -0
  80. package/node_modules/@posthog/types/dist/posthog-config.d.ts +60 -0
  81. package/node_modules/@posthog/types/dist/posthog-config.d.ts.map +1 -1
  82. package/node_modules/@posthog/types/package.json +1 -1
  83. package/node_modules/@posthog/types/src/capture-metric.ts +133 -0
  84. package/node_modules/@posthog/types/src/index.ts +17 -0
  85. package/node_modules/@posthog/types/src/posthog-config.ts +62 -0
  86. package/node_modules/@zuplo/core/package.json +1 -1
  87. package/node_modules/@zuplo/graphql/package.json +1 -1
  88. package/node_modules/@zuplo/openapi-tools/package.json +1 -1
  89. package/node_modules/@zuplo/otel/package.json +1 -1
  90. package/node_modules/@zuplo/runtime/out/esm/{chunk-FAOWNDMK.js → chunk-IC7XGD5C.js} +93 -93
  91. package/node_modules/@zuplo/runtime/out/esm/chunk-IC7XGD5C.js.map +1 -0
  92. package/node_modules/@zuplo/runtime/out/esm/index.js +1 -1
  93. package/node_modules/@zuplo/runtime/out/esm/index.js.map +1 -1
  94. package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +1 -1
  95. package/node_modules/@zuplo/runtime/out/types/index.d.ts +830 -6
  96. package/node_modules/@zuplo/runtime/package.json +1 -1
  97. package/package.json +6 -6
  98. package/node_modules/@zuplo/runtime/out/esm/chunk-FAOWNDMK.js.map +0 -1
  99. /package/node_modules/@zuplo/runtime/out/esm/{chunk-FAOWNDMK.js.LEGAL.txt → chunk-IC7XGD5C.js.LEGAL.txt} +0 -0
@@ -22,5 +22,5 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$a as tr,$b as Ur,$d as cs,A as G,Aa as Ht,Ae as Rs,B as I,Ba as Pt,Be as qs,C as J,Ca as St,D as K,Da as Tt,E as M,Ea as Ut,F as N,Fa as $t,Fd as Rr,G as O,Ga as kt,Gd as qr,H as Q,Ha as Ft,Hd as vr,I as W,Ia as Lt,Id as zr,J as X,Ja as Rt,Jd as Gr,K as Y,Ka as qt,Kd as Ir,L as Z,La as vt,Ld as Jr,M as _,Ma as zt,Md as Kr,N as tt,Na as Gt,Nd as Mr,O as rt,Oa as It,Od as Nr,Pa as Jt,Pd as Or,Qa as Kt,Qd as Qr,Ra as Mt,Rd as Vr,Sa as Nt,Sd as Wr,Ta as Ot,Td as Xr,Ua as Qt,Ud as Yr,Va as Vt,Vd as Zr,Wa as Wt,Wb as Er,Wd as _r,Xa as Xt,Xb as Hr,Xd as ts,Ya as Yt,Yb as Pr,Yd as rs,Za as Zt,Zb as Sr,Zd as ss,_a as _t,_b as Tr,_d as es,a as x,ab as rr,ac as $r,ae as hs,b as y,ba as st,bb as sr,bc as kr,be as ms,c as w,ca as et,cb as er,cc as Fr,ce as gs,d as A,da as ot,db as or,dc as Lr,de as ds,e as b,ea as at,eb as ar,ee as us,f as l,fa as nt,fb as nr,fe as fs,g as j,ga as it,gb as ir,ge as xs,h as B,ha as pt,hb as pr,he as ys,i as n,ia as ct,ib as cr,ie as ws,j as C,ja as ht,jb as hr,je as As,k as D,ka as mt,kb as mr,ke as bs,l as E,la as gt,lb as gr,le as ls,m as H,ma as dt,mb as dr,me as js,n as P,na as ut,nb as ur,ne as Bs,o as S,oa as ft,ob as fr,oe as Cs,p as T,pa as xt,pb as xr,pe as Ds,q as U,qa as yt,qb as yr,qe as Es,r as $,ra as wt,rb as wr,re as Hs,sa as At,sb as Ar,se as Ps,t as k,ta as bt,tb as br,te as Ss,u as F,ua as lt,ub as lr,ue as Ts,v as L,va as jt,vb as jr,ve as Us,w as R,wa as Bt,wb as Br,we as $s,x as q,xa as Ct,xb as Cr,xe as ks,ya as Dt,yb as Dr,ye as Fs,z,za as Et,ze as Ls}from"./chunk-FAOWNDMK.js";import{a as v,d as V,e as os,f as as,g as ns,h as is,i as ps}from"./chunk-4MNJC7E2.js";import"./chunk-4QJJMELB.js";import{_ as u,a as t,aa as a,ba as f}from"./chunk-DSZS6PZJ.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{Ft as AIGatewayAnthropicToOpenAIInboundPolicy,Lt as AIGatewayAuthInboundPolicy,X as AIGatewayMeteringInboundPolicy,Rt as AIGatewayOpenAIToAnthropicOutboundPolicy,qt as AIGatewaySemanticCacheInboundPolicy,zt as AIGatewaySemanticCacheOutboundPolicy,vt as AIGatewaySemanticCacheV2InboundPolicy,Gt as AIGatewayUsageTrackerPolicy,ht as AWSLoggingPlugin,It as AkamaiAIFirewallInboundPolicy,Jt as AkamaiAIFirewallV2InboundPolicy,Ht as AkamaiApiSecurityPlugin,Kt as AkamaiFirewallForAiInboundPolicy,Mt as AkamaiFirewallForAiOutboundPolicy,Ot as AmberfloMeteringInboundPolicy,Nt as AmberfloMeteringPolicy,Vt as ApiAuthKeyInboundPolicy,Rs as ApiKeyConsumerClient,Qt as ApiKeyInboundPolicy,jt as AuditLogDataStaxProvider,Wt as AuditLogInboundPolicy,Bt as AuditLogPlugin,Yt as Auth0JwtInboundPolicy,Zt as AuthZenInboundPolicy,Z as AwsLambdaHandlerExtensions,_t as AxiomaticsAuthZInboundPolicy,St as AzureBlobPlugin,Tt as AzureEventHubsRequestLoggerPlugin,Pt as BackgroundDispatcher,qs as BackgroundLoader,tr as BasicAuthInboundPolicy,Yr as BasicRateLimitInboundPolicy,q as BatchDispatch,rr as BrownoutInboundPolicy,sr as CachingInboundPolicy,er as ChangeMethodInboundPolicy,or as ClearHeadersInboundPolicy,ar as ClearHeadersOutboundPolicy,nr as ClerkJwtInboundPolicy,ir as CognitoJwtInboundPolicy,pr as CometOpikTracingInboundPolicy,cr as CometOpikTracingV2InboundPolicy,hr as ComplexRateLimitInboundPolicy,mr as CompositeInboundPolicy,gr as CompositeOutboundPolicy,f as ConfigurationError,L as ContentTypes,Q as ContextData,o as CryptoBeta,dr as CurityPhantomTokenInboundPolicy,J as DataDogLoggingPlugin,wt as DataDogMetricsPlugin,ur as DataLossPreventionInboundPolicy,fr as DataLossPreventionOutboundPolicy,mt as DynaTraceLoggingPlugin,At as DynatraceMetricsPlugin,xr as FirebaseJwtInboundPolicy,yr as FormDataToJsonInboundPolicy,wr as GalileoTracingInboundPolicy,Ar as GalileoTracingV2InboundPolicy,br as GeoFilterInboundPolicy,I as GoogleCloudLoggingPlugin,Br as GraphqlAnalyticsOutboundPolicy,W as Handler,Cr as HttpDeprecationOutboundPolicy,$ as HttpProblems,S as HttpStatusCode,$t as HydrolixRequestLoggerPlugin,z as InboundPolicy,Dr as JWTScopeValidationInboundPolicy,Ct as JwtServicePlugin,gt as LokiLoggingPlugin,M as LookupResult,Jr as MTLSAuthInboundPolicy,Rr as McpAuth0OAuthInboundPolicy,Er as McpClerkOAuthInboundPolicy,Hr as McpCognitoOAuthInboundPolicy,Pr as McpEntraOAuthInboundPolicy,Dt as McpGatewayOAuthProtectedResourcePlugin,Sr as McpGoogleOAuthInboundPolicy,Tr as McpKeycloakOAuthInboundPolicy,Ur as McpLogtoOAuthInboundPolicy,qr as McpOAuthInboundPolicy,$r as McpOktaOAuthInboundPolicy,kr as McpOneLoginOAuthInboundPolicy,Fr as McpPingOAuthInboundPolicy,Lr as McpWorkosOAuthInboundPolicy,E as MemoryZoneReadThroughCache,vr as MockApiInboundPolicy,Gr as MoesifInboundPolicy,Ir as MonetizationInboundPolicy,dt as NewRelicLoggingPlugin,bt as NewRelicMetricsPlugin,Et as OAuthProtectedResourcePlugin,lt as OTelMetricsPlugin,Kr as OktaFGAAuthZInboundPolicy,Mr as OktaJwtInboundPolicy,Nr as OpenFGAAuthZInboundPolicy,Xt as OpenIdJwtInboundPolicy,Or as OpenMeterInboundPolicy,G as OutboundPolicy,U as ProblemResponseFormatter,Qr as PromptInjectionDetectionOutboundPolicy,Vr as PropelAuthJwtInboundPolicy,Wr as QueryParamToHeaderInboundPolicy,Xr as QuotaInboundPolicy,Yr as RateLimitInboundPolicy,Zr as ReadmeMetricsInboundPolicy,_r as RemoveHeadersInboundPolicy,ts as RemoveHeadersOutboundPolicy,rs as RemoveQueryParamsInboundPolicy,ss as ReplaceStringOutboundPolicy,kt as RequestLoggerPlugin,es as RequestSizeLimitInboundPolicy,cs as RequestValidationInboundPolicy,ms as RequireOriginInboundPolicy,N as ResponseSendingEvent,O as ResponseSentEvent,a as RuntimeError,u as SYSTEM_LOGGER,hs as SchemaBasedRequestValidation,gs as SecretMaskingOutboundPolicy,P as SemanticAttributes,ds as SemanticCacheInboundPolicy,Ls as ServiceProviderImpl,us as SetBodyInboundPolicy,fs as SetHeadersInboundPolicy,xs as SetHeadersOutboundPolicy,ys as SetQueryParamsInboundPolicy,ws as SetStatusOutboundPolicy,As as SetUpstreamApiKeyInboundPolicy,bs as SleepInboundPolicy,ut as SplunkLoggingPlugin,H as StreamingZoneCache,ls as StripeWebhookVerificationInboundPolicy,ft as SumoLogicLoggingPlugin,js as SupabaseJwtInboundPolicy,v as SystemRouteName,k as TelemetryPlugin,Bs as TrafficSplittingInboundPolicy,Cs as UpstreamAzureAdServiceAuthInboundPolicy,Ds as UpstreamFirebaseAdminAuthInboundPolicy,Es as UpstreamFirebaseUserAuthInboundPolicy,Ps as UpstreamGcpFederatedAuthInboundPolicy,Ss as UpstreamGcpJwtInboundPolicy,Ts as UpstreamGcpServiceAuthInboundPolicy,Us as UpstreamZuploJwtAuthInboundPolicy,xt as VMWareLogInsightLoggingPlugin,$s as ValidateJsonSchemaInbound,ks as WebBotAuthInboundPolicy,Fs as XmlToJsonOutboundPolicy,D as ZoneCache,yt as ZuploMcpSdk,F as ZuploRequest,Hs as ZuploServices,Y as aiGatewayHandler,C as apiServices,_ as awsLambdaHandler,Ut as defaultGenerateHydrolixEntry,V as environment,l as extractAllText,lr as extractGraphqlErrors,B as extractStreamTextDelta,b as flattenMessageContent,x as getFormat,as as getIdForParameterSchema,is as getIdForRefSchema,ns as getIdForRequestBodySchema,os as getRawOperationDataIdentifierName,y as getRequestBody,w as getResponseBody,j as getStreamEvents,A as getUsage,T as httpStatuses,tt as legacyDevPortalHandler,st as mcpServerHandler,et as openApiSpecHandler,K as recordGraphqlCacheState,ot as redirectHandler,rt as redirectLegacyDevPortal,jr as responseHasGraphqlErrors,ps as sanitizedIdentifierName,R as serialize,zr as setMoesifContext,n as trackFeature,nt as urlForwardHandler,it as urlRewriteHandler,pt as webSocketHandler,ct as webSocketPipelineHandler,at as zuploServiceProxy};
25
+ import{$a as tr,$b as Ur,$d as cs,A as G,Aa as Ht,Ae as Rs,B as I,Ba as Pt,Be as qs,C as J,Ca as St,Ce as vs,D as K,Da as Tt,E as M,Ea as Ut,F as N,Fa as $t,Fd as Rr,G as O,Ga as kt,Gd as qr,H as Q,Ha as Ft,Hd as vr,I as W,Ia as Lt,Id as zr,J as X,Ja as Rt,Jd as Gr,K as Y,Ka as qt,Kd as Ir,L as Z,La as vt,Ld as Jr,M as _,Ma as zt,Md as Kr,N as tt,Na as Gt,Nd as Mr,O as rt,Oa as It,Od as Nr,Pa as Jt,Pd as Or,Qa as Kt,Qd as Qr,Ra as Mt,Rd as Vr,Sa as Nt,Sd as Wr,Ta as Ot,Td as Xr,Ua as Qt,Ud as Yr,Va as Vt,Vd as Zr,Wa as Wt,Wb as Er,Wd as _r,Xa as Xt,Xb as Hr,Xd as ts,Ya as Yt,Yb as Pr,Yd as rs,Za as Zt,Zb as Sr,Zd as ss,_a as _t,_b as Tr,_d as es,a as x,ab as rr,ac as $r,ae as hs,b as y,ba as st,bb as sr,bc as kr,be as ms,c as w,ca as et,cb as er,cc as Fr,ce as gs,d as A,da as ot,db as or,dc as Lr,de as ds,e as b,ea as at,eb as ar,ee as us,f as l,fa as nt,fb as nr,fe as fs,g as j,ga as it,gb as ir,ge as xs,h as B,ha as pt,hb as pr,he as ys,i as n,ia as ct,ib as cr,ie as ws,j as C,ja as ht,jb as hr,je as As,k as D,ka as mt,kb as mr,ke as bs,l as E,la as gt,lb as gr,le as ls,m as H,ma as dt,mb as dr,me as js,n as P,na as ut,nb as ur,ne as Bs,o as S,oa as ft,ob as fr,oe as Cs,p as T,pa as xt,pb as xr,pe as Ds,q as U,qa as yt,qb as yr,qe as Es,r as $,ra as wt,rb as wr,re as Hs,sa as At,sb as Ar,se as Ps,t as k,ta as bt,tb as br,te as Ss,u as F,ua as lt,ub as lr,ue as Ts,v as L,va as jt,vb as jr,ve as Us,w as R,wa as Bt,wb as Br,we as $s,x as q,xa as Ct,xb as Cr,xe as ks,ya as Dt,yb as Dr,ye as Fs,z,za as Et,ze as Ls}from"./chunk-IC7XGD5C.js";import{a as v,d as V,e as os,f as as,g as ns,h as is,i as ps}from"./chunk-4MNJC7E2.js";import"./chunk-4QJJMELB.js";import{_ as u,a as t,aa as a,ba as f}from"./chunk-DSZS6PZJ.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{Ft as AIGatewayAnthropicToOpenAIInboundPolicy,Lt as AIGatewayAuthInboundPolicy,X as AIGatewayMeteringInboundPolicy,Rt as AIGatewayOpenAIToAnthropicOutboundPolicy,qt as AIGatewaySemanticCacheInboundPolicy,zt as AIGatewaySemanticCacheOutboundPolicy,vt as AIGatewaySemanticCacheV2InboundPolicy,Gt as AIGatewayUsageTrackerPolicy,ht as AWSLoggingPlugin,It as AkamaiAIFirewallInboundPolicy,Jt as AkamaiAIFirewallV2InboundPolicy,Ht as AkamaiApiSecurityPlugin,Kt as AkamaiFirewallForAiInboundPolicy,Mt as AkamaiFirewallForAiOutboundPolicy,Ot as AmberfloMeteringInboundPolicy,Nt as AmberfloMeteringPolicy,Vt as ApiAuthKeyInboundPolicy,qs as ApiKeyConsumerClient,Qt as ApiKeyInboundPolicy,jt as AuditLogDataStaxProvider,Wt as AuditLogInboundPolicy,Bt as AuditLogPlugin,Yt as Auth0JwtInboundPolicy,Zt as AuthZenInboundPolicy,Z as AwsLambdaHandlerExtensions,_t as AxiomaticsAuthZInboundPolicy,St as AzureBlobPlugin,Tt as AzureEventHubsRequestLoggerPlugin,Pt as BackgroundDispatcher,vs as BackgroundLoader,tr as BasicAuthInboundPolicy,Yr as BasicRateLimitInboundPolicy,q as BatchDispatch,rr as BrownoutInboundPolicy,sr as CachingInboundPolicy,er as ChangeMethodInboundPolicy,or as ClearHeadersInboundPolicy,ar as ClearHeadersOutboundPolicy,nr as ClerkJwtInboundPolicy,ir as CognitoJwtInboundPolicy,pr as CometOpikTracingInboundPolicy,cr as CometOpikTracingV2InboundPolicy,hr as ComplexRateLimitInboundPolicy,mr as CompositeInboundPolicy,gr as CompositeOutboundPolicy,f as ConfigurationError,L as ContentTypes,Q as ContextData,o as CryptoBeta,dr as CurityPhantomTokenInboundPolicy,J as DataDogLoggingPlugin,wt as DataDogMetricsPlugin,ur as DataLossPreventionInboundPolicy,fr as DataLossPreventionOutboundPolicy,mt as DynaTraceLoggingPlugin,At as DynatraceMetricsPlugin,xr as FirebaseJwtInboundPolicy,yr as FormDataToJsonInboundPolicy,wr as GalileoTracingInboundPolicy,Ar as GalileoTracingV2InboundPolicy,br as GeoFilterInboundPolicy,I as GoogleCloudLoggingPlugin,Br as GraphqlAnalyticsOutboundPolicy,W as Handler,Cr as HttpDeprecationOutboundPolicy,$ as HttpProblems,S as HttpStatusCode,$t as HydrolixRequestLoggerPlugin,z as InboundPolicy,Dr as JWTScopeValidationInboundPolicy,Ct as JwtServicePlugin,gt as LokiLoggingPlugin,M as LookupResult,Jr as MTLSAuthInboundPolicy,Rr as McpAuth0OAuthInboundPolicy,Er as McpClerkOAuthInboundPolicy,Hr as McpCognitoOAuthInboundPolicy,Pr as McpEntraOAuthInboundPolicy,Dt as McpGatewayOAuthProtectedResourcePlugin,Sr as McpGoogleOAuthInboundPolicy,Tr as McpKeycloakOAuthInboundPolicy,Ur as McpLogtoOAuthInboundPolicy,qr as McpOAuthInboundPolicy,$r as McpOktaOAuthInboundPolicy,kr as McpOneLoginOAuthInboundPolicy,Fr as McpPingOAuthInboundPolicy,Lr as McpWorkosOAuthInboundPolicy,E as MemoryZoneReadThroughCache,vr as MockApiInboundPolicy,Gr as MoesifInboundPolicy,Ir as MonetizationInboundPolicy,dt as NewRelicLoggingPlugin,bt as NewRelicMetricsPlugin,Et as OAuthProtectedResourcePlugin,lt as OTelMetricsPlugin,Kr as OktaFGAAuthZInboundPolicy,Mr as OktaJwtInboundPolicy,Nr as OpenFGAAuthZInboundPolicy,Xt as OpenIdJwtInboundPolicy,Or as OpenMeterInboundPolicy,G as OutboundPolicy,U as ProblemResponseFormatter,Qr as PromptInjectionDetectionOutboundPolicy,Vr as PropelAuthJwtInboundPolicy,Wr as QueryParamToHeaderInboundPolicy,Xr as QuotaInboundPolicy,Yr as RateLimitInboundPolicy,Zr as ReadmeMetricsInboundPolicy,_r as RemoveHeadersInboundPolicy,ts as RemoveHeadersOutboundPolicy,rs as RemoveQueryParamsInboundPolicy,ss as ReplaceStringOutboundPolicy,kt as RequestLoggerPlugin,es as RequestSizeLimitInboundPolicy,cs as RequestValidationInboundPolicy,ms as RequireOriginInboundPolicy,gs as RequireUserClaimsInboundPolicy,N as ResponseSendingEvent,O as ResponseSentEvent,a as RuntimeError,u as SYSTEM_LOGGER,hs as SchemaBasedRequestValidation,ds as SecretMaskingOutboundPolicy,P as SemanticAttributes,us as SemanticCacheInboundPolicy,Rs as ServiceProviderImpl,fs as SetBodyInboundPolicy,xs as SetHeadersInboundPolicy,ys as SetHeadersOutboundPolicy,ws as SetQueryParamsInboundPolicy,As as SetStatusOutboundPolicy,bs as SetUpstreamApiKeyInboundPolicy,ls as SleepInboundPolicy,ut as SplunkLoggingPlugin,H as StreamingZoneCache,js as StripeWebhookVerificationInboundPolicy,ft as SumoLogicLoggingPlugin,Bs as SupabaseJwtInboundPolicy,v as SystemRouteName,k as TelemetryPlugin,Cs as TrafficSplittingInboundPolicy,Ds as UpstreamAzureAdServiceAuthInboundPolicy,Es as UpstreamFirebaseAdminAuthInboundPolicy,Hs as UpstreamFirebaseUserAuthInboundPolicy,Ss as UpstreamGcpFederatedAuthInboundPolicy,Ts as UpstreamGcpJwtInboundPolicy,Us as UpstreamGcpServiceAuthInboundPolicy,$s as UpstreamZuploJwtAuthInboundPolicy,xt as VMWareLogInsightLoggingPlugin,ks as ValidateJsonSchemaInbound,Fs as WebBotAuthInboundPolicy,Ls as XmlToJsonOutboundPolicy,D as ZoneCache,yt as ZuploMcpSdk,F as ZuploRequest,Ps as ZuploServices,Y as aiGatewayHandler,C as apiServices,_ as awsLambdaHandler,Ut as defaultGenerateHydrolixEntry,V as environment,l as extractAllText,lr as extractGraphqlErrors,B as extractStreamTextDelta,b as flattenMessageContent,x as getFormat,as as getIdForParameterSchema,is as getIdForRefSchema,ns as getIdForRequestBodySchema,os as getRawOperationDataIdentifierName,y as getRequestBody,w as getResponseBody,j as getStreamEvents,A as getUsage,T as httpStatuses,tt as legacyDevPortalHandler,st as mcpServerHandler,et as openApiSpecHandler,K as recordGraphqlCacheState,ot as redirectHandler,rt as redirectLegacyDevPortal,jr as responseHasGraphqlErrors,ps as sanitizedIdentifierName,R as serialize,zr as setMoesifContext,n as trackFeature,nt as urlForwardHandler,it as urlRewriteHandler,pt as webSocketHandler,ct as webSocketPipelineHandler,at as zuploServiceProxy};
26
26
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["@zuplo/runtime/crypto-beta.ts","@zuplo/runtime/platforms/worker/crypto-beta.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;osDAIO,IAAMA,EAAmB,CAAC,QAAS,UAAW,UAAW,SAAS,EAKnDC,EAAf,KAA8B,CATrC,MASqC,CAAAC,EAAA,uBAErC,ECHO,IAAMC,EAAN,cAA+BC,CAAe,CARrD,MAQqD,CAAAC,EAAA,yBACnD,MAAM,OAAOC,EAAmBC,EAA+B,CAE7D,GADAC,EAAa,qBAAqB,EAC9B,CAACC,EAAiB,SAASH,EAAU,YAAY,CAAC,EACpD,MAAM,IAAII,EACR,aAAaJ,CAAS,gCAAgCG,EAAiB,KACrE,IACF,CAAC,EACH,EAEF,IAAME,EAAW,IAAI,YAAY,EAAE,OAAOJ,CAAI,EACxCK,EAAa,MAAM,OAAO,OAAO,OAAON,EAAWK,CAAQ,EAKjE,OAJkB,MAAM,KAAK,IAAI,WAAWC,CAAU,CAAC,EAEpD,IAAKC,GAAMA,EAAE,SAAS,EAAE,EAAE,SAAS,EAAG,GAAG,CAAC,EAC1C,KAAK,EAAE,CAEZ,CACF","names":["supportedDigests","BaseCryptoBeta","__name","WorkerCryptoBeta","BaseCryptoBeta","__name","algorithm","data","trackFeature","supportedDigests","RuntimeError","msgUint8","hashBuffer","b"]}
1
+ {"version":3,"sources":["@zuplo/runtime/crypto-beta.ts","@zuplo/runtime/platforms/worker/crypto-beta.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;6sDAIO,IAAMA,EAAmB,CAAC,QAAS,UAAW,UAAW,SAAS,EAKnDC,EAAf,KAA8B,CATrC,MASqC,CAAAC,EAAA,uBAErC,ECHO,IAAMC,EAAN,cAA+BC,CAAe,CARrD,MAQqD,CAAAC,EAAA,yBACnD,MAAM,OAAOC,EAAmBC,EAA+B,CAE7D,GADAC,EAAa,qBAAqB,EAC9B,CAACC,EAAiB,SAASH,EAAU,YAAY,CAAC,EACpD,MAAM,IAAII,EACR,aAAaJ,CAAS,gCAAgCG,EAAiB,KACrE,IACF,CAAC,EACH,EAEF,IAAME,EAAW,IAAI,YAAY,EAAE,OAAOJ,CAAI,EACxCK,EAAa,MAAM,OAAO,OAAO,OAAON,EAAWK,CAAQ,EAKjE,OAJkB,MAAM,KAAK,IAAI,WAAWC,CAAU,CAAC,EAEpD,IAAKC,GAAMA,EAAE,SAAS,EAAE,EAAE,SAAS,EAAG,GAAG,CAAC,EAC1C,KAAK,EAAE,CAEZ,CACF","names":["supportedDigests","BaseCryptoBeta","__name","WorkerCryptoBeta","BaseCryptoBeta","__name","algorithm","data","trackFeature","supportedDigests","RuntimeError","msgUint8","hashBuffer","b"]}
@@ -22,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$ as d,$b as Pc,$c as qr,Ab as K,Ac as wo,Ad as v,Bb as eo,Bc as ee,Bd as F,Cb as to,Cc as L,Cd as le,Db as M,Dc as bo,Dd as T,Eb as ro,Ec as Ro,Ed as Qt,Fb as Le,Fc as I,Fd as Dc,Gb as no,Gc as de,Gd as jc,Hb as Ne,Hc as $e,Ib as g,Ic as G,Jb as Je,Jc as q,Kb as Ge,Kc as Io,Lb as _e,Lc as N,Mb as we,Mc as Co,Nb as Nt,Nc as Re,Ob as oo,Oc as Tr,P as $n,Pb as re,Pc as Kt,Q as p,Qb as io,Qc as Ur,R as Zn,Rb as ce,Rc as Wt,S as Ar,Sb as b,Sc as pt,T as se,Tb as Jt,Tc as Ze,U as Kn,Ub as J,Uc as So,V as _,Vb as be,Vc as ue,W as ye,Wb as Ac,Wc as Pr,X as Lt,Xb as kc,Xc as Er,Y as Wn,Yb as xc,Yc as vo,Z as Vn,Zb as Tc,Zc as Vt,_ as Yn,_b as Uc,_c as Or,aa as Z,ac as Ec,ad as Ao,bc as Oc,bd as D,cc as qc,cd as ko,dc as Mc,dd as xo,ec as ao,ed as Mr,fc as so,fd as To,ga as Xn,gc as co,gd as Uo,hc as Gt,hd as Dr,i as ae,ic as kr,id as Po,jc as Ft,jd as Pe,kc as $t,kd as Eo,lc as dt,ld as mt,mc as uo,md as Oo,nc as lo,nd as Yt,oc as po,od as ft,pc as ut,pd as qo,qc as mo,qd as Mo,r as Ue,rc as Fe,rd as Do,s as Jn,sc as fo,sd as jo,tc as xr,td as zo,u as Gn,uc as ho,ud as Ho,vc as lt,vd as Bo,wc as Zt,wd as Xt,xc as go,xd as Lo,y as Fn,yc as yo,yd as No,z as Bt,zb as Qn,zc as _o,zd as R}from"../chunk-FAOWNDMK.js";import"../chunk-4MNJC7E2.js";import{a as C}from"../chunk-4QJJMELB.js";import{$ as Q,a as n,aa as h,ba as A,ca as Nn,da as Ht}from"../chunk-DSZS6PZJ.js";Z();function zc(e){let t=$t.safeParse(e);return t.success?t.data.id:void 0}n(zc,"parseJsonRpcRequestId");function Jo(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return zc(t)}catch{return}}n(Jo,"readJsonRpcRequestIdFromBody");function er(e){return uo.parse({jsonrpc:Ft,...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(er,"jsonRpcErrorResponse");function Go(e){return new po([lo.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Go,"urlElicitationRequiredError");var rr=d.record(d.string(),d.unknown()),Hc=d.record(d.string(),d.unknown()),Ie=d.array(d.string().min(1)).min(1).optional(),Bc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),annotations:Hc.optional(),_meta:rr.optional(),roles:Ie,groups:Ie,public:d.boolean().optional()}).strict(),Lc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),_meta:rr.optional(),roles:Ie,groups:Ie,public:d.boolean().optional()}).strict(),Nc=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:rr.optional(),roles:Ie,groups:Ie,public:d.boolean().optional()}).strict(),Jc=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:rr.optional(),roles:Ie,groups:Ie,public:d.boolean().optional()}).strict(),Gc=d.array(d.union([d.string(),Bc])),Fc=d.array(d.union([d.string(),Lc])),$c=d.array(d.union([d.string(),Nc])),Zc=d.array(d.union([d.string(),Jc])),Kc=d.object({module:d.unknown(),export:d.string().min(1)}).strict(),Wc=d.object({mode:d.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:d.string().min(1).optional(),groupClaim:d.string().min(1).optional(),identifier:Kc.optional()}).strict(),Vc=d.object({tools:Gc.optional(),prompts:Fc.optional(),resources:$c.optional(),resourceTemplates:Zc.optional(),accessControl:Wc.optional()}).strict(),Ce=[{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 Yc(e,t){return eo(Vc,e,`MCP capability filter policy "${t}"`)}n(Yc,"parseMcpCapabilityFilterOptions");function z(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(z,"isRecord");function Xc(e,t){if(!z(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(Xc,"readParamString");function zr(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(zr,"readRequestId");function Vo(e){return e===void 0?void 0:JSON.stringify(e)}n(Vo,"requestIdKey");function Fo(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}n(Fo,"asStringArray");function $o(e,t){if(!z(e))return[];let r=t in e?e[t]:t.split(".").reduce((o,i)=>z(o)?o[i]:void 0,e);return Array.isArray(r)?r.filter(o=>typeof o=="string"):typeof r=="string"?r.split(/\s+/).filter(o=>o.length>0):[]}n($o,"readClaimValues");function Hr(e,t){if(typeof e=="string")return{key:e,public:!1};if(!z(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:Fo(e.roles),groups:Fo(e.groups),public:e.public===!0}}n(Hr,"normalizeEntry");function Qc(e,t,r){if(e.public)return!0;let o=e.roles??[],i=e.groups??[];return o.length===0&&i.length===0?!1:o.some(a=>t.has(a))||i.some(a=>r.has(a))}n(Qc,"isCallerAllowed");function tr(e,t,r,o){if(e===void 0)return;let i=[];for(let a of e){let s=Hr(a,t);s!==void 0&&Qc(s,r,o)&&i.push(s.key)}return i}n(tr,"allowedKeys");var Yo=n((e,t,r)=>{let o=r.accessControl?.roleClaim??"roles",i=r.accessControl?.groupClaim??"groups",a=new Set($o(e.user?.data,o)),s=new Set($o(e.user?.data,i));return{tools:tr(r.tools,"name",a,s),prompts:tr(r.prompts,"name",a,s),resources:tr(r.resources,"uri",a,s),resourceTemplates:tr(r.resourceTemplates,"uriTemplate",a,s)}},"claimsCapabilityResolver");function ed(e,t){let r=[];for(let o of Ce){let i=e[o.option];if(i!==void 0)for(let a of i){let s=Hr(a,o.itemProperty);if(s===void 0)continue;let c=(s.roles?.length??0)>0||(s.groups?.length??0)>0;s.public&&c?r.push(`${o.option} "${s.key}" (both)`):!s.public&&!c&&r.push(`${o.option} "${s.key}" (neither)`)}}if(r.length>0)throw new A(`MCP capability filter policy "${t}" - with accessControl.mode "rolesAndGroups", every capability must set roles/groups OR "public": true (not both, not neither): ${r.join(", ")}`)}n(ed,"assertClassified");function td(e,t){let r=[];for(let o of Ce){let i=e[o.option];if(i!==void 0)for(let a of i){let s=Hr(a,o.itemProperty);s!==void 0&&((s.roles?.length??0)>0||(s.groups?.length??0)>0||s.public)&&r.push(`${o.option} "${s.key}"`)}}if(r.length>0)throw new A(`MCP capability filter policy "${t}" - accessControl.mode is "allPublic" (the default) but these capabilities set roles/groups/public; set accessControl.mode to "rolesAndGroups" or remove the markup: ${r.join(", ")}`)}n(td,"assertNoMarkup");function rd(e,t){let r=e.identifier;if(r===void 0)throw new A(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);if(r.module===null||typeof r.module!="object")throw new A(`MCP capability filter policy "${t}" - accessControl.identifier.module must reference a module, e.g. $import(./modules/mcp-access-control)`);if(!r.export)throw new A(`MCP capability filter policy "${t}" - accessControl.identifier.export must be specified`);let o=r.module[r.export];if(typeof o!="function")throw new A(`MCP capability filter policy "${t}" - accessControl.identifier must resolve to a valid function`);let i=o;return async(a,s,c)=>{let u=await i(a,s,c);if(u==null)throw new h(`MCP capability filter policy "${t}" - accessControl resolver returned no value; return an AllowedCapabilities object (use empty arrays to deny)`);if(typeof u!="object"||Array.isArray(u))throw new h(`MCP capability filter policy "${t}" - accessControl resolver must return an AllowedCapabilities object`);return u}}n(rd,"buildCustomResolver");function nd(e,t){let r=e.accessControl,o=r?.mode??"allPublic";if(o==="function"){if(r===void 0)throw new A(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);return rd(r,t)}if(o==="rolesAndGroups")return ed(e,t),Yo;td(e,t)}n(nd,"buildCapabilityResolver");function od(e){let t={};for(let r of Ce){let o=e[r.option];if(o===void 0)continue;let i=new Map;for(let a of o){let s=dd(a,r.itemProperty);s!==void 0&&i.set(s.key,s)}t[r.option]=i}return t}n(od,"buildProjectionMaps");function Br(e){return Ce.find(t=>t.listMethod===e)}n(Br,"findListRule");function id(e){return e.requests.some(t=>{if(!z(t))return!1;let r=Br(t.method);return r!==void 0&&e.projectionMaps[r.option]!==void 0})}n(id,"shouldFilterListResponses");function ad(e){return e.requests.some(t=>z(t)?Ce.some(r=>e.projectionMaps[r.option]===void 0?!1:r.listMethod===t.method||r.directMethods.some(o=>o.method===t.method)):!1)}n(ad,"requestTouchesConfiguredCapability");function sd(e){for(let t of Ce){let r=e.projectionMaps[t.option];if(r!==void 0)for(let o of t.directMethods){if(e.request.method!==o.method)continue;let i=Xc(e.request.params,o.paramProperty);if(i===void 0)continue;let a=e.allowedSets?.[t.option];if(!r.has(i)||a!==void 0&&!a.has(i))return{id:zr(e.request)}}}}n(sd,"findDisallowedDirectAccess");function cd(e){return Response.json(er({id:e,error:{code:dt.MethodNotFound,message:"Method not found"}}))}n(cd,"methodNotFoundResponse");function dd(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!z(e))return;let r=e[t];if(typeof r!="string")return;let o={...e};return delete o.roles,delete o.groups,delete o.public,{key:r,overlay:o}}n(dd,"buildProjection");function Zo(e){let t=e.base[e.property],r=e.overlay[e.property];return z(r)?z(t)?{...t,...r}:r:t}n(Zo,"mergeRecordProperty");function ud(e,t){let r={...e,...t.overlay},o=Zo({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let i=Zo({base:e,overlay:t.overlay,property:"_meta"});return i!==void 0&&(r._meta=i),r}n(ud,"applyProjection");function Ko(e,t,r,o){if(!z(e))return e;let i=e.result;if(!z(i))return e;let a=i[t.resultProperty];return!Array.isArray(a)||!a.every(s=>z(s)&&typeof s[t.itemProperty]=="string")?e:{...e,result:{...i,[t.resultProperty]:a.flatMap(s=>{if(!z(s))return[];let c=s[t.itemProperty];if(typeof c!="string")return[];if(o!==void 0&&!o.has(c))return[];let u=r.get(c);return u===void 0?[]:[ud(s,u)]})}}}n(Ko,"filterAndProjectItems");function ld(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!z(r))continue;let o=Br(r.method),i=zr(r),a=Vo(i);o!==void 0&&a!==void 0&&t.set(a,o)}return t}n(ld,"buildListRulesByResponseId");function pd(e){if(Array.isArray(e.responseBody)){let o=ld(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(i=>{if(!z(i)||"error"in i)return i;let a=Vo(zr(i)),s=a===void 0?void 0:o.get(a),c=s===void 0?void 0:e.projectionMaps[s.option];return s===void 0||c===void 0?i:Ko(i,s,c,e.allowedSets?.[s.option])})}if(!z(e.requestBody)||!z(e.responseBody)||"error"in e.responseBody)return e.responseBody;let t=Br(e.requestBody.method),r=t===void 0?void 0:e.projectionMaps[t.option];return t===void 0||r===void 0?e.responseBody:Ko(e.responseBody,t,r,e.allowedSets?.[t.option])}n(pd,"filterJsonRpcResponse");async function Wo(e){return e.clone().json()}n(Wo,"readJson");function md(e){return e.headers.get("content-type")?.includes("json")??!1}n(md,"isJsonResponse");var jr=class extends Bt{static{n(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#n;#t;constructor(t,r){let o=Yc(t,r);super(o,r),this.#r=o,this.#n=r,this.#e=od(o),this.#t=nd(o,r)}async handler(t,r){let o;try{o=await Wo(t)}catch{return t}let i=Array.isArray(o)?o:[o],a=this.#t!==void 0&&ad({requests:i,projectionMaps:this.#e})?await this.#o(t,r):void 0;for(let s of i){if(!z(s))continue;let c=sd({request:s,projectionMaps:this.#e,allowedSets:a});if(c!==void 0)return cd(c.id)}return id({requests:i,projectionMaps:this.#e})&&r.addResponseSendingHook(async s=>{if(!md(s))return s;let c;try{c=await Wo(s)}catch{return s}let u=pd({requestBody:o,responseBody:c,projectionMaps:this.#e,allowedSets:a});if(u===c)return s;let l=new Headers(s.headers);return l.delete("content-length"),new Response(JSON.stringify(u),{status:s.status,statusText:s.statusText,headers:l})}),t}async#o(t,r){let o=this.#t;if(o===void 0)return{};let i;try{i=await o(t,r,this.#r)}catch(s){r.log.error(`MCP capability filter policy "${this.#n}" - access-control resolver threw; denying configured capabilities`,s);let c={};for(let u of Ce)this.#e[u.option]!==void 0&&(c[u.option]=new Set);return c}let a={};for(let s of Ce){let c=this.#e[s.option];if(c===void 0)continue;let u=i[s.option];if(u===void 0)continue;let l=new Set;if(Array.isArray(u))for(let m of u)typeof m=="string"&&c.has(m)&&l.add(m);a[s.option]=l}return a}};var Lr;Lr=globalThis.crypto;async function fd(e){return(await Lr).getRandomValues(new Uint8Array(e))}n(fd,"getRandomValues");async function hd(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await fd(e-o.length);for(let a of i)a<r&&(o+=t[a%t.length])}return o}n(hd,"random");async function gd(e){return await hd(e)}n(gd,"generateVerifier");async function yd(e){let t=await(await Lr).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(yd,"generateChallenge");async function Nr(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await gd(e),r=await yd(t);return{code_verifier:t,code_challenge:r}}n(Nr,"pkceChallenge");Z();var H=Zn().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Vn.custom,message:"URL must be parseable",fatal:!0}),$n}).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"}),nr=Lt({resource:p().url(),authorization_servers:_(H).optional(),jwks_uri:p().url().optional(),scopes_supported:_(p()).optional(),bearer_methods_supported:_(p()).optional(),resource_signing_alg_values_supported:_(p()).optional(),resource_name:p().optional(),resource_documentation:p().optional(),resource_policy_uri:p().url().optional(),resource_tos_uri:p().url().optional(),tls_client_certificate_bound_access_tokens:se().optional(),authorization_details_types_supported:_(p()).optional(),dpop_signing_alg_values_supported:_(p()).optional(),dpop_bound_access_tokens_required:se().optional()}),ht=Lt({issuer:p(),authorization_endpoint:H,token_endpoint:H,registration_endpoint:H.optional(),scopes_supported:_(p()).optional(),response_types_supported:_(p()),response_modes_supported:_(p()).optional(),grant_types_supported:_(p()).optional(),token_endpoint_auth_methods_supported:_(p()).optional(),token_endpoint_auth_signing_alg_values_supported:_(p()).optional(),service_documentation:H.optional(),revocation_endpoint:H.optional(),revocation_endpoint_auth_methods_supported:_(p()).optional(),revocation_endpoint_auth_signing_alg_values_supported:_(p()).optional(),introspection_endpoint:p().optional(),introspection_endpoint_auth_methods_supported:_(p()).optional(),introspection_endpoint_auth_signing_alg_values_supported:_(p()).optional(),code_challenge_methods_supported:_(p()).optional(),client_id_metadata_document_supported:se().optional()}),_d=Lt({issuer:p(),authorization_endpoint:H,token_endpoint:H,userinfo_endpoint:H.optional(),jwks_uri:H,registration_endpoint:H.optional(),scopes_supported:_(p()).optional(),response_types_supported:_(p()),response_modes_supported:_(p()).optional(),grant_types_supported:_(p()).optional(),acr_values_supported:_(p()).optional(),subject_types_supported:_(p()),id_token_signing_alg_values_supported:_(p()),id_token_encryption_alg_values_supported:_(p()).optional(),id_token_encryption_enc_values_supported:_(p()).optional(),userinfo_signing_alg_values_supported:_(p()).optional(),userinfo_encryption_alg_values_supported:_(p()).optional(),userinfo_encryption_enc_values_supported:_(p()).optional(),request_object_signing_alg_values_supported:_(p()).optional(),request_object_encryption_alg_values_supported:_(p()).optional(),request_object_encryption_enc_values_supported:_(p()).optional(),token_endpoint_auth_methods_supported:_(p()).optional(),token_endpoint_auth_signing_alg_values_supported:_(p()).optional(),display_values_supported:_(p()).optional(),claim_types_supported:_(p()).optional(),claims_supported:_(p()).optional(),service_documentation:p().optional(),claims_locales_supported:_(p()).optional(),ui_locales_supported:_(p()).optional(),claims_parameter_supported:se().optional(),request_parameter_supported:se().optional(),request_uri_parameter_supported:se().optional(),require_request_uri_registration:se().optional(),op_policy_uri:H.optional(),op_tos_uri:H.optional(),client_id_metadata_document_supported:se().optional()}),or=ye({..._d.shape,...ht.pick({code_challenge_methods_supported:!0}).shape}),Ke=ye({access_token:p(),id_token:p().optional(),token_type:p(),expires_in:Yn.number().optional(),scope:p().optional(),refresh_token:p().optional()}).strip(),Qo=ye({error:p(),error_description:p().optional(),error_uri:p().optional()}),Xo=H.optional().or(Wn("").transform(()=>{})),wd=ye({redirect_uris:_(H),token_endpoint_auth_method:p().optional(),grant_types:_(p()).optional(),response_types:_(p()).optional(),client_name:p().optional(),client_uri:H.optional(),logo_uri:Xo,scope:p().optional(),contacts:_(p()).optional(),tos_uri:Xo,policy_uri:p().optional(),jwks_uri:H.optional(),jwks:Kn().optional(),software_id:p().optional(),software_version:p().optional(),software_statement:p().optional()}).strip(),ir=ye({client_id:p(),client_secret:p().optional(),client_id_issued_at:Ar().optional(),client_secret_expires_at:Ar().optional()}).strip(),gt=wd.merge(ir),cg=ye({error:p(),error_description:p().optional()}).strip(),dg=ye({token:p(),token_type_hint:p().optional()}).strip();function ei(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(ei,"resourceUrlFromServerUrl");function ti({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",a=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return i.startsWith(a)}n(ti,"checkResourceAllowed");var k=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}},yt=class extends k{static{n(this,"InvalidRequestError")}};yt.errorCode="invalid_request";var Ee=class extends k{static{n(this,"InvalidClientError")}};Ee.errorCode="invalid_client";var Oe=class extends k{static{n(this,"InvalidGrantError")}};Oe.errorCode="invalid_grant";var qe=class extends k{static{n(this,"UnauthorizedClientError")}};qe.errorCode="unauthorized_client";var _t=class extends k{static{n(this,"UnsupportedGrantTypeError")}};_t.errorCode="unsupported_grant_type";var wt=class extends k{static{n(this,"InvalidScopeError")}};wt.errorCode="invalid_scope";var bt=class extends k{static{n(this,"AccessDeniedError")}};bt.errorCode="access_denied";var pe=class extends k{static{n(this,"ServerError")}};pe.errorCode="server_error";var Rt=class extends k{static{n(this,"TemporarilyUnavailableError")}};Rt.errorCode="temporarily_unavailable";var It=class extends k{static{n(this,"UnsupportedResponseTypeError")}};It.errorCode="unsupported_response_type";var Ct=class extends k{static{n(this,"UnsupportedTokenTypeError")}};Ct.errorCode="unsupported_token_type";var St=class extends k{static{n(this,"InvalidTokenError")}};St.errorCode="invalid_token";var vt=class extends k{static{n(this,"MethodNotAllowedError")}};vt.errorCode="method_not_allowed";var At=class extends k{static{n(this,"TooManyRequestsError")}};At.errorCode="too_many_requests";var Me=class extends k{static{n(this,"InvalidClientMetadataError")}};Me.errorCode="invalid_client_metadata";var kt=class extends k{static{n(this,"InsufficientScopeError")}};kt.errorCode="insufficient_scope";var xt=class extends k{static{n(this,"InvalidTargetError")}};xt.errorCode="invalid_target";var ri={[yt.errorCode]:yt,[Ee.errorCode]:Ee,[Oe.errorCode]:Oe,[qe.errorCode]:qe,[_t.errorCode]:_t,[wt.errorCode]:wt,[bt.errorCode]:bt,[pe.errorCode]:pe,[Rt.errorCode]:Rt,[It.errorCode]:It,[Ct.errorCode]:Ct,[St.errorCode]:St,[vt.errorCode]:vt,[At.errorCode]:At,[Me.errorCode]:Me,[kt.errorCode]:kt,[xt.errorCode]:xt};function bd(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(bd,"isClientAuthMethod");var Jr="code",Gr="S256";function Rd(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&bd(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(Rd,"selectClientAuthMethod");function Id(e,t,r,o){let{client_id:i,client_secret:a}=t;switch(e){case"client_secret_basic":Cd(i,a,r);return;case"client_secret_post":Sd(i,a,o);return;case"none":vd(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(Id,"applyClientAuthentication");function Cd(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(Cd,"applyBasicAuth");function Sd(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(Sd,"applyPostAuth");function vd(e,t){t.set("client_id",e)}n(vd,"applyPublicAuth");async function oi(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Qo.parse(JSON.parse(r)),{error:i,error_description:a,error_uri:s}=o,c=ri[i]||pe;return new c(a||"",s)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new pe(i)}}n(oi,"parseErrorResponse");async function Zr(e,t){try{return await Fr(e,t)}catch(r){if(r instanceof Ee||r instanceof qe)return await e.invalidateCredentials?.("all"),await Fr(e,t);if(r instanceof Oe)return await e.invalidateCredentials?.("tokens"),await Fr(e,t);throw r}}n(Zr,"auth");async function Fr(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:i,fetchFn:a}){let s=await e.discoveryState?.(),c,u,l,m=i;if(!m&&s?.resourceMetadataUrl&&(m=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(u=s.authorizationServerUrl,c=s.resourceMetadata,l=s.authorizationServerMetadata??await si(u,{fetchFn:a}),!c)try{c=await ai(t,{resourceMetadataUrl:m},a)}catch{}(l!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:m?.toString(),resourceMetadata:c,authorizationServerMetadata:l})}else{let O=await Pd(t,{resourceMetadataUrl:m,fetchFn:a});u=O.authorizationServerUrl,l=O.authorizationServerMetadata,c=O.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:m?.toString(),resourceMetadata:c,authorizationServerMetadata:l})}let w=await Ad(t,e,c),P=o||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,y=await Promise.resolve(e.clientInformation());if(!y){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let O=l?.client_id_metadata_document_supported===!0,j=e.clientMetadataUrl;if(j&&!Kr(j))throw new Me(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${j}`);if(O&&j)y={client_id:j},await e.saveClientInformation?.(y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Ln=await Dd(u,{metadata:l,clientMetadata:e.clientMetadata,scope:P,fetchFn:a});await e.saveClientInformation(Ln),y=Ln}}let E=!e.redirectUrl;if(r!==void 0||E){let O=await Md(e,u,{metadata:l,resource:w,authorizationCode:r,fetchFn:a});return await e.saveTokens(O),"AUTHORIZED"}let x=await e.tokens();if(x?.refresh_token)try{let O=await qd(u,{metadata:l,clientInformation:y,refreshToken:x.refresh_token,resource:w,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(O),"AUTHORIZED"}catch(O){if(!(!(O instanceof k)||O instanceof pe))throw O}let B=e.state?await e.state():void 0,{authorizationUrl:Be,codeVerifier:X}=await Ed(u,{metadata:l,clientInformation:y,state:B,redirectUrl:e.redirectUrl,scope:P,resource:w});return await e.saveCodeVerifier(X),await e.redirectToAuthorization(Be),"REDIRECT"}n(Fr,"authInternal");function Kr(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(Kr,"isHttpsUrl");async function Ad(e,t,r){let o=ei(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!ti({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(Ad,"selectResourceURL");function ii(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let i=$r(e,"resource_metadata")||void 0,a;if(i)try{a=new URL(i)}catch{}let s=$r(e,"scope")||void 0,c=$r(e,"error")||void 0;return{resourceMetadataUrl:a,scope:s,error:c}}n(ii,"extractWWWAuthenticateParams");function $r(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=r.match(o);return i?i[1]||i[2]:null}n($r,"extractFieldFromWwwAuth");async function ai(e,t,r=fetch){let o=await Td(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 nr.parse(await o.json())}n(ai,"discoverOAuthProtectedResourceMetadata");async function Wr(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Wr(e,void 0,r):void 0;throw o}}n(Wr,"fetchWithCorsRetry");function kd(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(kd,"buildWellKnownPath");async function ni(e,t,r=fetch){return await Wr(e,{"MCP-Protocol-Version":t},r)}n(ni,"tryMetadataDiscovery");function xd(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(xd,"shouldAttemptFallback");async function Td(e,t,r,o){let i=new URL(e),a=o?.protocolVersion??kr,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let u=kd(t,i.pathname);s=new URL(u,o?.metadataServerUrl??i),s.search=i.search}let c=await ni(s,a,r);if(!o?.metadataUrl&&xd(c,i.pathname)){let u=new URL(`/.well-known/${t}`,i);c=await ni(u,a,r)}return c}n(Td,"discoverMetadataWithFallback");function Ud(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let i=t.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:"oidc"}),o.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(Ud,"buildDiscoveryUrls");async function si(e,{fetchFn:t=fetch,protocolVersion:r=kr}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=Ud(e);for(let{url:a,type:s}of i){let c=await Wr(a,o,t);if(c){if(!c.ok){if(await c.body?.cancel(),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}return s==="oauth"?ht.parse(await c.json()):or.parse(await c.json())}}}n(si,"discoverAuthorizationServerMetadata");async function Pd(e,t){let r,o;try{r=await ai(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch{}o||(o=String(new URL("/",e)));let i=await si(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(Pd,"discoverOAuthServerInfo");async function Ed(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:i,state:a,resource:s}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Jr))throw new Error(`Incompatible auth server: does not support response type ${Jr}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Gr))throw new Error(`Incompatible auth server: does not support code challenge method ${Gr}`)}else c=new URL("/authorize",e);let u=await Nr(),l=u.code_verifier,m=u.code_challenge;return c.searchParams.set("response_type",Jr),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",m),c.searchParams.set("code_challenge_method",Gr),c.searchParams.set("redirect_uri",String(o)),a&&c.searchParams.set("state",a),i&&c.searchParams.set("scope",i),i?.includes("offline_access")&&c.searchParams.append("prompt","consent"),s&&c.searchParams.set("resource",s.href),{authorizationUrl:c,codeVerifier:l}}n(Ed,"startAuthorization");function Od(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(Od,"prepareAuthorizationCodeRequest");async function ci(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:i,resource:a,fetchFn:s}){let c=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(a&&r.set("resource",a.href),i)await i(u,r,c,t);else if(o){let m=t?.token_endpoint_auth_methods_supported??[],w=Rd(o,m);Id(w,o,u,r)}let l=await(s??fetch)(c,{method:"POST",headers:u,body:r});if(!l.ok)throw await oi(l);return Ke.parse(await l.json())}n(ci,"executeTokenRequest");async function qd(e,{metadata:t,clientInformation:r,refreshToken:o,resource:i,addClientAuthentication:a,fetchFn:s}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),u=await ci(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:a,resource:i,fetchFn:s});return{refresh_token:o,...u}}n(qd,"refreshAuthorization");async function Md(e,t,{metadata:r,resource:o,authorizationCode:i,fetchFn:a}={}){let s=e.clientMetadata.scope,c;if(e.prepareTokenRequest&&(c=await e.prepareTokenRequest(s)),!c){if(!i)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let l=await e.codeVerifier();c=Od(i,l,e.redirectUrl)}let u=await e.clientInformation();return ci(t,{metadata:r,tokenRequestParams:c,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(Md,"fetchToken");async function Dd(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");a=new URL(t.registration_endpoint)}else a=new URL("/register",e);let s=await(i??fetch)(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!s.ok)throw await oi(s);return gt.parse(await s.json())}n(Dd,"registerClient");var Vr="zuplo.com",jd=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),zd=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function di(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(di,"s2FaviconHref");function Hd(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(Hd,"strictFaviconHref");var ar=di(Vr);function Yr(e){let t=e.toLowerCase();return t===Vr||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?di(Vr):Hd(e)}n(Yr,"resolveIconHref");function Bd(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(Bd,"hostnameFromHost");function Ld(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(Ld,"isLocalOrAddressHost");function Nd(e){let t=Bd(e).toLowerCase().replace(/\.$/,"");if(Ld(t)||zd.some(a=>t===a.slice(1)||t.endsWith(a)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let o=r.slice(-2).join("."),i=jd.has(o)?3:2;return r.slice(-i).join(".")}n(Nd,"inferFaviconDomain");function Xr(e){return{src:Yr(Nd(e)),mimeType:"image/png",sizes:["128x128"]}}n(Xr,"resolveMcpFaviconIcon");function sr(e){try{return Xr(new URL(e).host)}catch{return}}n(sr,"resolveMcpFaviconIconFromUrl");function Se(e){let t=ee().connectionsById.get(e);if(!t)throw new A(`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(Se,"getUpstreamServerConfig");function cr(e){let t=ee().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new A(`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(cr,"getUpstreamAuthConfig");function We(e,t){let r=cr({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new A(`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(We,"requireUpstreamOAuthConfig");function ui(e,t){let r=cr({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new A(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(ui,"requireUpstreamIdJagConfig");function li(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(li,"mergeAbortSignals");async function Jd(e){try{await e.cancel()}catch{}}n(Jd,"cancelReader");async function dr(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],i=0,a=await r.read();for(;!a.done;){let u=a.value;if(i+=u.byteLength,i>t.maxBytes)throw await Jd(r),t.createLimitError();o.push(u),a=await r.read()}let s=new Uint8Array(i),c=0;for(let u of o)s.set(u,c),c+=u.byteLength;return s}n(dr,"readBoundedByteStream");var Gd=2,Fd=1024*1024,$d=1e4,Zd=new Set([301,302,303,307,308]),Kd=["authorization","proxy-authorization","cookie","cookie2"];function Qr(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Qr,"readRequestUrl");function Ve(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(Ve,"readRequestMethod");function Wd(e,t,r){let o=e.headers.get("content-length");if(!o)return;let i=Number.parseInt(o,10);if(Number.isFinite(i)&&i>t)throw new h({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}})}n(Wd,"assertContentLengthWithinLimit");async function Vd(e,t,r){return Wd(e,t,r),dr(e.body,{maxBytes:t,createLimitError:n(()=>new h({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}}),"createLimitError")})}n(Vd,"readBoundedResponseBody");function Yd(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(Yd,"responseFromBufferedBody");function Xd(e,t){if(!Zd.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(Xd,"resolveRedirectUrl");function pi(e,t){try{return t.validateUrl(e)}catch(r){throw new h({message:"Outbound URL was not allowed.",extensionMembers:{[g]:t.problemCode}},{cause:r})}}n(pi,"validateOutboundUrl");function Qd(e,t){throw e instanceof h&&Nt(e.extensionMembers?.[g])?e:new h({message:"Outbound fetch failed.",extensionMembers:{[g]:t}},{cause:e})}n(Qd,"normalizeFetchError");function Tt(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[o,i]of Object.entries(t.extra))i!==void 0&&(r[o]=i);t.error!==void 0&&G(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(Tt,"logOutboundFailure");async function eu(e,t,r,o,i,a,s){let c=Ve(r,o);try{return await t(r,o)}catch(u){let l=u instanceof DOMException&&u.name==="AbortError";Tt(e,{event:l?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:i,method:c,host:q(a),error:u,extra:{abortReason:s()}}),Qd(u,i)}}n(eu,"fetchWithNormalizedError");function tu(e){if(e.redirects>=e.maxRedirects)throw new h({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[g]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new h({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[g]:e.problemCode}})}n(tu,"assertRedirectAllowed");function ru(e,t){let r=new Headers(e);for(let o of Kd)r.delete(o);for(let o of t)r.delete(o);return r}n(ru,"stripCrossOriginHeaders");function nu(e,t,r,o,i){let a={...e,method:t,redirect:"manual",signal:r};return o&&(a.headers=ru(e.headers,i)),a}n(nu,"buildRedirectInit");function ou(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(ou,"buildInitialRequestInit");function iu(e){let t=Ve(e.currentInput,e.currentInit);tu({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=pi(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),i=r.origin!==o.origin,a=r.toString();return{currentInput:a,currentUrl:a,currentInit:nu(e.currentInit,t,e.signal,i,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(iu,"followRedirect");async function en(e,t,r){let o=r.problemCode??"invalid_request",i=r.maxRedirects??Gd,a=r.maxResponseBytes??Fd,s=r.timeoutMs??$d,c=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],l=r.context,m=new AbortController,w=li(m,t.signal),P=!1,y=setTimeout(()=>{P=!0,m.abort()},s),E=e,x=ou(e,t,m.signal),B;try{B=pi(Qr(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(X){throw Tt(l,{event:"outbound_url_blocked",problemCode:o,method:Ve(e,t),host:q(Qr(e)),error:X}),clearTimeout(y),w?.(),X}let Be=0;try{for(;;){let X=await eu(l,c,E,x,o,B,()=>P?`timeout_after_${s}ms`:void 0),O=Xd(X,B);if(O!==void 0)try{let j=iu({currentInput:E,currentInit:x,currentUrl:B,redirectUrl:O,redirects:Be,maxRedirects:i,problemCode:o,validateUrl:r.validateUrl,signal:m.signal,additionalCrossOriginStrippedHeaders:u});E=j.currentInput,x=j.currentInit,B=j.currentUrl,Be=j.redirects;continue}catch(j){throw Tt(l,{event:"outbound_redirect_blocked",problemCode:o,method:Ve(E,x),host:q(B),error:j,extra:{redirects:Be,maxRedirects:i,redirectTargetHost:q(O)}}),j}try{return Yd(X,await Vd(X,a,o))}catch(j){throw Tt(l,{event:"outbound_response_size_exceeded",problemCode:o,method:Ve(E,x),host:q(B),error:j,extra:{maxResponseBytes:a,status:X.status}}),j}}}finally{clearTimeout(y),w?.()}}n(en,"runSafeOutboundExchange");async function Ut(e,t,r){let o=await en(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(i){throw Tt(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Ve(e,t),host:q(Qr(e)),error:i,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new h({message:"Outbound JSON response could not be parsed.",extensionMembers:{[g]:r.problemCode??"invalid_request"}},{cause:i})}}n(Ut,"runSafeOutboundJsonExchange");function mi(e,t={},r={}){return en(e,t,{...r,validateUrl:mt})}n(mi,"fetchConfiguredOutbound");function fi(e,t={},r={}){return Ut(e,t,{...r,validateUrl:mt})}n(fi,"fetchConfiguredOutboundJson");function ur(e,t={},r={}){return Ut(e,t,{...r,validateUrl:Oo})}n(ur,"fetchIdentityProviderJson");function hi(e,t={},r={}){return Ut(e,t,{...r,validateUrl:Yt})}n(hi,"fetchCimdClientMetadataJson");function gi(e,t={},r={}){return Ut(e,t,{...r,validateUrl:ft})}n(gi,"fetchCimdClientJwksJson");Z();import{errors as Ii,jwtVerify as Ci,SignJWT as Si}from"jose";var $="zuplo-mcp-gateway",W=$,V="HS256";import{base64url as au}from"jose";var su=new TextEncoder,cu="MCP gateway could not initialize secure key material.",du=32,yi=new Map,_i=new Map,uu;function lu(){return uu??Nn.instance.authPrivateKey}n(lu,"readAuthPrivateKey");function wi(e){return new Q(cu,e===void 0?void 0:{cause:e})}n(wi,"createGeneratedKeyMaterialError");function bi(e,t){let r=au.decode(t);if(r.byteLength!==du)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(bi,"decodeJwkKeyField");function pu(e){let t=lu();if(!t)throw wi();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=bi("d",r.d);bi("x",r.x);let i=su.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),a=new Uint8Array(i.byteLength+o.byteLength);return a.set(i),a.set(o,i.byteLength),a}catch(r){throw wi(r)}}n(pu,"decodeGeneratedKeyMaterial");function mu(e){let t=yi.get(e);return t||(t=pu(e),yi.set(e,t)),t}n(mu,"getMasterKeyMaterial");async function oe(e){let t=_i.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(mu(e.keyMaterialPurpose));return _i.set(e.purpose,r),r}n(oe,"readCachedDerivedKey");var fu="SHA-256",hu=32,gu="zuplo-mcp-gateway:",yu=new TextEncoder,Ri=new WeakMap;async function ve(e,t){let r=Ri.get(e);r||(r=new Map,Ri.set(e,r));let o=r.get(t);if(o)return o;let i=await _u(e,t);return r.set(t,i),i}n(ve,"deriveGatewaySigningKey");async function _u(e,t){let r=F(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=yu.encode(`${gu}${t}`),a=await crypto.subtle.deriveBits({name:"HKDF",hash:fu,salt:new Uint8Array,info:F(i)},o,hu*8);return new Uint8Array(a)}n(_u,"hkdfExpand");var vi=900,wu=900,bu=ho.extend({id:zo}),Ru=bu.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),Ai=xr.extend({id:Ho,purpose:d.literal("browser_connect")}),Iu=xr.extend({purpose:d.literal("browser_connect")}),Cu=Ai.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ki=vi*1e3;async function xi(){return oe({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>ve(e,"oauth-state"),"derive")})}n(xi,"getOAuthStateKey");async function Ti(){return oe({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>ve(e,"browser-connect"),"derive")})}n(Ti,"getBrowserConnectKey");async function Ui(e){let t=Math.floor(Date.now()/1e3)+vi;return new Si(e).setProtectedHeader({alg:V,typ:"JWT"}).setIssuer($).setAudience(W).setIssuedAt().setExpirationTime(t).sign(await xi())}n(Ui,"signOAuthState");async function lr(e){try{let{payload:t}=await Ci(e,await xi(),{algorithms:[V],issuer:$,audience:W});return Ru.parse(t)}catch(t){throw t instanceof Ii.JWTExpired?new h({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new h({message:"OAuth state could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(lr,"verifyOAuthState");async function Pi(e){let t=Math.floor(Date.now()/1e3)+wu,r=Iu.parse(e),o=Ai.parse({...r,id:No()});return new Si(o).setProtectedHeader({alg:V,typ:"JWT"}).setIssuer($).setAudience(W).setIssuedAt().setExpirationTime(t).sign(await Ti())}n(Pi,"signBrowserConnectTicket");async function Ei(e){try{let{payload:t}=await Ci(e,await Ti(),{algorithms:[V],issuer:$,audience:W});return Cu.parse(t)}catch(t){throw t instanceof Ii.JWTExpired?new h({message:"Browser connect ticket has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new h({message:"Browser connect ticket could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(Ei,"verifyBrowserConnectTicket");async function Oi(e){if((await R().consumeBrowserConnectTicket({id:e.id,expiresAt:I(new Date(e.exp*1e3)),now:I(new Date)})).kind==="consumed")throw new h({message:"Browser connect ticket has already been used",extensionMembers:{[g]:"oauth_state_reused"}})}n(Oi,"consumeBrowserConnectTicket");function Su(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(Su,"buildConnectRequiredMessage");async function vu(e){let t=M(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 Pi({...lt(e),purpose:"browser_connect"})),r.toString()}n(vu,"buildGatewayBrowserTicketUrl");function Au(e){return L().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(Au,"buildGatewayConnectPath");async function tn(e){return vu({...e,path:Au(e.upstreamServerId),redirect:!0})}n(tn,"buildGatewayConnectUrl");async function pr(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 tn(t),message:Su(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(pr,"buildRedirectConnectRequiredResponse");function qi(e){return ku({...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(qi,"buildAdminConnectRequiredResponse");function ku(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(ku,"buildAdminSetupRequiredResponse");var Mi=12;async function Di(e){let t=await crypto.subtle.digest("SHA-256",F(new TextEncoder().encode(e)));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}n(Di,"sha256Hex");async function Ye(e){if(e)return(await Di(e)).slice(0,Mi)}n(Ye,"fingerprintSecret");async function Xe(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await Di(t)).slice(0,Mi)}n(Xe,"fingerprintConnectionIdentity");function Pt(e){return e?e.status!=="active"?"inactive":e.encryptedAccessToken?e.expiresAt&&new Date(e.expiresAt).getTime()<=Date.now()?"expired":"usable":"no_access_token":"no_connection"}n(Pt,"describeAccessTokenState");Z();var ji=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function xu(e,t){return e&&e.length>0?e.join(t):void 0}n(xu,"joinOAuthScopes");function Tu(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of ji)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(Tu,"sanitizeAuthorizationServerMetadata");function zi(e){let t=Tu(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(zi,"sanitizeOAuthDiscoveryState");function Hi(e){let t=new URL(e);for(let r of ji){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(Hi,"dedupeSingletonAuthorizationRequestParams");function mr(e){let t=new URL(e);return K(t)&&Qn(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(mr,"normalizeLoopbackOAuthRedirectUri");function Bi(e){return xu(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(Bi,"readProtectedResourceMetadataScope");function Uu(e){return`Zuplo MCP Gateway - ${e}`}n(Uu,"buildGatewayOAuthClientName");function Pu(e,t){return e&&e.length>0?e.join(t):void 0}n(Pu,"joinOAuthScopeList");function Eu(e){if(e.clientRegistration.mode!=="auto")return Pu(e.scopes,e.scopeDelimiter)}n(Eu,"readPublicClientMetadataScope");function rn(e){return new URL(L().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(rn,"buildOAuthClientMetadataDocumentUrl");function nn(e){let t=Se(e.upstreamServerId);return{client_name:Uu(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(nn,"buildGatewayOAuthClientMetadata");function Li(e,t,r){let o=We(t,r),i=Eu(o);return{client_id:rn({origin:e,upstreamServerId:t}),...nn({origin:e,upstreamServerId:t,redirectUri:mr(new URL(o.redirectPath,e)).toString(),scope:i})}}n(Li,"buildOAuthClientMetadataDocument");Z();import{base64url as Ae}from"jose";var Ou="SHA-256",Qe="AES-GCM",qu=12,an="zuplo-secret",sn=1,Ni="generated:auth_private_key:token-encryption",Mu=d.object({version:d.literal(sn),keyId:d.literal(Ni),algorithm:d.literal(Qe),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();async function on(){return oe({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(Ou,F(e));return crypto.subtle.importKey("raw",t,{name:Qe},!1,["encrypt","decrypt"])},"derive")})}n(on,"getEncryptionKey");function Ji(e){return F(new TextEncoder().encode(`${an}:v${e.version}:${e.keyId}`))}n(Ji,"getAssociatedData");function Du(e){return`${an}:v${e.version}:${Ae.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(Du,"encodeEnvelope");function ju(e){let t=`${an}:v${sn}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(Ae.decode(r));return Mu.parse(JSON.parse(o))}n(ju,"decodeEnvelope");async function me(e){let t=await on(),r=crypto.getRandomValues(new Uint8Array(qu)),o={version:sn,keyId:Ni},i=await crypto.subtle.encrypt({name:Qe,iv:r,additionalData:Ji(o)},t,new TextEncoder().encode(e));return Du({...o,algorithm:Qe,iv:Ae.encode(r),ciphertext:Ae.encode(new Uint8Array(i))})}n(me,"encryptSecret");async function ke(e){let t=ju(e);if(t){let s=await on(),c=await crypto.subtle.decrypt({name:Qe,iv:F(Ae.decode(t.iv)),additionalData:Ji(t)},s,F(Ae.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,o]=e.split(".");if(!r||!o)throw new Q("Encrypted payload is malformed");let i=await on(),a=await crypto.subtle.decrypt({name:Qe,iv:F(Ae.decode(r))},i,F(Ae.decode(o)));return new TextDecoder().decode(a)}n(ke,"decryptSecret");var zu=d.union([gt,ir]),Hu=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:nr.optional(),authorizationServerMetadata:d.union([ht,or]).optional()}).passthrough(),Bu="Bearer",Lu="__zuplo_refresh_only_upstream_access_token__";function Gi(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Gi,"splitScopes");function Nu(e){return Ne.parse(e)}n(Nu,"parsePkceCodeVerifier");function Ju(e){if(typeof e.expires_in=="number")return I(new Date(Date.now()+e.expires_in*1e3))}n(Ju,"readTokenExpiry");async function Gu(e){if(e!==void 0)return me(JSON.stringify(e))}n(Gu,"encryptJson");async function Fu(e,t){if(!e)return;let r=await ke(e);try{return t.parse(JSON.parse(r))}catch(o){throw new h({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:o})}}n(Fu,"decryptJson");function $u(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n($u,"clientInformationAllowsRedirectUri");function Zu(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(Zu,"clientInformationMatchesCurrentClientMetadataUrl");function Ku(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(Ku,"isUrlBasedClientInformation");function Wu(e,t){return t===void 0?e:{...e,scope:t}}n(Wu,"applyOAuthClientMetadataScope");function Vu(e,t){return Bi({state:e,delimiter:t})}n(Vu,"readResourceMetadataScope");function Yu(e,t){return e&&e.length>0?e.join(t):void 0}n(Yu,"joinOAuthScopeList");function Xu(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new A(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return gt.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(Xu,"buildManualOAuthClientInformation");function Qu(e,t){let r=rn({origin:new URL(t).origin,upstreamServerId:e});return Kr(r)?r:void 0}n(Qu,"buildClientMetadataUrl");function el(e){for(let t of e)if(t!==void 0)return t}n(el,"firstDefined");function tl(e){let t=We(e.target.upstreamServerId,e.target.authProfileId),r=Yu(t.scopes,t.scopeDelimiter),o=nn({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,promptOverride:t.prompt,configuredClientInformation:Xu({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let i=Qu(e.target.upstreamServerId,e.redirectUri);return i===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,clientMetadataUrl:i}}n(tl,"buildInitialOAuthClientSetup");function rl(e,t){if(t===void 0)return el([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(rl,"readEncryptedClientInformation");var De=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredScope;scopeDelimiter;promptOverride;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;connection;pendingState;encryptedClientInformation;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;connectionFingerprintValue;usedRefreshTokenFingerprintValue;constructor(t){let r=tl({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.promptOverride=r.promptOverride,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=rl(t,this.configuredClientInformation)}get authorizationUrl(){return this.authorizationUrlValue}get configuredAuthorizationScope(){return this.configuredScope}get usedRefreshTokenFingerprint(){return this.usedRefreshTokenFingerprintValue}async connectionFingerprint(){return this.connectionFingerprintValue===void 0&&(this.connectionFingerprintValue=await Xe({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return Wu(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return Ui({id:t.id,...lt({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,N()?.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"),!Ku({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Gu(t),await this.syncPendingState(!1)))}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=zi(Hu.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,N()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:q(r.authorizationServerUrl),resourceMetadataHost:q(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=Vu(r,this.scopeDelimiter);let o=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&o!==void 0){let i=Gi(this.configuredScope).filter(a=>!o.includes(a));i.length>0&&N()?.debug({event:"upstream_oauth_configured_scopes_not_advertised",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,unadvertisedScopes:i,scopesSupported:o},"Configured upstream OAuth scopes include values the resource metadata does not advertise")}}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Ke.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=this.connection,a=!r.refresh_token&&!!i?.encryptedRefreshToken,s=r.refresh_token?await me(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:Ke.parse({...r,refresh_token:await ke(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let c={id:this.connection?.id??Xt(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await me(r.access_token),encryptedRefreshToken:s,scopes:Gi(r.scope??this.readEffectiveScope()),expiresAt:Ju(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await R().upsertUpstreamConnection(c),N()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.connection.id,hasRefreshToken:!!s,priorStatus:i?.status,priorUpdatedAt:i?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await Ye(r.refresh_token),reusedSnapshotRefreshToken:a,scopeCount:c.scopes.length,expiresAt:c.expiresAt},"Upstream OAuth tokens persisted; upstream connection is active")}async redirectToAuthorization(t){let r=Hi(t);this.promptOverride===!1?r.searchParams.delete("prompt"):this.promptOverride!==void 0&&r.searchParams.set("prompt",this.promptOverride),this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:Nu(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new h({message:"OAuth code verifier is missing",extensionMembers:{[g]:"oauth_state_invalid"}});return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",o=t==="all"||t==="client",i=t==="all"||t==="discovery",a=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),i&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.challengeScope=void 0,this.inferredScope=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(a),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:Lo(),...lt({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()+ki)),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 R().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await Fu(this.encryptedClientInformation,zu)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&(!$u(t,this.redirectUriValue)||!Zu({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=ir.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"){N()?.debug({event:"upstream_oauth_tokens_not_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.connection?.id,status:this.connection?.status??"not_connected"},"Upstream OAuth tokens not loaded; connection is not active");return}let t=this.connection.encryptedAccessToken?await ke(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await ke(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=N();this.usedRefreshTokenFingerprintValue=o?await Ye(r):void 0,o?.debug({event:"upstream_oauth_tokens_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.connection.id,hasAccessToken:!!t,hasRefreshToken:!!r,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,expiresAt:this.connection.expiresAt},"Upstream OAuth tokens loaded from stored connection");let i=Ke.parse({access_token:t??Lu,token_type:Bu,refresh_token:r,scope:this.connection.scopes.length>0?this.connection.scopes.join(" "):void 0});return this.cachedTokens=i,i}async persistCredentialInvalidation(t){if(!this.connection)return;let r=this.connection.status,o=this.connection.updatedAt,i={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&&(i.status="reconsent_required",i.encryptedAccessToken=void 0,i.encryptedRefreshToken=void 0,i.scopes=[],i.expiresAt=void 0),i.metadata=this.readStoredOAuthPersistence(this.connection.metadata?.connectedBySubjectId),this.connection=await R().upsertUpstreamConnection(i);let a=N();if(a){let s={event:"upstream_oauth_credentials_invalidated",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.connection.id,clearedTokens:t,priorStatus:r,newStatus:this.connection.status,priorUpdatedAt:o,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue};t?a.warn(s,"Upstream OAuth credentials invalidated; connection now requires reconsent"):a.debug(s,"Upstream OAuth credential metadata rewritten")}}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var nl=3e4,ol=256*1024,il=2,al="does not support dynamic client registration",sl=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],cl=["HTTP 403 Forbidden","Access Denied","permission to access"],dl=new Set(["access_denied","invalid_client","invalid_grant","invalid_request","invalid_scope","invalid_target","unauthorized_client","unsupported_grant_type"]);function ul(e){return e instanceof Error&&e.message.includes(al)}n(ul,"isDynamicClientRegistrationUnsupported");function ll(e){return e instanceof Error&&sl.some(t=>e.message.includes(t))}n(ll,"isProtectedResourceMetadataUnavailable");function pl(e){return e instanceof Error&&cl.some(t=>e.message.includes(t))}n(pl,"isUpstreamProviderAccessDenied");function ml(e){return e instanceof k&&dl.has(e.errorCode)}n(ml,"isStoredConnectionReconsentError");function fl(e){if(e.error instanceof h&&e.error.extensionMembers?.[g]!==void 0)return e.error;if(ul(e.error))return new h({message:`The authorization server for ${e.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register an OAuth client for the gateway manually before retrying.`,extensionMembers:{[g]:"upstream_client_registration_required"}},{cause:e.error});if(ll(e.error))return new h({message:`The upstream MCP server "${e.upstreamServerId}" does not publish OAuth protected resource metadata at "${e.resourceMetadataUrl}". Configure protectedResourceMetadataUrl to a working metadata document, use a provider-supported legacy client, or contact the provider to approve/allowlist this gateway OAuth client before retrying.`,extensionMembers:{[g]:"upstream_oauth_discovery_unavailable"}},{cause:e.error});if(pl(e.error))return new h({message:`The upstream provider denied access while connecting ${e.upstreamServerId}. Confirm the provider allows this gateway and its OAuth client, then retry.`,extensionMembers:{[g]:"upstream_provider_access_denied"}},{cause:e.error})}n(fl,"mapUpstreamOAuthSetupError");function hl(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(hl,"readOAuthFetchRequest");function gl(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(gl,"responseLooksJson");function yl(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(yl,"responseLooksHtml");function _l(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new h({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[g]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[_e]:e.response.status,[Je]:r,[we]:e.request.url.toString(),[Ge]:e.body}})}n(_l,"throwUpstreamHtmlError");function wl(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(wl,"readUpstreamOAuthErrorBody");function bl(e){let{error:t,errorDescription:r}=wl(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.request.method??"GET",host:q(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(bl,"logUpstreamOAuthHttpError");function $i(e){return async(t,r)=>{let o=hl(t),i=N(),a=Date.now(),s=await mi(t,r,{maxRedirects:il,maxResponseBytes:ol,problemCode:"upstream_token_exchange_failed",timeoutMs:nl}),c=await s.clone().text();if(i?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:o.method??"GET",host:q(o.url),path:o.url.pathname,status:s.status,durationMs:Date.now()-a,responseChars:c.length},"Upstream OAuth HTTP request completed"),s.ok||bl({log:i,upstreamServerId:e,request:o,response:s,body:c}),!s.ok&&yl(s,c)&&_l({upstreamServerId:e,request:o,response:s,body:c}),!gl(s,c))return s;try{JSON.parse(c)}catch(u){throw new h({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[g]:"upstream_token_exchange_failed"}},{cause:u})}return s}}n($i,"createUpstreamOAuthFetch");function Zi(e){N()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:q(e.serverUrl),resourceMetadataHost:q(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}n(Zi,"logUpstreamOAuthFlowStarted");function Ki(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=q(e.serverUrl);r!==void 0&&(t.serverHost=r);let o=e.error instanceof h?e.error.extensionMembers?.[g]:void 0;typeof o=="string"&&(t.code=o),G(t,"error",e.error),N()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(Ki,"logUpstreamOAuthFlowFailed");function Wi(e,t){return e.configuredAuthorizationScope??t.requestedScope}n(Wi,"readAuthorizationRequestScope");async function Vi(e,t){e.applyChallengeScope(t.requestedScope),Zi({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:$i(t.upstreamServerId)},o=Wi(e,t);return o!==void 0&&(r.scope=o),await Zr(e,r)}catch(r){Ki({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=fl({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(Vi,"runUpstreamOAuth");async function Rl(e,t){e.applyChallengeScope(t.requestedScope),Zi({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:$i(t.upstreamServerId)},o=Wi(e,t);o!==void 0&&(r.scope=o);try{return await Zr(e,r)}catch(i){throw Ki({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:i}),i}}n(Rl,"exchangeUpstreamAuthorizationCode");async function Yi(e,t){let r=await Vi(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new h({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new h({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Yi,"requireUpstreamAuthorizationRedirect");async function Xi(e){let t=Pt(e.connection),r=!!e.forceRefresh,o=!r&&t==="usable",i=N(),a=i?await Xe({owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}):void 0;if(i?.debug({event:"upstream_oauth_refresh_decision",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,ownerMode:e.target.owner.mode,connectionFingerprint:a,connectionId:e.connection?.id,accessTokenState:t,forceRefresh:r,willRefresh:!o,expiresAt:e.connection?.expiresAt,connectionUpdatedAt:e.connection?.updatedAt},o?"Reusing stored upstream access token":"Refreshing upstream credential"),o)return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let s;try{s=await Vi(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(c){if(e.connection===void 0||!ml(c))throw c;return i?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:c.errorCode,connectionFingerprint:a,connectionId:e.connection.id,rejectedRefreshTokenFingerprint:e.provider.usedRefreshTokenFingerprint,connectionUpdatedAt:e.connection.updatedAt,connectionExpiresAt:e.connection.expiresAt},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),{kind:"connect_required",payload:await Fi({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(s==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(s!=="REDIRECT")throw new h({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${s}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new h({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}});return{kind:"connect_required",payload:await Fi({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}n(Xi,"authorizeUpstreamOAuthSession");async function Il(e){let t=await lr(e.stateToken),r=await R().consumeUpstreamOAuthState({id:t.id,now:I(new Date)}),o=Cl(r);return Sl({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),vl(o),o}n(Il,"consumeStoredCallbackState");function Cl(e){switch(e.kind){case"consumed":throw new h({message:"OAuth state has already been used",extensionMembers:{[g]:"oauth_state_reused"}});case"missing":throw new h({message:"OAuth state is missing or expired",extensionMembers:{[g]:"oauth_state_expired"}});case"available":return e.record}}n(Cl,"readConsumedCallbackState");function Sl(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.operationId===e.signedState.operationId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw new h({message:"OAuth callback did not match the initiating request",extensionMembers:{[g]:"oauth_callback_mismatch"}})}n(Sl,"assertStoredCallbackStateMatches");function vl(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new h({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}})}n(vl,"assertStoredCallbackStateFresh");async function Fi(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),qi(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),pr(t)}n(Fi,"buildOAuthConnectRequiredResponse");async function Qi(e){let t=await Il({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Zt(t),[o]=await R().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),i={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};o!==void 0&&(i.connection=o);let a=new De(i),s=await Rl(a,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(s==="AUTHORIZED")return t;throw s!=="REDIRECT"?new h({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${s}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new h({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Qi,"finishUpstreamOAuthCallback");Z();import{importPKCS8 as Al,SignJWT as kl}from"jose";var ta=1e4,ra=64*1024,na=2,xl=300,ne=d.string().min(1),Tl=d.object({access_token:ne,issued_token_type:d.literal(Ur),token_type:d.string().optional(),expires_in:d.number().int().positive().optional(),scope:ne.optional()}).passthrough(),Ul=d.object({id_token:ne,token_type:ne.optional(),expires_in:d.number().int().positive().optional(),refresh_token:ne.optional(),scope:ne.optional()}).passthrough(),Pl=d.object({access_token:ne,token_type:ne,expires_in:d.number().int().positive().optional(),scope:ne.optional(),resource:ne.optional(),refresh_token:ne.optional()}).passthrough();function ea(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(ea,"formEncodeClientCredential");function El(e){return e.replaceAll("\\n",`
25
+ import{$ as d,$b as Pc,$c as qr,Ab as K,Ac as wo,Ad as v,Bb as eo,Bc as ee,Bd as F,Cb as to,Cc as L,Cd as le,Db as M,Dc as bo,Dd as T,Eb as ro,Ec as Ro,Ed as Qt,Fb as Le,Fc as I,Fd as Dc,Gb as no,Gc as de,Gd as jc,Hb as Ne,Hc as $e,Ib as g,Ic as G,Jb as Je,Jc as q,Kb as Ge,Kc as Io,Lb as _e,Lc as N,Mb as we,Mc as Co,Nb as Nt,Nc as Re,Ob as oo,Oc as Tr,P as $n,Pb as re,Pc as Kt,Q as p,Qb as io,Qc as Ur,R as Zn,Rb as ce,Rc as Wt,S as Ar,Sb as b,Sc as pt,T as se,Tb as Jt,Tc as Ze,U as Kn,Ub as J,Uc as So,V as _,Vb as be,Vc as ue,W as ye,Wb as Ac,Wc as Pr,X as Lt,Xb as kc,Xc as Er,Y as Wn,Yb as xc,Yc as vo,Z as Vn,Zb as Tc,Zc as Vt,_ as Yn,_b as Uc,_c as Or,aa as Z,ac as Ec,ad as Ao,bc as Oc,bd as D,cc as qc,cd as ko,dc as Mc,dd as xo,ec as ao,ed as Mr,fc as so,fd as To,ga as Xn,gc as co,gd as Uo,hc as Gt,hd as Dr,i as ae,ic as kr,id as Po,jc as Ft,jd as Pe,kc as $t,kd as Eo,lc as dt,ld as mt,mc as uo,md as Oo,nc as lo,nd as Yt,oc as po,od as ft,pc as ut,pd as qo,qc as mo,qd as Mo,r as Ue,rc as Fe,rd as Do,s as Jn,sc as fo,sd as jo,tc as xr,td as zo,u as Gn,uc as ho,ud as Ho,vc as lt,vd as Bo,wc as Zt,wd as Xt,xc as go,xd as Lo,y as Fn,yc as yo,yd as No,z as Bt,zb as Qn,zc as _o,zd as R}from"../chunk-IC7XGD5C.js";import"../chunk-4MNJC7E2.js";import{a as C}from"../chunk-4QJJMELB.js";import{$ as Q,a as n,aa as h,ba as A,ca as Nn,da as Ht}from"../chunk-DSZS6PZJ.js";Z();function zc(e){let t=$t.safeParse(e);return t.success?t.data.id:void 0}n(zc,"parseJsonRpcRequestId");function Jo(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return zc(t)}catch{return}}n(Jo,"readJsonRpcRequestIdFromBody");function er(e){return uo.parse({jsonrpc:Ft,...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(er,"jsonRpcErrorResponse");function Go(e){return new po([lo.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Go,"urlElicitationRequiredError");var rr=d.record(d.string(),d.unknown()),Hc=d.record(d.string(),d.unknown()),Ie=d.array(d.string().min(1)).min(1).optional(),Bc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),annotations:Hc.optional(),_meta:rr.optional(),roles:Ie,groups:Ie,public:d.boolean().optional()}).strict(),Lc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),_meta:rr.optional(),roles:Ie,groups:Ie,public:d.boolean().optional()}).strict(),Nc=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:rr.optional(),roles:Ie,groups:Ie,public:d.boolean().optional()}).strict(),Jc=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:rr.optional(),roles:Ie,groups:Ie,public:d.boolean().optional()}).strict(),Gc=d.array(d.union([d.string(),Bc])),Fc=d.array(d.union([d.string(),Lc])),$c=d.array(d.union([d.string(),Nc])),Zc=d.array(d.union([d.string(),Jc])),Kc=d.object({module:d.unknown(),export:d.string().min(1)}).strict(),Wc=d.object({mode:d.enum(["allPublic","rolesAndGroups","function"]).optional(),roleClaim:d.string().min(1).optional(),groupClaim:d.string().min(1).optional(),identifier:Kc.optional()}).strict(),Vc=d.object({tools:Gc.optional(),prompts:Fc.optional(),resources:$c.optional(),resourceTemplates:Zc.optional(),accessControl:Wc.optional()}).strict(),Ce=[{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 Yc(e,t){return eo(Vc,e,`MCP capability filter policy "${t}"`)}n(Yc,"parseMcpCapabilityFilterOptions");function z(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(z,"isRecord");function Xc(e,t){if(!z(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(Xc,"readParamString");function zr(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(zr,"readRequestId");function Vo(e){return e===void 0?void 0:JSON.stringify(e)}n(Vo,"requestIdKey");function Fo(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}n(Fo,"asStringArray");function $o(e,t){if(!z(e))return[];let r=t in e?e[t]:t.split(".").reduce((o,i)=>z(o)?o[i]:void 0,e);return Array.isArray(r)?r.filter(o=>typeof o=="string"):typeof r=="string"?r.split(/\s+/).filter(o=>o.length>0):[]}n($o,"readClaimValues");function Hr(e,t){if(typeof e=="string")return{key:e,public:!1};if(!z(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:Fo(e.roles),groups:Fo(e.groups),public:e.public===!0}}n(Hr,"normalizeEntry");function Qc(e,t,r){if(e.public)return!0;let o=e.roles??[],i=e.groups??[];return o.length===0&&i.length===0?!1:o.some(a=>t.has(a))||i.some(a=>r.has(a))}n(Qc,"isCallerAllowed");function tr(e,t,r,o){if(e===void 0)return;let i=[];for(let a of e){let s=Hr(a,t);s!==void 0&&Qc(s,r,o)&&i.push(s.key)}return i}n(tr,"allowedKeys");var Yo=n((e,t,r)=>{let o=r.accessControl?.roleClaim??"roles",i=r.accessControl?.groupClaim??"groups",a=new Set($o(e.user?.data,o)),s=new Set($o(e.user?.data,i));return{tools:tr(r.tools,"name",a,s),prompts:tr(r.prompts,"name",a,s),resources:tr(r.resources,"uri",a,s),resourceTemplates:tr(r.resourceTemplates,"uriTemplate",a,s)}},"claimsCapabilityResolver");function ed(e,t){let r=[];for(let o of Ce){let i=e[o.option];if(i!==void 0)for(let a of i){let s=Hr(a,o.itemProperty);if(s===void 0)continue;let c=(s.roles?.length??0)>0||(s.groups?.length??0)>0;s.public&&c?r.push(`${o.option} "${s.key}" (both)`):!s.public&&!c&&r.push(`${o.option} "${s.key}" (neither)`)}}if(r.length>0)throw new A(`MCP capability filter policy "${t}" - with accessControl.mode "rolesAndGroups", every capability must set roles/groups OR "public": true (not both, not neither): ${r.join(", ")}`)}n(ed,"assertClassified");function td(e,t){let r=[];for(let o of Ce){let i=e[o.option];if(i!==void 0)for(let a of i){let s=Hr(a,o.itemProperty);s!==void 0&&((s.roles?.length??0)>0||(s.groups?.length??0)>0||s.public)&&r.push(`${o.option} "${s.key}"`)}}if(r.length>0)throw new A(`MCP capability filter policy "${t}" - accessControl.mode is "allPublic" (the default) but these capabilities set roles/groups/public; set accessControl.mode to "rolesAndGroups" or remove the markup: ${r.join(", ")}`)}n(td,"assertNoMarkup");function rd(e,t){let r=e.identifier;if(r===void 0)throw new A(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);if(r.module===null||typeof r.module!="object")throw new A(`MCP capability filter policy "${t}" - accessControl.identifier.module must reference a module, e.g. $import(./modules/mcp-access-control)`);if(!r.export)throw new A(`MCP capability filter policy "${t}" - accessControl.identifier.export must be specified`);let o=r.module[r.export];if(typeof o!="function")throw new A(`MCP capability filter policy "${t}" - accessControl.identifier must resolve to a valid function`);let i=o;return async(a,s,c)=>{let u=await i(a,s,c);if(u==null)throw new h(`MCP capability filter policy "${t}" - accessControl resolver returned no value; return an AllowedCapabilities object (use empty arrays to deny)`);if(typeof u!="object"||Array.isArray(u))throw new h(`MCP capability filter policy "${t}" - accessControl resolver must return an AllowedCapabilities object`);return u}}n(rd,"buildCustomResolver");function nd(e,t){let r=e.accessControl,o=r?.mode??"allPublic";if(o==="function"){if(r===void 0)throw new A(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);return rd(r,t)}if(o==="rolesAndGroups")return ed(e,t),Yo;td(e,t)}n(nd,"buildCapabilityResolver");function od(e){let t={};for(let r of Ce){let o=e[r.option];if(o===void 0)continue;let i=new Map;for(let a of o){let s=dd(a,r.itemProperty);s!==void 0&&i.set(s.key,s)}t[r.option]=i}return t}n(od,"buildProjectionMaps");function Br(e){return Ce.find(t=>t.listMethod===e)}n(Br,"findListRule");function id(e){return e.requests.some(t=>{if(!z(t))return!1;let r=Br(t.method);return r!==void 0&&e.projectionMaps[r.option]!==void 0})}n(id,"shouldFilterListResponses");function ad(e){return e.requests.some(t=>z(t)?Ce.some(r=>e.projectionMaps[r.option]===void 0?!1:r.listMethod===t.method||r.directMethods.some(o=>o.method===t.method)):!1)}n(ad,"requestTouchesConfiguredCapability");function sd(e){for(let t of Ce){let r=e.projectionMaps[t.option];if(r!==void 0)for(let o of t.directMethods){if(e.request.method!==o.method)continue;let i=Xc(e.request.params,o.paramProperty);if(i===void 0)continue;let a=e.allowedSets?.[t.option];if(!r.has(i)||a!==void 0&&!a.has(i))return{id:zr(e.request)}}}}n(sd,"findDisallowedDirectAccess");function cd(e){return Response.json(er({id:e,error:{code:dt.MethodNotFound,message:"Method not found"}}))}n(cd,"methodNotFoundResponse");function dd(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!z(e))return;let r=e[t];if(typeof r!="string")return;let o={...e};return delete o.roles,delete o.groups,delete o.public,{key:r,overlay:o}}n(dd,"buildProjection");function Zo(e){let t=e.base[e.property],r=e.overlay[e.property];return z(r)?z(t)?{...t,...r}:r:t}n(Zo,"mergeRecordProperty");function ud(e,t){let r={...e,...t.overlay},o=Zo({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let i=Zo({base:e,overlay:t.overlay,property:"_meta"});return i!==void 0&&(r._meta=i),r}n(ud,"applyProjection");function Ko(e,t,r,o){if(!z(e))return e;let i=e.result;if(!z(i))return e;let a=i[t.resultProperty];return!Array.isArray(a)||!a.every(s=>z(s)&&typeof s[t.itemProperty]=="string")?e:{...e,result:{...i,[t.resultProperty]:a.flatMap(s=>{if(!z(s))return[];let c=s[t.itemProperty];if(typeof c!="string")return[];if(o!==void 0&&!o.has(c))return[];let u=r.get(c);return u===void 0?[]:[ud(s,u)]})}}}n(Ko,"filterAndProjectItems");function ld(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!z(r))continue;let o=Br(r.method),i=zr(r),a=Vo(i);o!==void 0&&a!==void 0&&t.set(a,o)}return t}n(ld,"buildListRulesByResponseId");function pd(e){if(Array.isArray(e.responseBody)){let o=ld(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(i=>{if(!z(i)||"error"in i)return i;let a=Vo(zr(i)),s=a===void 0?void 0:o.get(a),c=s===void 0?void 0:e.projectionMaps[s.option];return s===void 0||c===void 0?i:Ko(i,s,c,e.allowedSets?.[s.option])})}if(!z(e.requestBody)||!z(e.responseBody)||"error"in e.responseBody)return e.responseBody;let t=Br(e.requestBody.method),r=t===void 0?void 0:e.projectionMaps[t.option];return t===void 0||r===void 0?e.responseBody:Ko(e.responseBody,t,r,e.allowedSets?.[t.option])}n(pd,"filterJsonRpcResponse");async function Wo(e){return e.clone().json()}n(Wo,"readJson");function md(e){return e.headers.get("content-type")?.includes("json")??!1}n(md,"isJsonResponse");var jr=class extends Bt{static{n(this,"McpCapabilityFilterInboundPolicy")}static policyType="mcp-capability-filter";#e;#r;#n;#t;constructor(t,r){let o=Yc(t,r);super(o,r),this.#r=o,this.#n=r,this.#e=od(o),this.#t=nd(o,r)}async handler(t,r){let o;try{o=await Wo(t)}catch{return t}let i=Array.isArray(o)?o:[o],a=this.#t!==void 0&&ad({requests:i,projectionMaps:this.#e})?await this.#o(t,r):void 0;for(let s of i){if(!z(s))continue;let c=sd({request:s,projectionMaps:this.#e,allowedSets:a});if(c!==void 0)return cd(c.id)}return id({requests:i,projectionMaps:this.#e})&&r.addResponseSendingHook(async s=>{if(!md(s))return s;let c;try{c=await Wo(s)}catch{return s}let u=pd({requestBody:o,responseBody:c,projectionMaps:this.#e,allowedSets:a});if(u===c)return s;let l=new Headers(s.headers);return l.delete("content-length"),new Response(JSON.stringify(u),{status:s.status,statusText:s.statusText,headers:l})}),t}async#o(t,r){let o=this.#t;if(o===void 0)return{};let i;try{i=await o(t,r,this.#r)}catch(s){r.log.error(`MCP capability filter policy "${this.#n}" - access-control resolver threw; denying configured capabilities`,s);let c={};for(let u of Ce)this.#e[u.option]!==void 0&&(c[u.option]=new Set);return c}let a={};for(let s of Ce){let c=this.#e[s.option];if(c===void 0)continue;let u=i[s.option];if(u===void 0)continue;let l=new Set;if(Array.isArray(u))for(let m of u)typeof m=="string"&&c.has(m)&&l.add(m);a[s.option]=l}return a}};var Lr;Lr=globalThis.crypto;async function fd(e){return(await Lr).getRandomValues(new Uint8Array(e))}n(fd,"getRandomValues");async function hd(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await fd(e-o.length);for(let a of i)a<r&&(o+=t[a%t.length])}return o}n(hd,"random");async function gd(e){return await hd(e)}n(gd,"generateVerifier");async function yd(e){let t=await(await Lr).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(yd,"generateChallenge");async function Nr(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await gd(e),r=await yd(t);return{code_verifier:t,code_challenge:r}}n(Nr,"pkceChallenge");Z();var H=Zn().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Vn.custom,message:"URL must be parseable",fatal:!0}),$n}).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"}),nr=Lt({resource:p().url(),authorization_servers:_(H).optional(),jwks_uri:p().url().optional(),scopes_supported:_(p()).optional(),bearer_methods_supported:_(p()).optional(),resource_signing_alg_values_supported:_(p()).optional(),resource_name:p().optional(),resource_documentation:p().optional(),resource_policy_uri:p().url().optional(),resource_tos_uri:p().url().optional(),tls_client_certificate_bound_access_tokens:se().optional(),authorization_details_types_supported:_(p()).optional(),dpop_signing_alg_values_supported:_(p()).optional(),dpop_bound_access_tokens_required:se().optional()}),ht=Lt({issuer:p(),authorization_endpoint:H,token_endpoint:H,registration_endpoint:H.optional(),scopes_supported:_(p()).optional(),response_types_supported:_(p()),response_modes_supported:_(p()).optional(),grant_types_supported:_(p()).optional(),token_endpoint_auth_methods_supported:_(p()).optional(),token_endpoint_auth_signing_alg_values_supported:_(p()).optional(),service_documentation:H.optional(),revocation_endpoint:H.optional(),revocation_endpoint_auth_methods_supported:_(p()).optional(),revocation_endpoint_auth_signing_alg_values_supported:_(p()).optional(),introspection_endpoint:p().optional(),introspection_endpoint_auth_methods_supported:_(p()).optional(),introspection_endpoint_auth_signing_alg_values_supported:_(p()).optional(),code_challenge_methods_supported:_(p()).optional(),client_id_metadata_document_supported:se().optional()}),_d=Lt({issuer:p(),authorization_endpoint:H,token_endpoint:H,userinfo_endpoint:H.optional(),jwks_uri:H,registration_endpoint:H.optional(),scopes_supported:_(p()).optional(),response_types_supported:_(p()),response_modes_supported:_(p()).optional(),grant_types_supported:_(p()).optional(),acr_values_supported:_(p()).optional(),subject_types_supported:_(p()),id_token_signing_alg_values_supported:_(p()),id_token_encryption_alg_values_supported:_(p()).optional(),id_token_encryption_enc_values_supported:_(p()).optional(),userinfo_signing_alg_values_supported:_(p()).optional(),userinfo_encryption_alg_values_supported:_(p()).optional(),userinfo_encryption_enc_values_supported:_(p()).optional(),request_object_signing_alg_values_supported:_(p()).optional(),request_object_encryption_alg_values_supported:_(p()).optional(),request_object_encryption_enc_values_supported:_(p()).optional(),token_endpoint_auth_methods_supported:_(p()).optional(),token_endpoint_auth_signing_alg_values_supported:_(p()).optional(),display_values_supported:_(p()).optional(),claim_types_supported:_(p()).optional(),claims_supported:_(p()).optional(),service_documentation:p().optional(),claims_locales_supported:_(p()).optional(),ui_locales_supported:_(p()).optional(),claims_parameter_supported:se().optional(),request_parameter_supported:se().optional(),request_uri_parameter_supported:se().optional(),require_request_uri_registration:se().optional(),op_policy_uri:H.optional(),op_tos_uri:H.optional(),client_id_metadata_document_supported:se().optional()}),or=ye({..._d.shape,...ht.pick({code_challenge_methods_supported:!0}).shape}),Ke=ye({access_token:p(),id_token:p().optional(),token_type:p(),expires_in:Yn.number().optional(),scope:p().optional(),refresh_token:p().optional()}).strip(),Qo=ye({error:p(),error_description:p().optional(),error_uri:p().optional()}),Xo=H.optional().or(Wn("").transform(()=>{})),wd=ye({redirect_uris:_(H),token_endpoint_auth_method:p().optional(),grant_types:_(p()).optional(),response_types:_(p()).optional(),client_name:p().optional(),client_uri:H.optional(),logo_uri:Xo,scope:p().optional(),contacts:_(p()).optional(),tos_uri:Xo,policy_uri:p().optional(),jwks_uri:H.optional(),jwks:Kn().optional(),software_id:p().optional(),software_version:p().optional(),software_statement:p().optional()}).strip(),ir=ye({client_id:p(),client_secret:p().optional(),client_id_issued_at:Ar().optional(),client_secret_expires_at:Ar().optional()}).strip(),gt=wd.merge(ir),cg=ye({error:p(),error_description:p().optional()}).strip(),dg=ye({token:p(),token_type_hint:p().optional()}).strip();function ei(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(ei,"resourceUrlFromServerUrl");function ti({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",a=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return i.startsWith(a)}n(ti,"checkResourceAllowed");var k=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}},yt=class extends k{static{n(this,"InvalidRequestError")}};yt.errorCode="invalid_request";var Ee=class extends k{static{n(this,"InvalidClientError")}};Ee.errorCode="invalid_client";var Oe=class extends k{static{n(this,"InvalidGrantError")}};Oe.errorCode="invalid_grant";var qe=class extends k{static{n(this,"UnauthorizedClientError")}};qe.errorCode="unauthorized_client";var _t=class extends k{static{n(this,"UnsupportedGrantTypeError")}};_t.errorCode="unsupported_grant_type";var wt=class extends k{static{n(this,"InvalidScopeError")}};wt.errorCode="invalid_scope";var bt=class extends k{static{n(this,"AccessDeniedError")}};bt.errorCode="access_denied";var pe=class extends k{static{n(this,"ServerError")}};pe.errorCode="server_error";var Rt=class extends k{static{n(this,"TemporarilyUnavailableError")}};Rt.errorCode="temporarily_unavailable";var It=class extends k{static{n(this,"UnsupportedResponseTypeError")}};It.errorCode="unsupported_response_type";var Ct=class extends k{static{n(this,"UnsupportedTokenTypeError")}};Ct.errorCode="unsupported_token_type";var St=class extends k{static{n(this,"InvalidTokenError")}};St.errorCode="invalid_token";var vt=class extends k{static{n(this,"MethodNotAllowedError")}};vt.errorCode="method_not_allowed";var At=class extends k{static{n(this,"TooManyRequestsError")}};At.errorCode="too_many_requests";var Me=class extends k{static{n(this,"InvalidClientMetadataError")}};Me.errorCode="invalid_client_metadata";var kt=class extends k{static{n(this,"InsufficientScopeError")}};kt.errorCode="insufficient_scope";var xt=class extends k{static{n(this,"InvalidTargetError")}};xt.errorCode="invalid_target";var ri={[yt.errorCode]:yt,[Ee.errorCode]:Ee,[Oe.errorCode]:Oe,[qe.errorCode]:qe,[_t.errorCode]:_t,[wt.errorCode]:wt,[bt.errorCode]:bt,[pe.errorCode]:pe,[Rt.errorCode]:Rt,[It.errorCode]:It,[Ct.errorCode]:Ct,[St.errorCode]:St,[vt.errorCode]:vt,[At.errorCode]:At,[Me.errorCode]:Me,[kt.errorCode]:kt,[xt.errorCode]:xt};function bd(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(bd,"isClientAuthMethod");var Jr="code",Gr="S256";function Rd(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&bd(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(Rd,"selectClientAuthMethod");function Id(e,t,r,o){let{client_id:i,client_secret:a}=t;switch(e){case"client_secret_basic":Cd(i,a,r);return;case"client_secret_post":Sd(i,a,o);return;case"none":vd(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(Id,"applyClientAuthentication");function Cd(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(Cd,"applyBasicAuth");function Sd(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(Sd,"applyPostAuth");function vd(e,t){t.set("client_id",e)}n(vd,"applyPublicAuth");async function oi(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Qo.parse(JSON.parse(r)),{error:i,error_description:a,error_uri:s}=o,c=ri[i]||pe;return new c(a||"",s)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new pe(i)}}n(oi,"parseErrorResponse");async function Zr(e,t){try{return await Fr(e,t)}catch(r){if(r instanceof Ee||r instanceof qe)return await e.invalidateCredentials?.("all"),await Fr(e,t);if(r instanceof Oe)return await e.invalidateCredentials?.("tokens"),await Fr(e,t);throw r}}n(Zr,"auth");async function Fr(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:i,fetchFn:a}){let s=await e.discoveryState?.(),c,u,l,m=i;if(!m&&s?.resourceMetadataUrl&&(m=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(u=s.authorizationServerUrl,c=s.resourceMetadata,l=s.authorizationServerMetadata??await si(u,{fetchFn:a}),!c)try{c=await ai(t,{resourceMetadataUrl:m},a)}catch{}(l!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:m?.toString(),resourceMetadata:c,authorizationServerMetadata:l})}else{let O=await Pd(t,{resourceMetadataUrl:m,fetchFn:a});u=O.authorizationServerUrl,l=O.authorizationServerMetadata,c=O.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:m?.toString(),resourceMetadata:c,authorizationServerMetadata:l})}let w=await Ad(t,e,c),P=o||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,y=await Promise.resolve(e.clientInformation());if(!y){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let O=l?.client_id_metadata_document_supported===!0,j=e.clientMetadataUrl;if(j&&!Kr(j))throw new Me(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${j}`);if(O&&j)y={client_id:j},await e.saveClientInformation?.(y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Ln=await Dd(u,{metadata:l,clientMetadata:e.clientMetadata,scope:P,fetchFn:a});await e.saveClientInformation(Ln),y=Ln}}let E=!e.redirectUrl;if(r!==void 0||E){let O=await Md(e,u,{metadata:l,resource:w,authorizationCode:r,fetchFn:a});return await e.saveTokens(O),"AUTHORIZED"}let x=await e.tokens();if(x?.refresh_token)try{let O=await qd(u,{metadata:l,clientInformation:y,refreshToken:x.refresh_token,resource:w,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(O),"AUTHORIZED"}catch(O){if(!(!(O instanceof k)||O instanceof pe))throw O}let B=e.state?await e.state():void 0,{authorizationUrl:Be,codeVerifier:X}=await Ed(u,{metadata:l,clientInformation:y,state:B,redirectUrl:e.redirectUrl,scope:P,resource:w});return await e.saveCodeVerifier(X),await e.redirectToAuthorization(Be),"REDIRECT"}n(Fr,"authInternal");function Kr(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(Kr,"isHttpsUrl");async function Ad(e,t,r){let o=ei(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!ti({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(Ad,"selectResourceURL");function ii(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let i=$r(e,"resource_metadata")||void 0,a;if(i)try{a=new URL(i)}catch{}let s=$r(e,"scope")||void 0,c=$r(e,"error")||void 0;return{resourceMetadataUrl:a,scope:s,error:c}}n(ii,"extractWWWAuthenticateParams");function $r(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=r.match(o);return i?i[1]||i[2]:null}n($r,"extractFieldFromWwwAuth");async function ai(e,t,r=fetch){let o=await Td(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 nr.parse(await o.json())}n(ai,"discoverOAuthProtectedResourceMetadata");async function Wr(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Wr(e,void 0,r):void 0;throw o}}n(Wr,"fetchWithCorsRetry");function kd(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(kd,"buildWellKnownPath");async function ni(e,t,r=fetch){return await Wr(e,{"MCP-Protocol-Version":t},r)}n(ni,"tryMetadataDiscovery");function xd(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(xd,"shouldAttemptFallback");async function Td(e,t,r,o){let i=new URL(e),a=o?.protocolVersion??kr,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let u=kd(t,i.pathname);s=new URL(u,o?.metadataServerUrl??i),s.search=i.search}let c=await ni(s,a,r);if(!o?.metadataUrl&&xd(c,i.pathname)){let u=new URL(`/.well-known/${t}`,i);c=await ni(u,a,r)}return c}n(Td,"discoverMetadataWithFallback");function Ud(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let i=t.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:"oidc"}),o.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(Ud,"buildDiscoveryUrls");async function si(e,{fetchFn:t=fetch,protocolVersion:r=kr}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=Ud(e);for(let{url:a,type:s}of i){let c=await Wr(a,o,t);if(c){if(!c.ok){if(await c.body?.cancel(),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}return s==="oauth"?ht.parse(await c.json()):or.parse(await c.json())}}}n(si,"discoverAuthorizationServerMetadata");async function Pd(e,t){let r,o;try{r=await ai(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch{}o||(o=String(new URL("/",e)));let i=await si(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(Pd,"discoverOAuthServerInfo");async function Ed(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:i,state:a,resource:s}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Jr))throw new Error(`Incompatible auth server: does not support response type ${Jr}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Gr))throw new Error(`Incompatible auth server: does not support code challenge method ${Gr}`)}else c=new URL("/authorize",e);let u=await Nr(),l=u.code_verifier,m=u.code_challenge;return c.searchParams.set("response_type",Jr),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",m),c.searchParams.set("code_challenge_method",Gr),c.searchParams.set("redirect_uri",String(o)),a&&c.searchParams.set("state",a),i&&c.searchParams.set("scope",i),i?.includes("offline_access")&&c.searchParams.append("prompt","consent"),s&&c.searchParams.set("resource",s.href),{authorizationUrl:c,codeVerifier:l}}n(Ed,"startAuthorization");function Od(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(Od,"prepareAuthorizationCodeRequest");async function ci(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:i,resource:a,fetchFn:s}){let c=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(a&&r.set("resource",a.href),i)await i(u,r,c,t);else if(o){let m=t?.token_endpoint_auth_methods_supported??[],w=Rd(o,m);Id(w,o,u,r)}let l=await(s??fetch)(c,{method:"POST",headers:u,body:r});if(!l.ok)throw await oi(l);return Ke.parse(await l.json())}n(ci,"executeTokenRequest");async function qd(e,{metadata:t,clientInformation:r,refreshToken:o,resource:i,addClientAuthentication:a,fetchFn:s}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),u=await ci(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:a,resource:i,fetchFn:s});return{refresh_token:o,...u}}n(qd,"refreshAuthorization");async function Md(e,t,{metadata:r,resource:o,authorizationCode:i,fetchFn:a}={}){let s=e.clientMetadata.scope,c;if(e.prepareTokenRequest&&(c=await e.prepareTokenRequest(s)),!c){if(!i)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let l=await e.codeVerifier();c=Od(i,l,e.redirectUrl)}let u=await e.clientInformation();return ci(t,{metadata:r,tokenRequestParams:c,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(Md,"fetchToken");async function Dd(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");a=new URL(t.registration_endpoint)}else a=new URL("/register",e);let s=await(i??fetch)(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!s.ok)throw await oi(s);return gt.parse(await s.json())}n(Dd,"registerClient");var Vr="zuplo.com",jd=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),zd=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function di(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(di,"s2FaviconHref");function Hd(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(Hd,"strictFaviconHref");var ar=di(Vr);function Yr(e){let t=e.toLowerCase();return t===Vr||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?di(Vr):Hd(e)}n(Yr,"resolveIconHref");function Bd(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(Bd,"hostnameFromHost");function Ld(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(Ld,"isLocalOrAddressHost");function Nd(e){let t=Bd(e).toLowerCase().replace(/\.$/,"");if(Ld(t)||zd.some(a=>t===a.slice(1)||t.endsWith(a)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let o=r.slice(-2).join("."),i=jd.has(o)?3:2;return r.slice(-i).join(".")}n(Nd,"inferFaviconDomain");function Xr(e){return{src:Yr(Nd(e)),mimeType:"image/png",sizes:["128x128"]}}n(Xr,"resolveMcpFaviconIcon");function sr(e){try{return Xr(new URL(e).host)}catch{return}}n(sr,"resolveMcpFaviconIconFromUrl");function Se(e){let t=ee().connectionsById.get(e);if(!t)throw new A(`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(Se,"getUpstreamServerConfig");function cr(e){let t=ee().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new A(`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(cr,"getUpstreamAuthConfig");function We(e,t){let r=cr({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new A(`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(We,"requireUpstreamOAuthConfig");function ui(e,t){let r=cr({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new A(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(ui,"requireUpstreamIdJagConfig");function li(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(li,"mergeAbortSignals");async function Jd(e){try{await e.cancel()}catch{}}n(Jd,"cancelReader");async function dr(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],i=0,a=await r.read();for(;!a.done;){let u=a.value;if(i+=u.byteLength,i>t.maxBytes)throw await Jd(r),t.createLimitError();o.push(u),a=await r.read()}let s=new Uint8Array(i),c=0;for(let u of o)s.set(u,c),c+=u.byteLength;return s}n(dr,"readBoundedByteStream");var Gd=2,Fd=1024*1024,$d=1e4,Zd=new Set([301,302,303,307,308]),Kd=["authorization","proxy-authorization","cookie","cookie2"];function Qr(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Qr,"readRequestUrl");function Ve(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(Ve,"readRequestMethod");function Wd(e,t,r){let o=e.headers.get("content-length");if(!o)return;let i=Number.parseInt(o,10);if(Number.isFinite(i)&&i>t)throw new h({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}})}n(Wd,"assertContentLengthWithinLimit");async function Vd(e,t,r){return Wd(e,t,r),dr(e.body,{maxBytes:t,createLimitError:n(()=>new h({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}}),"createLimitError")})}n(Vd,"readBoundedResponseBody");function Yd(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(Yd,"responseFromBufferedBody");function Xd(e,t){if(!Zd.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(Xd,"resolveRedirectUrl");function pi(e,t){try{return t.validateUrl(e)}catch(r){throw new h({message:"Outbound URL was not allowed.",extensionMembers:{[g]:t.problemCode}},{cause:r})}}n(pi,"validateOutboundUrl");function Qd(e,t){throw e instanceof h&&Nt(e.extensionMembers?.[g])?e:new h({message:"Outbound fetch failed.",extensionMembers:{[g]:t}},{cause:e})}n(Qd,"normalizeFetchError");function Tt(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[o,i]of Object.entries(t.extra))i!==void 0&&(r[o]=i);t.error!==void 0&&G(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(Tt,"logOutboundFailure");async function eu(e,t,r,o,i,a,s){let c=Ve(r,o);try{return await t(r,o)}catch(u){let l=u instanceof DOMException&&u.name==="AbortError";Tt(e,{event:l?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:i,method:c,host:q(a),error:u,extra:{abortReason:s()}}),Qd(u,i)}}n(eu,"fetchWithNormalizedError");function tu(e){if(e.redirects>=e.maxRedirects)throw new h({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[g]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new h({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[g]:e.problemCode}})}n(tu,"assertRedirectAllowed");function ru(e,t){let r=new Headers(e);for(let o of Kd)r.delete(o);for(let o of t)r.delete(o);return r}n(ru,"stripCrossOriginHeaders");function nu(e,t,r,o,i){let a={...e,method:t,redirect:"manual",signal:r};return o&&(a.headers=ru(e.headers,i)),a}n(nu,"buildRedirectInit");function ou(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(ou,"buildInitialRequestInit");function iu(e){let t=Ve(e.currentInput,e.currentInit);tu({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=pi(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),i=r.origin!==o.origin,a=r.toString();return{currentInput:a,currentUrl:a,currentInit:nu(e.currentInit,t,e.signal,i,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(iu,"followRedirect");async function en(e,t,r){let o=r.problemCode??"invalid_request",i=r.maxRedirects??Gd,a=r.maxResponseBytes??Fd,s=r.timeoutMs??$d,c=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],l=r.context,m=new AbortController,w=li(m,t.signal),P=!1,y=setTimeout(()=>{P=!0,m.abort()},s),E=e,x=ou(e,t,m.signal),B;try{B=pi(Qr(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(X){throw Tt(l,{event:"outbound_url_blocked",problemCode:o,method:Ve(e,t),host:q(Qr(e)),error:X}),clearTimeout(y),w?.(),X}let Be=0;try{for(;;){let X=await eu(l,c,E,x,o,B,()=>P?`timeout_after_${s}ms`:void 0),O=Xd(X,B);if(O!==void 0)try{let j=iu({currentInput:E,currentInit:x,currentUrl:B,redirectUrl:O,redirects:Be,maxRedirects:i,problemCode:o,validateUrl:r.validateUrl,signal:m.signal,additionalCrossOriginStrippedHeaders:u});E=j.currentInput,x=j.currentInit,B=j.currentUrl,Be=j.redirects;continue}catch(j){throw Tt(l,{event:"outbound_redirect_blocked",problemCode:o,method:Ve(E,x),host:q(B),error:j,extra:{redirects:Be,maxRedirects:i,redirectTargetHost:q(O)}}),j}try{return Yd(X,await Vd(X,a,o))}catch(j){throw Tt(l,{event:"outbound_response_size_exceeded",problemCode:o,method:Ve(E,x),host:q(B),error:j,extra:{maxResponseBytes:a,status:X.status}}),j}}}finally{clearTimeout(y),w?.()}}n(en,"runSafeOutboundExchange");async function Ut(e,t,r){let o=await en(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(i){throw Tt(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Ve(e,t),host:q(Qr(e)),error:i,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new h({message:"Outbound JSON response could not be parsed.",extensionMembers:{[g]:r.problemCode??"invalid_request"}},{cause:i})}}n(Ut,"runSafeOutboundJsonExchange");function mi(e,t={},r={}){return en(e,t,{...r,validateUrl:mt})}n(mi,"fetchConfiguredOutbound");function fi(e,t={},r={}){return Ut(e,t,{...r,validateUrl:mt})}n(fi,"fetchConfiguredOutboundJson");function ur(e,t={},r={}){return Ut(e,t,{...r,validateUrl:Oo})}n(ur,"fetchIdentityProviderJson");function hi(e,t={},r={}){return Ut(e,t,{...r,validateUrl:Yt})}n(hi,"fetchCimdClientMetadataJson");function gi(e,t={},r={}){return Ut(e,t,{...r,validateUrl:ft})}n(gi,"fetchCimdClientJwksJson");Z();import{errors as Ii,jwtVerify as Ci,SignJWT as Si}from"jose";var $="zuplo-mcp-gateway",W=$,V="HS256";import{base64url as au}from"jose";var su=new TextEncoder,cu="MCP gateway could not initialize secure key material.",du=32,yi=new Map,_i=new Map,uu;function lu(){return uu??Nn.instance.authPrivateKey}n(lu,"readAuthPrivateKey");function wi(e){return new Q(cu,e===void 0?void 0:{cause:e})}n(wi,"createGeneratedKeyMaterialError");function bi(e,t){let r=au.decode(t);if(r.byteLength!==du)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(bi,"decodeJwkKeyField");function pu(e){let t=lu();if(!t)throw wi();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=bi("d",r.d);bi("x",r.x);let i=su.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),a=new Uint8Array(i.byteLength+o.byteLength);return a.set(i),a.set(o,i.byteLength),a}catch(r){throw wi(r)}}n(pu,"decodeGeneratedKeyMaterial");function mu(e){let t=yi.get(e);return t||(t=pu(e),yi.set(e,t)),t}n(mu,"getMasterKeyMaterial");async function oe(e){let t=_i.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(mu(e.keyMaterialPurpose));return _i.set(e.purpose,r),r}n(oe,"readCachedDerivedKey");var fu="SHA-256",hu=32,gu="zuplo-mcp-gateway:",yu=new TextEncoder,Ri=new WeakMap;async function ve(e,t){let r=Ri.get(e);r||(r=new Map,Ri.set(e,r));let o=r.get(t);if(o)return o;let i=await _u(e,t);return r.set(t,i),i}n(ve,"deriveGatewaySigningKey");async function _u(e,t){let r=F(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=yu.encode(`${gu}${t}`),a=await crypto.subtle.deriveBits({name:"HKDF",hash:fu,salt:new Uint8Array,info:F(i)},o,hu*8);return new Uint8Array(a)}n(_u,"hkdfExpand");var vi=900,wu=900,bu=ho.extend({id:zo}),Ru=bu.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),Ai=xr.extend({id:Ho,purpose:d.literal("browser_connect")}),Iu=xr.extend({purpose:d.literal("browser_connect")}),Cu=Ai.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ki=vi*1e3;async function xi(){return oe({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>ve(e,"oauth-state"),"derive")})}n(xi,"getOAuthStateKey");async function Ti(){return oe({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>ve(e,"browser-connect"),"derive")})}n(Ti,"getBrowserConnectKey");async function Ui(e){let t=Math.floor(Date.now()/1e3)+vi;return new Si(e).setProtectedHeader({alg:V,typ:"JWT"}).setIssuer($).setAudience(W).setIssuedAt().setExpirationTime(t).sign(await xi())}n(Ui,"signOAuthState");async function lr(e){try{let{payload:t}=await Ci(e,await xi(),{algorithms:[V],issuer:$,audience:W});return Ru.parse(t)}catch(t){throw t instanceof Ii.JWTExpired?new h({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new h({message:"OAuth state could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(lr,"verifyOAuthState");async function Pi(e){let t=Math.floor(Date.now()/1e3)+wu,r=Iu.parse(e),o=Ai.parse({...r,id:No()});return new Si(o).setProtectedHeader({alg:V,typ:"JWT"}).setIssuer($).setAudience(W).setIssuedAt().setExpirationTime(t).sign(await Ti())}n(Pi,"signBrowserConnectTicket");async function Ei(e){try{let{payload:t}=await Ci(e,await Ti(),{algorithms:[V],issuer:$,audience:W});return Cu.parse(t)}catch(t){throw t instanceof Ii.JWTExpired?new h({message:"Browser connect ticket has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new h({message:"Browser connect ticket could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(Ei,"verifyBrowserConnectTicket");async function Oi(e){if((await R().consumeBrowserConnectTicket({id:e.id,expiresAt:I(new Date(e.exp*1e3)),now:I(new Date)})).kind==="consumed")throw new h({message:"Browser connect ticket has already been used",extensionMembers:{[g]:"oauth_state_reused"}})}n(Oi,"consumeBrowserConnectTicket");function Su(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(Su,"buildConnectRequiredMessage");async function vu(e){let t=M(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 Pi({...lt(e),purpose:"browser_connect"})),r.toString()}n(vu,"buildGatewayBrowserTicketUrl");function Au(e){return L().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(Au,"buildGatewayConnectPath");async function tn(e){return vu({...e,path:Au(e.upstreamServerId),redirect:!0})}n(tn,"buildGatewayConnectUrl");async function pr(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 tn(t),message:Su(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(pr,"buildRedirectConnectRequiredResponse");function qi(e){return ku({...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(qi,"buildAdminConnectRequiredResponse");function ku(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(ku,"buildAdminSetupRequiredResponse");var Mi=12;async function Di(e){let t=await crypto.subtle.digest("SHA-256",F(new TextEncoder().encode(e)));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}n(Di,"sha256Hex");async function Ye(e){if(e)return(await Di(e)).slice(0,Mi)}n(Ye,"fingerprintSecret");async function Xe(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await Di(t)).slice(0,Mi)}n(Xe,"fingerprintConnectionIdentity");function Pt(e){return e?e.status!=="active"?"inactive":e.encryptedAccessToken?e.expiresAt&&new Date(e.expiresAt).getTime()<=Date.now()?"expired":"usable":"no_access_token":"no_connection"}n(Pt,"describeAccessTokenState");Z();var ji=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function xu(e,t){return e&&e.length>0?e.join(t):void 0}n(xu,"joinOAuthScopes");function Tu(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of ji)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(Tu,"sanitizeAuthorizationServerMetadata");function zi(e){let t=Tu(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(zi,"sanitizeOAuthDiscoveryState");function Hi(e){let t=new URL(e);for(let r of ji){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(Hi,"dedupeSingletonAuthorizationRequestParams");function mr(e){let t=new URL(e);return K(t)&&Qn(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(mr,"normalizeLoopbackOAuthRedirectUri");function Bi(e){return xu(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(Bi,"readProtectedResourceMetadataScope");function Uu(e){return`Zuplo MCP Gateway - ${e}`}n(Uu,"buildGatewayOAuthClientName");function Pu(e,t){return e&&e.length>0?e.join(t):void 0}n(Pu,"joinOAuthScopeList");function Eu(e){if(e.clientRegistration.mode!=="auto")return Pu(e.scopes,e.scopeDelimiter)}n(Eu,"readPublicClientMetadataScope");function rn(e){return new URL(L().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(rn,"buildOAuthClientMetadataDocumentUrl");function nn(e){let t=Se(e.upstreamServerId);return{client_name:Uu(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(nn,"buildGatewayOAuthClientMetadata");function Li(e,t,r){let o=We(t,r),i=Eu(o);return{client_id:rn({origin:e,upstreamServerId:t}),...nn({origin:e,upstreamServerId:t,redirectUri:mr(new URL(o.redirectPath,e)).toString(),scope:i})}}n(Li,"buildOAuthClientMetadataDocument");Z();import{base64url as Ae}from"jose";var Ou="SHA-256",Qe="AES-GCM",qu=12,an="zuplo-secret",sn=1,Ni="generated:auth_private_key:token-encryption",Mu=d.object({version:d.literal(sn),keyId:d.literal(Ni),algorithm:d.literal(Qe),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();async function on(){return oe({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(Ou,F(e));return crypto.subtle.importKey("raw",t,{name:Qe},!1,["encrypt","decrypt"])},"derive")})}n(on,"getEncryptionKey");function Ji(e){return F(new TextEncoder().encode(`${an}:v${e.version}:${e.keyId}`))}n(Ji,"getAssociatedData");function Du(e){return`${an}:v${e.version}:${Ae.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(Du,"encodeEnvelope");function ju(e){let t=`${an}:v${sn}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(Ae.decode(r));return Mu.parse(JSON.parse(o))}n(ju,"decodeEnvelope");async function me(e){let t=await on(),r=crypto.getRandomValues(new Uint8Array(qu)),o={version:sn,keyId:Ni},i=await crypto.subtle.encrypt({name:Qe,iv:r,additionalData:Ji(o)},t,new TextEncoder().encode(e));return Du({...o,algorithm:Qe,iv:Ae.encode(r),ciphertext:Ae.encode(new Uint8Array(i))})}n(me,"encryptSecret");async function ke(e){let t=ju(e);if(t){let s=await on(),c=await crypto.subtle.decrypt({name:Qe,iv:F(Ae.decode(t.iv)),additionalData:Ji(t)},s,F(Ae.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,o]=e.split(".");if(!r||!o)throw new Q("Encrypted payload is malformed");let i=await on(),a=await crypto.subtle.decrypt({name:Qe,iv:F(Ae.decode(r))},i,F(Ae.decode(o)));return new TextDecoder().decode(a)}n(ke,"decryptSecret");var zu=d.union([gt,ir]),Hu=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:nr.optional(),authorizationServerMetadata:d.union([ht,or]).optional()}).passthrough(),Bu="Bearer",Lu="__zuplo_refresh_only_upstream_access_token__";function Gi(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Gi,"splitScopes");function Nu(e){return Ne.parse(e)}n(Nu,"parsePkceCodeVerifier");function Ju(e){if(typeof e.expires_in=="number")return I(new Date(Date.now()+e.expires_in*1e3))}n(Ju,"readTokenExpiry");async function Gu(e){if(e!==void 0)return me(JSON.stringify(e))}n(Gu,"encryptJson");async function Fu(e,t){if(!e)return;let r=await ke(e);try{return t.parse(JSON.parse(r))}catch(o){throw new h({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:o})}}n(Fu,"decryptJson");function $u(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n($u,"clientInformationAllowsRedirectUri");function Zu(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(Zu,"clientInformationMatchesCurrentClientMetadataUrl");function Ku(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(Ku,"isUrlBasedClientInformation");function Wu(e,t){return t===void 0?e:{...e,scope:t}}n(Wu,"applyOAuthClientMetadataScope");function Vu(e,t){return Bi({state:e,delimiter:t})}n(Vu,"readResourceMetadataScope");function Yu(e,t){return e&&e.length>0?e.join(t):void 0}n(Yu,"joinOAuthScopeList");function Xu(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new A(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return gt.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(Xu,"buildManualOAuthClientInformation");function Qu(e,t){let r=rn({origin:new URL(t).origin,upstreamServerId:e});return Kr(r)?r:void 0}n(Qu,"buildClientMetadataUrl");function el(e){for(let t of e)if(t!==void 0)return t}n(el,"firstDefined");function tl(e){let t=We(e.target.upstreamServerId,e.target.authProfileId),r=Yu(t.scopes,t.scopeDelimiter),o=nn({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,promptOverride:t.prompt,configuredClientInformation:Xu({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let i=Qu(e.target.upstreamServerId,e.redirectUri);return i===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,promptOverride:t.prompt,clientMetadataUrl:i}}n(tl,"buildInitialOAuthClientSetup");function rl(e,t){if(t===void 0)return el([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(rl,"readEncryptedClientInformation");var De=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredScope;scopeDelimiter;promptOverride;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;connection;pendingState;encryptedClientInformation;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;connectionFingerprintValue;usedRefreshTokenFingerprintValue;constructor(t){let r=tl({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.promptOverride=r.promptOverride,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=rl(t,this.configuredClientInformation)}get authorizationUrl(){return this.authorizationUrlValue}get configuredAuthorizationScope(){return this.configuredScope}get usedRefreshTokenFingerprint(){return this.usedRefreshTokenFingerprintValue}async connectionFingerprint(){return this.connectionFingerprintValue===void 0&&(this.connectionFingerprintValue=await Xe({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return Wu(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return Ui({id:t.id,...lt({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,N()?.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"),!Ku({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Gu(t),await this.syncPendingState(!1)))}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=zi(Hu.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,N()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:q(r.authorizationServerUrl),resourceMetadataHost:q(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=Vu(r,this.scopeDelimiter);let o=r.resourceMetadata?.scopes_supported;if(this.configuredScope!==void 0&&o!==void 0){let i=Gi(this.configuredScope).filter(a=>!o.includes(a));i.length>0&&N()?.debug({event:"upstream_oauth_configured_scopes_not_advertised",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,unadvertisedScopes:i,scopesSupported:o},"Configured upstream OAuth scopes include values the resource metadata does not advertise")}}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Ke.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=this.connection,a=!r.refresh_token&&!!i?.encryptedRefreshToken,s=r.refresh_token?await me(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:Ke.parse({...r,refresh_token:await ke(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let c={id:this.connection?.id??Xt(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await me(r.access_token),encryptedRefreshToken:s,scopes:Gi(r.scope??this.readEffectiveScope()),expiresAt:Ju(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await R().upsertUpstreamConnection(c),N()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.connection.id,hasRefreshToken:!!s,priorStatus:i?.status,priorUpdatedAt:i?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await Ye(r.refresh_token),reusedSnapshotRefreshToken:a,scopeCount:c.scopes.length,expiresAt:c.expiresAt},"Upstream OAuth tokens persisted; upstream connection is active")}async redirectToAuthorization(t){let r=Hi(t);this.promptOverride===!1?r.searchParams.delete("prompt"):this.promptOverride!==void 0&&r.searchParams.set("prompt",this.promptOverride),this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:Nu(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new h({message:"OAuth code verifier is missing",extensionMembers:{[g]:"oauth_state_invalid"}});return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",o=t==="all"||t==="client",i=t==="all"||t==="discovery",a=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),i&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.challengeScope=void 0,this.inferredScope=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(a),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:Lo(),...lt({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()+ki)),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 R().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await Fu(this.encryptedClientInformation,zu)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&(!$u(t,this.redirectUriValue)||!Zu({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=ir.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"){N()?.debug({event:"upstream_oauth_tokens_not_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.connection?.id,status:this.connection?.status??"not_connected"},"Upstream OAuth tokens not loaded; connection is not active");return}let t=this.connection.encryptedAccessToken?await ke(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await ke(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=N();this.usedRefreshTokenFingerprintValue=o?await Ye(r):void 0,o?.debug({event:"upstream_oauth_tokens_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.connection.id,hasAccessToken:!!t,hasRefreshToken:!!r,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,expiresAt:this.connection.expiresAt},"Upstream OAuth tokens loaded from stored connection");let i=Ke.parse({access_token:t??Lu,token_type:Bu,refresh_token:r,scope:this.connection.scopes.length>0?this.connection.scopes.join(" "):void 0});return this.cachedTokens=i,i}async persistCredentialInvalidation(t){if(!this.connection)return;let r=this.connection.status,o=this.connection.updatedAt,i={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&&(i.status="reconsent_required",i.encryptedAccessToken=void 0,i.encryptedRefreshToken=void 0,i.scopes=[],i.expiresAt=void 0),i.metadata=this.readStoredOAuthPersistence(this.connection.metadata?.connectedBySubjectId),this.connection=await R().upsertUpstreamConnection(i);let a=N();if(a){let s={event:"upstream_oauth_credentials_invalidated",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.connection.id,clearedTokens:t,priorStatus:r,newStatus:this.connection.status,priorUpdatedAt:o,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue};t?a.warn(s,"Upstream OAuth credentials invalidated; connection now requires reconsent"):a.debug(s,"Upstream OAuth credential metadata rewritten")}}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var nl=3e4,ol=256*1024,il=2,al="does not support dynamic client registration",sl=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],cl=["HTTP 403 Forbidden","Access Denied","permission to access"],dl=new Set(["access_denied","invalid_client","invalid_grant","invalid_request","invalid_scope","invalid_target","unauthorized_client","unsupported_grant_type"]);function ul(e){return e instanceof Error&&e.message.includes(al)}n(ul,"isDynamicClientRegistrationUnsupported");function ll(e){return e instanceof Error&&sl.some(t=>e.message.includes(t))}n(ll,"isProtectedResourceMetadataUnavailable");function pl(e){return e instanceof Error&&cl.some(t=>e.message.includes(t))}n(pl,"isUpstreamProviderAccessDenied");function ml(e){return e instanceof k&&dl.has(e.errorCode)}n(ml,"isStoredConnectionReconsentError");function fl(e){if(e.error instanceof h&&e.error.extensionMembers?.[g]!==void 0)return e.error;if(ul(e.error))return new h({message:`The authorization server for ${e.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register an OAuth client for the gateway manually before retrying.`,extensionMembers:{[g]:"upstream_client_registration_required"}},{cause:e.error});if(ll(e.error))return new h({message:`The upstream MCP server "${e.upstreamServerId}" does not publish OAuth protected resource metadata at "${e.resourceMetadataUrl}". Configure protectedResourceMetadataUrl to a working metadata document, use a provider-supported legacy client, or contact the provider to approve/allowlist this gateway OAuth client before retrying.`,extensionMembers:{[g]:"upstream_oauth_discovery_unavailable"}},{cause:e.error});if(pl(e.error))return new h({message:`The upstream provider denied access while connecting ${e.upstreamServerId}. Confirm the provider allows this gateway and its OAuth client, then retry.`,extensionMembers:{[g]:"upstream_provider_access_denied"}},{cause:e.error})}n(fl,"mapUpstreamOAuthSetupError");function hl(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(hl,"readOAuthFetchRequest");function gl(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(gl,"responseLooksJson");function yl(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(yl,"responseLooksHtml");function _l(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new h({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[g]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[_e]:e.response.status,[Je]:r,[we]:e.request.url.toString(),[Ge]:e.body}})}n(_l,"throwUpstreamHtmlError");function wl(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(wl,"readUpstreamOAuthErrorBody");function bl(e){let{error:t,errorDescription:r}=wl(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.request.method??"GET",host:q(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(bl,"logUpstreamOAuthHttpError");function $i(e){return async(t,r)=>{let o=hl(t),i=N(),a=Date.now(),s=await mi(t,r,{maxRedirects:il,maxResponseBytes:ol,problemCode:"upstream_token_exchange_failed",timeoutMs:nl}),c=await s.clone().text();if(i?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:o.method??"GET",host:q(o.url),path:o.url.pathname,status:s.status,durationMs:Date.now()-a,responseChars:c.length},"Upstream OAuth HTTP request completed"),s.ok||bl({log:i,upstreamServerId:e,request:o,response:s,body:c}),!s.ok&&yl(s,c)&&_l({upstreamServerId:e,request:o,response:s,body:c}),!gl(s,c))return s;try{JSON.parse(c)}catch(u){throw new h({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[g]:"upstream_token_exchange_failed"}},{cause:u})}return s}}n($i,"createUpstreamOAuthFetch");function Zi(e){N()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:q(e.serverUrl),resourceMetadataHost:q(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}n(Zi,"logUpstreamOAuthFlowStarted");function Ki(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=q(e.serverUrl);r!==void 0&&(t.serverHost=r);let o=e.error instanceof h?e.error.extensionMembers?.[g]:void 0;typeof o=="string"&&(t.code=o),G(t,"error",e.error),N()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(Ki,"logUpstreamOAuthFlowFailed");function Wi(e,t){return e.configuredAuthorizationScope??t.requestedScope}n(Wi,"readAuthorizationRequestScope");async function Vi(e,t){e.applyChallengeScope(t.requestedScope),Zi({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:$i(t.upstreamServerId)},o=Wi(e,t);return o!==void 0&&(r.scope=o),await Zr(e,r)}catch(r){Ki({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=fl({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(Vi,"runUpstreamOAuth");async function Rl(e,t){e.applyChallengeScope(t.requestedScope),Zi({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:$i(t.upstreamServerId)},o=Wi(e,t);o!==void 0&&(r.scope=o);try{return await Zr(e,r)}catch(i){throw Ki({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:i}),i}}n(Rl,"exchangeUpstreamAuthorizationCode");async function Yi(e,t){let r=await Vi(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new h({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new h({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Yi,"requireUpstreamAuthorizationRedirect");async function Xi(e){let t=Pt(e.connection),r=!!e.forceRefresh,o=!r&&t==="usable",i=N(),a=i?await Xe({owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}):void 0;if(i?.debug({event:"upstream_oauth_refresh_decision",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,ownerMode:e.target.owner.mode,connectionFingerprint:a,connectionId:e.connection?.id,accessTokenState:t,forceRefresh:r,willRefresh:!o,expiresAt:e.connection?.expiresAt,connectionUpdatedAt:e.connection?.updatedAt},o?"Reusing stored upstream access token":"Refreshing upstream credential"),o)return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let s;try{s=await Vi(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(c){if(e.connection===void 0||!ml(c))throw c;return i?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:c.errorCode,connectionFingerprint:a,connectionId:e.connection.id,rejectedRefreshTokenFingerprint:e.provider.usedRefreshTokenFingerprint,connectionUpdatedAt:e.connection.updatedAt,connectionExpiresAt:e.connection.expiresAt},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),{kind:"connect_required",payload:await Fi({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(s==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(s!=="REDIRECT")throw new h({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${s}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new h({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}});return{kind:"connect_required",payload:await Fi({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}n(Xi,"authorizeUpstreamOAuthSession");async function Il(e){let t=await lr(e.stateToken),r=await R().consumeUpstreamOAuthState({id:t.id,now:I(new Date)}),o=Cl(r);return Sl({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),vl(o),o}n(Il,"consumeStoredCallbackState");function Cl(e){switch(e.kind){case"consumed":throw new h({message:"OAuth state has already been used",extensionMembers:{[g]:"oauth_state_reused"}});case"missing":throw new h({message:"OAuth state is missing or expired",extensionMembers:{[g]:"oauth_state_expired"}});case"available":return e.record}}n(Cl,"readConsumedCallbackState");function Sl(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.operationId===e.signedState.operationId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw new h({message:"OAuth callback did not match the initiating request",extensionMembers:{[g]:"oauth_callback_mismatch"}})}n(Sl,"assertStoredCallbackStateMatches");function vl(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new h({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}})}n(vl,"assertStoredCallbackStateFresh");async function Fi(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),qi(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),pr(t)}n(Fi,"buildOAuthConnectRequiredResponse");async function Qi(e){let t=await Il({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Zt(t),[o]=await R().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),i={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};o!==void 0&&(i.connection=o);let a=new De(i),s=await Rl(a,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(s==="AUTHORIZED")return t;throw s!=="REDIRECT"?new h({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${s}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new h({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Qi,"finishUpstreamOAuthCallback");Z();import{importPKCS8 as Al,SignJWT as kl}from"jose";var ta=1e4,ra=64*1024,na=2,xl=300,ne=d.string().min(1),Tl=d.object({access_token:ne,issued_token_type:d.literal(Ur),token_type:d.string().optional(),expires_in:d.number().int().positive().optional(),scope:ne.optional()}).passthrough(),Ul=d.object({id_token:ne,token_type:ne.optional(),expires_in:d.number().int().positive().optional(),refresh_token:ne.optional(),scope:ne.optional()}).passthrough(),Pl=d.object({access_token:ne,token_type:ne,expires_in:d.number().int().positive().optional(),scope:ne.optional(),resource:ne.optional(),refresh_token:ne.optional()}).passthrough();function ea(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(ea,"formEncodeClientCredential");function El(e){return e.replaceAll("\\n",`
26
26
  `)}n(El,"normalizePem");async function Ol(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??xl,o=await Al(El(e.clientAuth.privateKeyPem),t),i={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new kl({jti:crypto.randomUUID()}).setProtectedHeader(i).setIssuer(e.clientAuth.clientId).setSubject(e.clientAuth.clientId).setAudience(e.clientAuth.audience??e.tokenUrl).setIssuedAt().setExpirationTime(`${r}s`).sign(o)}n(Ol,"createPrivateKeyJwtClientAssertion");async function ql(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=ea(e.clientAuth.clientId),r=ea(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",Wt),e.form.set("client_assertion",await Ol({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}n(ql,"appendClientAuthentication");async function cn(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await ql({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}n(cn,"buildFormRequest");function oa(e){return(t,r)=>ur(t,r,{context:e,maxRedirects:na,maxResponseBytes:ra,problemCode:"upstream_token_exchange_failed",timeoutMs:ta})}n(oa,"defaultIdpFetchJson");function Ml(e){return(t,r)=>fi(t,r,{context:e,maxRedirects:na,maxResponseBytes:ra,problemCode:"upstream_token_exchange_failed",timeoutMs:ta})}n(Ml,"defaultResourceAsFetchJson");function fr(e){let t={[g]:e.code,[we]:e.tokenUrl};return e.response!==void 0&&(t[_e]=e.response.status),new h({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}n(fr,"runtimeError");function dn(e){if(!e.response.ok)throw fr({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(dn,"assertTokenEndpointSucceeded");function Dl(e){let t=Ul.safeParse(e.json);if(!t.success)throw fr({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(Dl,"parseIdpRefreshTokenResponse");function jl(e){let t=Tl.safeParse(e.json);if(!t.success)throw fr({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(jl,"parseIdJagTokenExchangeResponse");function zl(e){let t=Pl.safeParse(e.json);if(!t.success)throw fr({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(zl,"parseAccessTokenResponse");async function ia(e){let t=new URLSearchParams({grant_type:Kt,requested_token_type:Ur,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??oa(e.context),{response:o,json:i}=await r(e.idp.tokenUrl,await cn({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return dn({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),jl({json:i,response:o,tokenUrl:e.idp.tokenUrl})}n(ia,"requestIdJag");async function aa(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??oa(e.context),{response:o,json:i}=await r(e.idp.tokenUrl,await cn({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return dn({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),Dl({json:i,response:o,tokenUrl:e.idp.tokenUrl})}n(aa,"refreshIdpSubjectToken");async function sa(e){let t=new URLSearchParams({grant_type:Re,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??Ml(e.context),{response:o,json:i}=await r(e.resourceAs.tokenUrl,await cn({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return dn({response:o,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),zl({json:i,response:o,tokenUrl:e.resourceAs.tokenUrl})}n(sa,"exchangeIdJagForAccessToken");function Hl(e){return Pt(e)==="usable"}n(Hl,"hasUsableAccessToken");function Bl(e){if(e.tokenType.toLowerCase()!=="bearer")throw new h({message:"Upstream Resource AS returned a token type the MCP gateway cannot send as a bearer token.",extensionMembers:{[g]:"upstream_token_response_invalid"}})}n(Bl,"assertBearerToken");function ca(e,t){if(t===Ze)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}n(ca,"hasExpiredSubjectToken");async function Ll(e){let t=await ke(e.encryptedSubjectToken);if(e.subjectTokenType!==Ze)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await aa({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});if(r.refreshToken===void 0)return{connection:e.connection,subjectToken:r.idToken,subjectTokenType:pt};let o=await R().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:Ze,idpSubjectTokenExpiresAt:void 0}});return N()?.info({event:"upstream_id_jag_subject_token_rotated",upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,connectionFingerprint:e.connectionFingerprint,connectionId:o.id,priorStatus:e.connection.status,priorUpdatedAt:e.connection.updatedAt,usedSubjectRefreshTokenFingerprint:await Ye(t),newSubjectRefreshTokenFingerprint:await Ye(r.refreshToken)},"Upstream ID-JAG IdP subject refresh token rotated and persisted"),{connection:o,subjectToken:r.idToken,subjectTokenType:pt}}n(Ll,"resolveIdJagSubjectToken");async function da(e){let t="preloadedConnection"in e?e.preloadedConnection:(await R().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0],r=Pt(t),o=!!e.forceRefresh,i=!o&&r==="usable",a=N(),s=a?await Xe({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}):void 0;if(a?.debug({event:"upstream_id_jag_auth_decision",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,ownerMode:e.owner.mode,connectionFingerprint:s,connectionId:t?.id,accessTokenState:r,forceRefresh:o,willMint:!i,expiresAt:t?.expiresAt,connectionUpdatedAt:t?.updatedAt},i?"Reusing stored upstream ID-JAG access token":"Minting upstream ID-JAG access token"),!e.forceRefresh&&Hl(t))return{kind:"authorized",credential:{type:"bearer_token",token:await ke(t.encryptedAccessToken)}};let c=t?.metadata?.encryptedIdpSubjectToken,u=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||c===void 0||u===void 0||ca(t,u))return a?.debug({event:"upstream_id_jag_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:s,connectionId:t?.id,status:t?.status??"not_connected",hasSubjectToken:c!==void 0,subjectTokenType:u,subjectTokenExpired:u!==void 0&&ca(t,u)},"Upstream ID-JAG requires an admin subject-token binding"),{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 l=Se(e.upstreamServerId),m=ui(e.upstreamServerId,e.authProfileId),w=m.resourceAs.resource??l.transport.baseUrl,P=e.requestedScope??(m.scopes.length===0?void 0:m.scopes.join(m.scopeDelimiter)),y=await Ll({connection:t,connectionFingerprint:s,encryptedSubjectToken:c,subjectTokenType:u,idp:{tokenUrl:m.idp.tokenUrl},clientAuth:m.idp.clientAuth,context:e.context}),E=await ia({idp:{tokenUrl:m.idp.tokenUrl},subjectToken:y.subjectToken,subjectTokenType:y.subjectTokenType,audience:m.resourceAs.audience,resource:w,scope:P,clientAuth:m.idp.clientAuth,context:e.context}),x=E.scope??P,B=await sa({resourceAs:{tokenUrl:m.resourceAs.tokenUrl},assertion:E.assertion,resource:w,scope:x,clientAuth:m.resourceAs.clientAuth,context:e.context});if(Bl(B),t!==void 0){let X=(B.scope??x)?.split(/[,\s]+/).filter(Boolean)??[],O=B.expiresIn===void 0?void 0:I(new Date(Date.now()+B.expiresIn*1e3)),j=await R().upsertUpstreamConnection({id:y.connection.id,ownerMode:y.connection.ownerMode,subjectId:y.connection.subjectId,upstreamServerId:y.connection.upstreamServerId,authProfileId:y.connection.authProfileId,status:"active",encryptedAccessToken:await me(B.accessToken),encryptedRefreshToken:y.connection.encryptedRefreshToken,scopes:X,expiresAt:O,metadata:y.connection.metadata});a?.info({event:"upstream_id_jag_access_token_persisted",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:s,connectionId:j.id,priorStatus:y.connection.status,priorUpdatedAt:y.connection.updatedAt,scopeCount:X.length,expiresAt:O},"Upstream ID-JAG access token persisted; connection is active")}return{kind:"authorized",credential:{type:"bearer_token",token:B.accessToken}}}n(da,"authorizeUpstreamIdJagRequest");function Nl(e){return mr(new URL(e.callbackPath,M(e.requestUrl,e.requestHeaders))).toString()}n(Nl,"buildGatewayOAuthRedirectUri");async function ua(e){let t=Se(e.upstreamServerId),r=We(e.upstreamServerId,e.authProfileId),o=Nl({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),i="preloadedConnection"in e?e.preloadedConnection:(await R().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:i,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,returnTo:e.returnTo},redirectUri:o,returnOrigin:M(e.request.url,e.request.headers)}}}n(ua,"prepareUpstreamOAuthRequest");async function la(e){let t=await ua(e),r=new De({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Yi(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(la,"startUpstreamConnect");async function pa(e){let t=await ua(e),r=new De({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return Xi({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(pa,"authorizeUpstreamRequest");async function et(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return pa({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 da({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 Q(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(et,"resolveUpstreamCredentialForRoute");async function ma(e){if(e.connectRequest.authMode==="id-jag")throw new Q(`Upstream server ${e.connectRequest.upstreamServerId} uses XAA / ID-JAG and does not support browser OAuth connection flows.`);let t=await la({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(ma,"startUpstreamConnectForRequest");async function fa(e){let r=(await lr(e.callbackRequest.state)).authProfileId;if(cr({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}).mode==="id-jag")throw new Q(`Upstream server ${e.callbackRequest.upstreamServerId} uses XAA / ID-JAG and does not support OAuth callbacks.`);return Qi({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:Se(e.callbackRequest.upstreamServerId)})}n(fa,"finishUpstreamCallbackForRequest");function Jl(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(Jl,"buildRouteAuthBaseFromConnection");function ha(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:go(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(ha,"buildRouteAuthBaseFromPolicyOptions");function hr(e,t){let o=ee().byOperationId.get(t);if(!o)throw new A(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new A(`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 A(`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 Jl({connection:o.connection,operationId:t})}n(hr,"resolveRouteAuthBase");function un(e,t){switch(e){case"user":return Fe(t);case"shared":return fo()}}n(un,"buildOwnerForSubject");function tt(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:un("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:un("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:un("user",t),initiatedBySubjectId:t}}}n(tt,"resolveRouteAuthForSubject");var Gl=dt.InvalidRequest,Fl=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function $l(e,t){return{credentialType:e.type,forceRefresh:t}}n($l,"buildCredentialResolvedAttributes");function Zl(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(Zl,"connectRequiredReasonCode");function ga(e){v(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:$l(e.credential,e.forceRefresh===!0)})}n(ga,"emitCredentialResolvedAnalyticsEvent");function ya(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:Zl(e.payload.state),reasonClass:"auth",attributes:t})}n(ya,"emitCredentialMissingAnalyticsEvents");function Kl(e){let t=e.route.raw();return Gt.parse(t?.operationId)}n(Kl,"readOperationId");async function Wl(e,t,r,o){let i=await et({request:e,context:o,routeAuth:t});if(i.kind==="connect_required")return ya({context:o,payload:i.payload,routeBinding:t}),o.log.info({event:"mcp_upstream_connect_required",upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId},"MCP upstream proxy: upstream connection required"),{kind:"connect_required",payload:i.payload};let a=i.credential;if(ga({context:o,credential:a,routeBinding:t}),a.type==="bearer_token")return{kind:"headers",headers:[["authorization",`Bearer ${a.token}`]]};let s=await a.provider.tokens();return s?{kind:"headers",headers:[["authorization",`${s.token_type??"Bearer"} ${s.access_token}`]]}:(o.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:t.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),Response.json({error:"no_upstream_tokens"},{status:401}))}n(Wl,"buildCredentialHeaders");var Vl=new Set(["authorization","cookie","cookie2"]);function Yl(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(Yl,"readJsonRequestMethod");function Xl(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(Xl,"isJsonResponse");function ln(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(ln,"isRecord");function Ql(e){return Array.isArray(e)&&e.length>0}n(Ql,"hasIconList");function ep(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=sr(ao(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(ep,"readFallbackServerIcons");function tp(e){if(!ln(e.body))return e.body;let t=e.body.result;if(!ln(t))return e.body;let r=t.serverInfo;return!ln(r)||Ql(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n(tp,"addMissingServerIcons");function rp(e,t){let r=new Headers(e.headers);for(let o of Vl)r.delete(o);for(let[o,i]of t)r.set(o,i);return new Gn(e,{headers:r})}n(rp,"applyUpstreamHeaders");function np(e){let t=new Headers(e.headers);for(let r of Fl)t.delete(r);return t}n(np,"buildProxyHeaders");async function op(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(op,"readRetryBody");function _a(e,t){let r=t.authUrl===void 0?void 0:Go({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(er({id:Jo(e),error:{code:r?.code??Gl,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(_a,"connectRequiredJsonRpcResponse");async function ip(e){let{scope:t}=ii(e.upstreamResponse),r=await et({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="connect_required")return ya({context:e.context,payload:r.payload,routeBinding:e.routeAuth,forceRefresh:!0}),{kind:"connect_required",payload:r.payload};let o=new Headers(e.headers),i=r.credential;if(ga({context:e.context,credential:i,routeBinding:e.routeAuth,forceRefresh:!0}),i.type==="bearer_token")return o.set("authorization",`Bearer ${i.token}`),{kind:"headers",headers:o};let a=await i.provider.tokens();return a?(o.set("authorization",`${a.token_type??"Bearer"} ${a.access_token}`),{kind:"headers",headers:o}):(e.context.log.warn({event:"mcp_upstream_no_tokens_after_refresh",upstreamServerId:e.routeAuth.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens after refresh"),{kind:"response",response:Response.json({error:"no_upstream_tokens"},{status:401})})}n(ip,"applyRefreshedCredentialHeaders");function ap(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await ip({request:e.request,context:e.context,headers:np(r),routeAuth:e.routeAuth,upstreamResponse:t});if(o.kind==="connect_required")return _a(e.requestBody,o.payload);if(o.kind==="response")return o.response;let i=so({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return Ht.fetch(i.url,i.init)})}n(ap,"installUpstreamAuthRetryHook");function sp(e){if(Yl(e.requestBody)!=="initialize")return;let t=ep({connection:e.connection,context:e.context});t===void 0||t.length===0||e.context.addResponseSendingHook(async r=>{if(!Xl(r))return r;let o;try{o=await r.clone().json()}catch{return r}let i=tp({body:o,icons:t});if(i===o)return r;let a=new Headers(r.headers);return a.delete("content-length"),new Response(JSON.stringify(i),{status:r.status,statusText:r.statusText,headers:a})})}n(sp,"installInitializeIconHook");async function pn(e,t,r){let o=Kl(t),i=await op(e),a=ha({connection:r,operationId:o}),s=Pe(e.user,e.url,e.headers);t.log.setLogProperties?.({requestId:t.requestId}),Io(t,s);let c=tt(a,s.subjectId),u=await Wl(e,c,r,t);if(!(u instanceof Response)&&u.kind==="connect_required")return _a(i,u.payload);if(u instanceof Response)return u;let l=rp(e,u.headers);return ap({request:l,context:t,requestBody:i,routeAuth:c}),sp({context:t,requestBody:i,connection:r}),l}n(pn,"mcpTokenExchangePolicy");var mn=class extends Bt{static{n(this,"McpTokenExchangeInboundPolicy")}static policyType="mcp-token-exchange";constructor(t,r){let o=yo(t,r);super(o,r)}async handler(t,r){return pn(t,r,this.options)}};Z();var wa=Symbol("Html");function cp(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n(cp,"escapeHtml");function dp(e){return e===null||typeof e!="object"?!1:e[wa]===!0}n(dp,"isHtml");function ba(e){return e==null||e===!1?"":Array.isArray(e)?e.map(ba).join(""):dp(e)?e.value:cp(String(e))}n(ba,"renderValue");function fe(e){return{[wa]:!0,value:e}}n(fe,"trustedHtml");var te=fe("");function S(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=ba(t[o]),r+=e[o+1]??"";return fe(r)}n(S,"html");function rt(e){return e.value}n(rt,"renderHtml");function Ra(e){return S`<p class="card__description">${e.detail}</p>${e.guidance} ${e.technicalDetails} ${e.action}`}n(Ra,"renderBrowserErrorPage");var nt=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 ot(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(ot,"renderShell");var up="text/html; charset=utf-8";function it(e){try{return new URL(e).host}catch{return""}}n(it,"safeHostFromUrl");function ie(e){let t=pp(e.kind??"authorization_failed"),r=lp(e);return new Response(rt(ot({title:e.title??t.title,iconHref:"",styles:nt,headerIcon:te,heading:e.title??t.title,subhead:"",body:Ra({detail:e.detail,guidance:S`<p class="card__description">${t.guidance}</p>`,technicalDetails:yp({diagnostic:r,upstreamHtml:e.upstreamHtml}),action:hp(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":up,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(ie,"browserErrorPageResponse");function lp(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??mp(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??fp(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}n(lp,"buildBrowserErrorDiagnostic");function pp(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(pp,"readBrowserErrorPagePresentation");function mp(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(mp,"readBrowserErrorStage");function fp(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(fp,"readBrowserErrorSuggestedFix");function hp(e){return e===void 0?te:S`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(hp,"renderAction");function gp(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(`