@zuplo/cli 6.73.17 → 6.73.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/node_modules/@hono/node-server/README.md +58 -25
- package/node_modules/@hono/node-server/dist/conninfo.cjs +22 -0
- package/node_modules/@hono/node-server/dist/{conninfo.d.ts → conninfo.d.cts} +4 -3
- package/node_modules/@hono/node-server/dist/conninfo.d.mts +4 -3
- package/node_modules/@hono/node-server/dist/conninfo.mjs +19 -16
- package/node_modules/@hono/node-server/dist/constants-BLSFu_RU.mjs +5 -0
- package/node_modules/@hono/node-server/dist/constants-BXAKTxRC.cjs +11 -0
- package/node_modules/@hono/node-server/dist/index.cjs +1173 -0
- package/node_modules/@hono/node-server/dist/index.d.cts +101 -0
- package/node_modules/@hono/node-server/dist/index.d.mts +101 -8
- package/node_modules/@hono/node-server/dist/index.mjs +1143 -637
- package/node_modules/@hono/node-server/dist/serve-static.cjs +151 -0
- package/node_modules/@hono/node-server/dist/serve-static.d.cts +18 -0
- package/node_modules/@hono/node-server/dist/serve-static.d.mts +14 -13
- package/node_modules/@hono/node-server/dist/serve-static.mjs +143 -145
- package/node_modules/@hono/node-server/dist/utils/response.cjs +8 -0
- package/node_modules/@hono/node-server/dist/utils/response.d.cts +4 -0
- package/node_modules/@hono/node-server/dist/utils/response.d.mts +3 -2
- package/node_modules/@hono/node-server/dist/utils/response.mjs +6 -9
- package/node_modules/@hono/node-server/dist/utils/stream.cjs +65 -0
- package/node_modules/@hono/node-server/dist/utils/stream.d.cts +6 -0
- package/node_modules/@hono/node-server/dist/utils/stream.d.mts +6 -0
- package/node_modules/@hono/node-server/dist/utils/stream.mjs +64 -0
- package/node_modules/@hono/node-server/package.json +65 -54
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.js +1 -12
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/index.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.d.ts +7 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.js +9 -3
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/stdio.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.js +5 -3
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/streamableHttp.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.js +1 -12
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/index.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sseKeepAlive.d.ts +5 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sseKeepAlive.d.ts.map +1 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sseKeepAlive.js +17 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/sseKeepAlive.js.map +1 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.d.ts +9 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.js +10 -4
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/stdio.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.d.ts +21 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.js +239 -41
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/webStandardStreamableHttp.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.js +25 -6
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/server/zod-compat.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/mediaType.d.ts +32 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/mediaType.d.ts.map +1 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/mediaType.js +64 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/mediaType.js.map +1 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.d.ts +5 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.js +10 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/cjs/shared/stdio.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js +2 -13
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.d.ts +7 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js +9 -3
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js +5 -3
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js +2 -13
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sseKeepAlive.d.ts +5 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sseKeepAlive.d.ts.map +1 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sseKeepAlive.js +13 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/sseKeepAlive.js.map +1 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.d.ts +9 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js +10 -4
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.d.ts +21 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js +239 -41
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js +25 -6
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.d.ts +32 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.d.ts.map +1 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js +57 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/mediaType.js.map +1 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.d.ts +5 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.d.ts.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js +9 -0
- package/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js.map +1 -1
- package/node_modules/@modelcontextprotocol/sdk/package.json +4 -3
- package/node_modules/@zuplo/core/package.json +1 -1
- package/node_modules/@zuplo/graphql/package.json +1 -1
- package/node_modules/@zuplo/openapi-tools/package.json +1 -1
- package/node_modules/@zuplo/otel/out/esm/chunk-JYT2Q52R.js +26 -0
- package/node_modules/@zuplo/otel/out/esm/chunk-JYT2Q52R.js.map +1 -0
- package/node_modules/@zuplo/otel/out/esm/index.js +1 -1
- package/node_modules/@zuplo/otel/package.json +1 -1
- package/node_modules/@zuplo/runtime/out/esm/{chunk-OAVAM6CR.js → chunk-JPPAUB3E.js} +3 -3
- package/node_modules/@zuplo/runtime/out/esm/chunk-JPPAUB3E.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/index.js +1 -1
- package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +1 -1
- package/node_modules/@zuplo/runtime/out/types/index.d.ts +10 -3
- package/node_modules/@zuplo/runtime/package.json +1 -1
- package/node_modules/express-rate-limit/dist/index.d.cts +10 -12
- package/node_modules/express-rate-limit/dist/index.d.mts +10 -12
- package/node_modules/express-rate-limit/dist/index.d.ts +10 -12
- package/node_modules/express-rate-limit/package.json +5 -5
- package/node_modules/express-rate-limit/readme.md +2 -2
- package/node_modules/ip-address/README.md +102 -100
- package/node_modules/ip-address/dist/common.d.ts +23 -0
- package/node_modules/ip-address/dist/common.js +27 -4
- package/node_modules/ip-address/dist/common.js.map +1 -1
- package/node_modules/ip-address/dist/ipv4.d.ts +7 -0
- package/node_modules/ip-address/dist/ipv4.js +19 -7
- package/node_modules/ip-address/dist/ipv4.js.map +1 -1
- package/node_modules/ip-address/dist/ipv6.d.ts +7 -0
- package/node_modules/ip-address/dist/ipv6.js +38 -25
- package/node_modules/ip-address/dist/ipv6.js.map +1 -1
- package/node_modules/ip-address/dist/v4/constants.js +5 -1
- package/node_modules/ip-address/dist/v4/constants.js.map +1 -1
- package/node_modules/ip-address/package.json +2 -2
- package/package.json +6 -6
- package/node_modules/@hono/node-server/dist/conninfo.js +0 -42
- package/node_modules/@hono/node-server/dist/globals.d.mts +0 -2
- package/node_modules/@hono/node-server/dist/globals.d.ts +0 -2
- package/node_modules/@hono/node-server/dist/globals.js +0 -29
- package/node_modules/@hono/node-server/dist/globals.mjs +0 -5
- package/node_modules/@hono/node-server/dist/index.d.ts +0 -8
- package/node_modules/@hono/node-server/dist/index.js +0 -702
- package/node_modules/@hono/node-server/dist/listener.d.mts +0 -13
- package/node_modules/@hono/node-server/dist/listener.d.ts +0 -13
- package/node_modules/@hono/node-server/dist/listener.js +0 -670
- package/node_modules/@hono/node-server/dist/listener.mjs +0 -635
- package/node_modules/@hono/node-server/dist/request.d.mts +0 -25
- package/node_modules/@hono/node-server/dist/request.d.ts +0 -25
- package/node_modules/@hono/node-server/dist/request.js +0 -238
- package/node_modules/@hono/node-server/dist/request.mjs +0 -206
- package/node_modules/@hono/node-server/dist/response.d.mts +0 -26
- package/node_modules/@hono/node-server/dist/response.d.ts +0 -26
- package/node_modules/@hono/node-server/dist/response.js +0 -112
- package/node_modules/@hono/node-server/dist/response.mjs +0 -85
- package/node_modules/@hono/node-server/dist/serve-static.d.ts +0 -17
- package/node_modules/@hono/node-server/dist/serve-static.js +0 -177
- package/node_modules/@hono/node-server/dist/server.d.mts +0 -10
- package/node_modules/@hono/node-server/dist/server.d.ts +0 -10
- package/node_modules/@hono/node-server/dist/server.js +0 -696
- package/node_modules/@hono/node-server/dist/server.mjs +0 -660
- package/node_modules/@hono/node-server/dist/types.d.mts +0 -44
- package/node_modules/@hono/node-server/dist/types.d.ts +0 -44
- package/node_modules/@hono/node-server/dist/types.js +0 -18
- package/node_modules/@hono/node-server/dist/types.mjs +0 -0
- package/node_modules/@hono/node-server/dist/utils/response/constants.d.mts +0 -3
- package/node_modules/@hono/node-server/dist/utils/response/constants.d.ts +0 -3
- package/node_modules/@hono/node-server/dist/utils/response/constants.js +0 -30
- package/node_modules/@hono/node-server/dist/utils/response/constants.mjs +0 -5
- package/node_modules/@hono/node-server/dist/utils/response.d.ts +0 -3
- package/node_modules/@hono/node-server/dist/utils/response.js +0 -37
- package/node_modules/@hono/node-server/dist/utils.d.mts +0 -9
- package/node_modules/@hono/node-server/dist/utils.d.ts +0 -9
- package/node_modules/@hono/node-server/dist/utils.js +0 -99
- package/node_modules/@hono/node-server/dist/utils.mjs +0 -71
- package/node_modules/@hono/node-server/dist/vercel.d.mts +0 -7
- package/node_modules/@hono/node-server/dist/vercel.d.ts +0 -7
- package/node_modules/@hono/node-server/dist/vercel.js +0 -677
- package/node_modules/@hono/node-server/dist/vercel.mjs +0 -640
- package/node_modules/@zuplo/otel/out/esm/chunk-JWNK52ES.js +0 -26
- package/node_modules/@zuplo/otel/out/esm/chunk-JWNK52ES.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-OAVAM6CR.js.map +0 -1
- /package/node_modules/@zuplo/runtime/out/esm/{chunk-OAVAM6CR.js.LEGAL.txt → chunk-JPPAUB3E.js.LEGAL.txt} +0 -0
|
@@ -22,5 +22,5 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{$a as or,$b as Lr,$d as ps,A as N,Aa as Ut,Ab as Ur,Ae as Is,B as O,Ba as $t,Bb as $r,Be as Js,C as Q,Ca as kt,Ce as Ks,D as V,Da as Ft,De as Ms,E as W,Ea as Lt,Ee as Ns,F as X,Fa as Rt,Fe as Os,G as Y,Ga as qt,Ge as Qs,H as Z,Ha as vt,I as _,Ia as zt,Id as Kr,J as tt,Ja as Gt,Jd as Mr,K as rt,Ka as It,Kd as Nr,L as st,La as Jt,Ld as Or,M as et,Ma as Kt,Md as Qr,N as ot,Na as Mt,Nd as Vr,Oa as Nt,Od as Wr,Pa as Ot,Pd as Xr,Qa as Qt,Qd as Yr,Ra as Vt,Rd as Zr,Sa as Wt,Sd as _r,Ta as Xt,Td as ts,Ua as Yt,Ud as rs,Va as Zt,Vd as ss,Wa as _t,Wd as es,Xa as tr,Xd as os,Ya as rr,Yd as as,Za as sr,Zb as kr,Zd as ns,_a as er,_b as Fr,_d as is,a as b,aa as at,ab as ar,ac as Rr,ae as cs,b as l,ba as nt,bb as nr,bc as qr,be as hs,c as j,ca as it,cb as ir,cc as vr,ce as xs,d as B,da as pt,db as pr,dc as zr,de as ys,e as C,ea as ct,eb as cr,ec as Gr,ee as ws,f as D,fa as ht,fb as hr,fc as Ir,fe as As,g as E,ga as mt,gb as mr,gc as Jr,ge as bs,h as H,ha as gt,hb as gr,he as ls,i as P,ia as dt,ib as dr,ie as js,j as S,ja as ut,jb as ur,je as Bs,k as n,ka as ft,kb as fr,ke as Cs,l as T,la as xt,lb as xr,le as Ds,m as U,ma as yt,mb as yr,me as Es,n as $,na as wt,nb as wr,ne as Hs,o as k,oa as At,ob as Ar,oe as Ps,p as F,pa as bt,pb as br,pe as Ss,q as L,qa as lt,qb as lr,qe as Ts,r as R,ra as jt,rb as jr,re as Us,sa as Bt,sb as Br,se as ks,t as q,ta as Ct,tb as Cr,te as Fs,u as z,ua as Dt,ub as Dr,ue as Ls,v as G,va as Et,vb as Er,ve as Rs,w as I,wa as Ht,wb as Hr,we as qs,xa as Pt,xb as Pr,xe as vs,y as K,ya as St,yb as Sr,ye as zs,z as M,za as Tt,zb as Tr,ze as Gs}from"./chunk-
|
|
25
|
+
import{$a as or,$b as Lr,$d as ps,A as N,Aa as Ut,Ab as Ur,Ae as Is,B as O,Ba as $t,Bb as $r,Be as Js,C as Q,Ca as kt,Ce as Ks,D as V,Da as Ft,De as Ms,E as W,Ea as Lt,Ee as Ns,F as X,Fa as Rt,Fe as Os,G as Y,Ga as qt,Ge as Qs,H as Z,Ha as vt,I as _,Ia as zt,Id as Kr,J as tt,Ja as Gt,Jd as Mr,K as rt,Ka as It,Kd as Nr,L as st,La as Jt,Ld as Or,M as et,Ma as Kt,Md as Qr,N as ot,Na as Mt,Nd as Vr,Oa as Nt,Od as Wr,Pa as Ot,Pd as Xr,Qa as Qt,Qd as Yr,Ra as Vt,Rd as Zr,Sa as Wt,Sd as _r,Ta as Xt,Td as ts,Ua as Yt,Ud as rs,Va as Zt,Vd as ss,Wa as _t,Wd as es,Xa as tr,Xd as os,Ya as rr,Yd as as,Za as sr,Zb as kr,Zd as ns,_a as er,_b as Fr,_d as is,a as b,aa as at,ab as ar,ac as Rr,ae as cs,b as l,ba as nt,bb as nr,bc as qr,be as hs,c as j,ca as it,cb as ir,cc as vr,ce as xs,d as B,da as pt,db as pr,dc as zr,de as ys,e as C,ea as ct,eb as cr,ec as Gr,ee as ws,f as D,fa as ht,fb as hr,fc as Ir,fe as As,g as E,ga as mt,gb as mr,gc as Jr,ge as bs,h as H,ha as gt,hb as gr,he as ls,i as P,ia as dt,ib as dr,ie as js,j as S,ja as ut,jb as ur,je as Bs,k as n,ka as ft,kb as fr,ke as Cs,l as T,la as xt,lb as xr,le as Ds,m as U,ma as yt,mb as yr,me as Es,n as $,na as wt,nb as wr,ne as Hs,o as k,oa as At,ob as Ar,oe as Ps,p as F,pa as bt,pb as br,pe as Ss,q as L,qa as lt,qb as lr,qe as Ts,r as R,ra as jt,rb as jr,re as Us,sa as Bt,sb as Br,se as ks,t as q,ta as Ct,tb as Cr,te as Fs,u as z,ua as Dt,ub as Dr,ue as Ls,v as G,va as Et,vb as Er,ve as Rs,w as I,wa as Ht,wb as Hr,we as qs,xa as Pt,xb as Pr,xe as vs,y as K,ya as St,yb as Sr,ye as zs,z as M,za as Tt,zb as Tr,ze as Gs}from"./chunk-JPPAUB3E.js";import{c as y,d as J,e as ms,f as gs,g as ds,h as us,i as fs}from"./chunk-US6ITPGV.js";import"./chunk-7WS4HIGR.js";import{a as v}from"./chunk-FPZAMUNA.js";import{a as x,e as w,f as A,n as $s}from"./chunk-QWO5UTVQ.js";import{U as u,W as a,X as f}from"./chunk-VCMIY3WJ.js";import{a as t}from"./chunk-2WLR6ZDZ.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{qt as AIGatewayAnthropicToOpenAIInboundPolicy,vt as AIGatewayAuthInboundPolicy,zt as AIGatewayAuthV2InboundPolicy,Gt as AIGatewayConfigurationExecutorV2InboundPolicy,It as AIGatewayFallbackModelV2InboundPolicy,Z as AIGatewayMeteringInboundPolicy,Jt as AIGatewayModelFilteringV2InboundPolicy,l as AIGatewayModelRouting,b as AIGatewayModels,Kt as AIGatewayOpenAIToAnthropicOutboundPolicy,Mt as AIGatewaySemanticCacheInboundPolicy,Nt as AIGatewaySemanticCacheOutboundPolicy,Ot as AIGatewaySemanticCacheV2InboundPolicy,Qt as AIGatewayUsageTrackerPolicy,dt as AWSLoggingPlugin,Vt as AkamaiAIFirewallInboundPolicy,Wt as AkamaiAIFirewallV2InboundPolicy,Tt as AkamaiApiSecurityPlugin,Xt as AkamaiFirewallForAiInboundPolicy,Yt as AkamaiFirewallForAiOutboundPolicy,_t as AmberfloMeteringInboundPolicy,Zt as AmberfloMeteringPolicy,rr as ApiAuthKeyInboundPolicy,Os as ApiKeyConsumerClient,tr as ApiKeyInboundPolicy,Dt as AuditLogDataStaxProvider,sr as AuditLogInboundPolicy,Et as AuditLogPlugin,or as Auth0JwtInboundPolicy,ar as AuthZenInboundPolicy,rt as AwsLambdaHandlerExtensions,nr as AxiomaticsAuthZInboundPolicy,$t as AzureBlobPlugin,kt as AzureEventHubsRequestLoggerPlugin,Ut as BackgroundDispatcher,Qs as BackgroundLoader,ir as BasicAuthInboundPolicy,os as BasicRateLimitInboundPolicy,I as BatchDispatch,pr as BrownoutInboundPolicy,cr as CachingInboundPolicy,hr as ChangeMethodInboundPolicy,mr as ClearHeadersInboundPolicy,gr as ClearHeadersOutboundPolicy,dr as ClerkJwtInboundPolicy,ur as CognitoJwtInboundPolicy,fr as CometOpikTracingInboundPolicy,xr as CometOpikTracingV2InboundPolicy,yr as ComplexRateLimitInboundPolicy,wr as CompositeInboundPolicy,Ar as CompositeOutboundPolicy,f as ConfigurationError,z as ContentTypes,x as ContextData,o as CryptoBeta,br as CurityPhantomTokenInboundPolicy,O as DataDogLoggingPlugin,lt as DataDogMetricsPlugin,lr as DataLossPreventionInboundPolicy,jr as DataLossPreventionOutboundPolicy,ut as DynaTraceLoggingPlugin,jt as DynatraceMetricsPlugin,Br as FirebaseJwtInboundPolicy,Cr as FormDataToJsonInboundPolicy,Dr as GalileoTracingInboundPolicy,Er as GalileoTracingV2InboundPolicy,Hr as GeoFilterInboundPolicy,N as GoogleCloudLoggingPlugin,Tr as GraphqlAnalyticsOutboundPolicy,Y as Handler,Ur as HttpDeprecationOutboundPolicy,R as HttpProblems,k as HttpStatusCode,Lt as HydrolixRequestLoggerPlugin,K as InboundPolicy,$r as JWTScopeValidationInboundPolicy,Ht as JwtServicePlugin,ft as LokiLoggingPlugin,V as LookupResult,Wr as MTLSAuthInboundPolicy,Kr as McpAuth0OAuthInboundPolicy,kr as McpClerkOAuthInboundPolicy,Fr as McpCognitoOAuthInboundPolicy,Lr as McpEntraOAuthInboundPolicy,Pt as McpGatewayOAuthProtectedResourcePlugin,Rr as McpGoogleOAuthInboundPolicy,qr as McpKeycloakOAuthInboundPolicy,vr as McpLogtoOAuthInboundPolicy,Mr as McpOAuthInboundPolicy,zr as McpOktaOAuthInboundPolicy,Gr as McpOneLoginOAuthInboundPolicy,Ir as McpPingOAuthInboundPolicy,Jr as McpWorkosOAuthInboundPolicy,A as MemoryZoneReadThroughCache,Nr as MockApiInboundPolicy,Qr as MoesifInboundPolicy,Vr as MonetizationInboundPolicy,xt as NewRelicLoggingPlugin,Bt as NewRelicMetricsPlugin,St as OAuthProtectedResourcePlugin,Ct as OTelMetricsPlugin,Xr as OktaFGAAuthZInboundPolicy,Yr as OktaJwtInboundPolicy,Zr as OpenFGAAuthZInboundPolicy,er as OpenIdJwtInboundPolicy,_r as OpenMeterInboundPolicy,M as OutboundPolicy,L as ProblemResponseFormatter,ts as PromptInjectionDetectionOutboundPolicy,rs as PropelAuthJwtInboundPolicy,ss as QueryParamToHeaderInboundPolicy,es as QuotaInboundPolicy,os as RateLimitInboundPolicy,as as ReadmeMetricsInboundPolicy,ns as RemoveHeadersInboundPolicy,is as RemoveHeadersOutboundPolicy,ps as RemoveQueryParamsInboundPolicy,cs as ReplaceStringOutboundPolicy,Rt as RequestLoggerPlugin,hs as RequestSizeLimitInboundPolicy,xs as RequestValidationInboundPolicy,ws as RequireOriginInboundPolicy,As as RequireUserClaimsInboundPolicy,W as ResponseSendingEvent,X as ResponseSentEvent,a as RuntimeError,u as SYSTEM_LOGGER,ys as SchemaBasedRequestValidation,bs as SecretMaskingOutboundPolicy,$ as SemanticAttributes,ls as SemanticCacheInboundPolicy,Ns as ServiceProviderImpl,js as SetBodyInboundPolicy,Bs as SetHeadersInboundPolicy,Cs as SetHeadersOutboundPolicy,Ds as SetQueryParamsInboundPolicy,Es as SetStatusOutboundPolicy,Hs as SetUpstreamApiKeyInboundPolicy,Ps as SleepInboundPolicy,yt as SplunkLoggingPlugin,U as StreamingZoneCache,Ss as StripeWebhookVerificationInboundPolicy,wt as SumoLogicLoggingPlugin,Ts as SupabaseJwtInboundPolicy,J as SystemRouteName,q as TelemetryPlugin,Us as TrafficSplittingInboundPolicy,ks as UpstreamAwsFederatedAuthInboundPolicy,Fs as UpstreamAwsServiceAuthInboundPolicy,Ls as UpstreamAzureAdServiceAuthInboundPolicy,Rs as UpstreamFirebaseAdminAuthInboundPolicy,qs as UpstreamFirebaseUserAuthInboundPolicy,vs as UpstreamGcpFederatedAuthInboundPolicy,zs as UpstreamGcpJwtInboundPolicy,Gs as UpstreamGcpServiceAuthInboundPolicy,Is as UpstreamZuploJwtAuthInboundPolicy,At as VMWareLogInsightLoggingPlugin,Js as ValidateJsonSchemaInbound,Ks as WebBotAuthInboundPolicy,Ms as XmlToJsonOutboundPolicy,w as ZoneCache,bt as ZuploMcpSdk,v as ZuploRequest,$s as ZuploServices,_ as aiGatewayHandler,tt as aiGatewayHandlerV2,T as apiServices,st as awsLambdaHandler,Ft as defaultGenerateHydrolixEntry,y as environment,H as extractAllText,Pr as extractGraphqlErrors,S as extractStreamTextDelta,E as flattenMessageContent,j as getFormat,gs as getIdForParameterSchema,us as getIdForRefSchema,ds as getIdForRequestBodySchema,ms as getRawOperationDataIdentifierName,B as getRequestBody,C as getResponseBody,P as getStreamEvents,D as getUsage,F as httpStatuses,et as legacyDevPortalHandler,at as mcpServerHandler,nt as openApiSpecHandler,Q as recordGraphqlCacheState,it as redirectHandler,ot as redirectLegacyDevPortal,Sr as responseHasGraphqlErrors,fs as sanitizedIdentifierName,G as serialize,Or as setMoesifContext,n as trackFeature,ct as urlForwardHandler,ht as urlRewriteHandler,mt as webSocketHandler,gt as webSocketPipelineHandler,pt as zuploServiceProxy};
|
|
26
26
|
//# sourceMappingURL=index.js.map
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{$ as Z,$b as kc,$c as vo,Ac as go,Ad as Lo,Bc as yo,Bd as No,Cb as Qn,Cc as _o,Cd as R,Db as K,Dc as wo,Dd as v,Eb as eo,Ec as ee,Ed as G,Fb as to,Fc as B,Fd as le,Gb as q,Gc as bo,Gd as U,Hb as ro,Hc as Ro,Hd as er,Ib as Le,Ic as I,Id as Dc,Jb as no,Jc as de,Jd as zc,Kb as Ne,Kc as $e,Lb as g,Lc as J,Mb as Je,Mc as M,Nb as Ge,Nc as Io,O as $n,Ob as _e,Oc as L,P as m,Pb as we,Pc as Co,Q as Zn,Qb as Jt,Qc as Re,R as xr,Rb as oo,Rc as Ur,S as se,Sb as re,Sc as Wt,T as Kn,Tb as io,Tc as Pr,U as w,Ub as ce,Uc as Vt,V as ye,Vb as b,Vc as pt,W as Nt,Wb as Gt,Wc as Ze,X as Wn,Xb as N,Xc as So,Y as Vn,Yb as be,Yc as ue,Z as Yn,Zb as Ac,Zc as Er,_ as d,_b as xc,_c as Or,ac as Tc,ad as Yt,bc as Uc,bd as Mr,cc as Pc,cd as qr,dc as Ec,dd as Ao,ec as Oc,ed as D,fa as Xn,fc as Mc,fd as xo,gc as qc,gd as ko,hc as ao,hd as Dr,ic as so,id as To,jc as co,jd as Uo,k as ae,kc as Ft,kd as zr,lc as kr,ld as Po,mc as $t,md as Pe,nc as Zt,nd as Eo,oc as dt,od as mt,pc as uo,pd as Oo,qc as lo,qd as Xt,r as Ue,rc as po,rd as ft,s as Jn,sc as ut,sd as Mo,tc as mo,td as qo,uc as Fe,ud as Do,vc as fo,vd as zo,wc as Tr,wd as jo,x as Fn,xc as ho,xd as Ho,y as Lt,yc as lt,yd as Bo,zc as Kt,zd as Qt}from"../chunk-OAVAM6CR.js";import"../chunk-US6ITPGV.js";import{a as C}from"../chunk-7WS4HIGR.js";import{a as Jo}from"../chunk-SNZSLL63.js";import{a as Gn}from"../chunk-FPZAMUNA.js";import"../chunk-QWO5UTVQ.js";import{V as Q,W as h,X as x,Y as Nn,Z as Bt}from"../chunk-VCMIY3WJ.js";import{a as n}from"../chunk-2WLR6ZDZ.js";Z();function jc(e){let t=Zt.safeParse(e);return t.success?t.data.id:void 0}n(jc,"parseJsonRpcRequestId");function Go(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return jc(t)}catch{return}}n(Go,"readJsonRpcRequestIdFromBody");function tr(e){return uo.parse({jsonrpc:$t,...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(tr,"jsonRpcErrorResponse");function Fo(e){return new po([lo.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Fo,"urlElicitationRequiredError");var nr=d.record(d.string(),d.unknown()),Hc=d.record(d.string(),d.unknown()),Ce=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:nr.optional(),roles:Ce,groups:Ce,public:d.boolean().optional()}).strict(),Lc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),_meta:nr.optional(),roles:Ce,groups:Ce,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:nr.optional(),roles:Ce,groups:Ce,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:nr.optional(),roles:Ce,groups:Ce,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(),Ie=[{option:"tools",listMethod:"tools/list",resultProperty:"tools",itemProperty:"name",directMethods:["tools/call"]},{option:"prompts",listMethod:"prompts/list",resultProperty:"prompts",itemProperty:"name",directMethods:["prompts/get"]},{option:"resources",listMethod:"resources/list",resultProperty:"resources",itemProperty:"uri",directMethods:["resources/read"]},{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 F(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(F,"isRecord");function ht(e){return typeof e.method=="string"?e.method:void 0}n(ht,"messageMethod");function $o(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}n($o,"correlationKey");function Zo(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}n(Zo,"asStringArray");function Ko(e,t){if(!F(e))return[];let r=t in e?e[t]:t.split(".").reduce((o,i)=>F(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(Ko,"readClaimValues");function Br(e,t){if(typeof e=="string")return{key:e,public:!1};if(!F(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:Zo(e.roles),groups:Zo(e.groups),public:e.public===!0}}n(Br,"normalizeEntry");function Xc(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(Xc,"isCallerAllowed");function rr(e,t,r,o){if(e===void 0)return;let i=[];for(let a of e){let s=Br(a,t);s!==void 0&&Xc(s,r,o)&&i.push(s.key)}return i}n(rr,"allowedKeys");var Yo=n((e,t,r)=>{let o=r.accessControl?.roleClaim??"roles",i=r.accessControl?.groupClaim??"groups",a=new Set(Ko(e.user?.data,o)),s=new Set(Ko(e.user?.data,i));return{tools:rr(r.tools,"name",a,s),prompts:rr(r.prompts,"name",a,s),resources:rr(r.resources,"uri",a,s),resourceTemplates:rr(r.resourceTemplates,"uriTemplate",a,s)}},"claimsCapabilityResolver");function Qc(e,t){let r=[];for(let o of Ie){let i=e[o.option];if(i!==void 0)for(let a of i){let s=Br(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}"`)}}if(r.length>0)throw new x(`MCP capability filter policy "${t}" - with accessControl.mode "rolesAndGroups", a capability cannot set both "public": true and roles/groups ("public" opens it to everyone, roles/groups restrict it). Remove one of the two on: ${r.join(", ")}`)}n(Qc,"assertNoConflictingMarkup");function ed(e,t){let r=[];for(let o of Ie){let i=e[o.option];if(i!==void 0)for(let a of i){let s=Br(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 x(`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(ed,"assertNoMarkup");function td(e,t){let r=e.identifier;if(r===void 0)throw new x(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);if(r.module===null||typeof r.module!="object")throw new x(`MCP capability filter policy "${t}" - accessControl.identifier.module must reference a module, e.g. $import(./modules/mcp-access-control)`);if(!r.export)throw new x(`MCP capability filter policy "${t}" - accessControl.identifier.export must be specified`);let o=r.module[r.export];if(typeof o!="function")throw new x(`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(td,"buildCustomResolver");function rd(e,t){let r=e.accessControl,o=r?.mode??"allPublic";if(o==="function"){if(r===void 0)throw new x(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);return td(r,t)}if(o==="rolesAndGroups")return Qc(e,t),Yo;ed(e,t)}n(rd,"buildCapabilityResolver");function nd(e){let t={};for(let r of Ie){let o=e[r.option];if(o===void 0)continue;let i=new Map;for(let a of o){let s=cd(a,r.itemProperty);s!==void 0&&i.set(s.key,s)}t[r.option]=i}return t}n(nd,"buildProjectionMaps");function jr(e){return e===void 0?void 0:Ie.find(t=>t.listMethod===e)}n(jr,"findListRule");function od(e){return e===void 0?void 0:Ie.find(t=>t.directMethods.includes(e))}n(od,"findDirectRule");function id(e){switch(e.method){case"tools/call":return{option:"tools",target:e.params.name};case"prompts/get":return{option:"prompts",target:e.params.name};case"resources/read":return{option:"resources",target:e.params.uri};default:return}}n(id,"directCapabilityAccess");function ad(e){let t=od(ht(e));if(t===void 0||!F(e.raw))return;let r=e.raw.params;if(!F(r))return;let o=r[t.itemProperty==="uri"?"uri":"name"];return typeof o=="string"?{option:t.option,target:o}:void 0}n(ad,"rawDirectCapabilityAccess");function sd(e){return Response.json(tr({...e==null?{}:{id:e},error:{code:dt.MethodNotFound,message:"Method not found"}}))}n(sd,"methodNotFoundResponse");function cd(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!F(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(cd,"buildProjection");function Wo(e){let t=e.base[e.property],r=e.overlay[e.property];return F(r)?F(t)?{...t,...r}:r:t}n(Wo,"mergeRecordProperty");function dd(e,t){let r={...e,...t.overlay},o=Wo({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let i=Wo({base:e,overlay:t.overlay,property:"_meta"});return i!==void 0&&(r._meta=i),r}n(dd,"applyProjection");function Vo(e,t,r,o){if(!F(e))return e;let i=e.result;if(!F(i))return e;let a=i[t.resultProperty];return!Array.isArray(a)||!a.every(s=>F(s)&&typeof s[t.itemProperty]=="string")?e:{...e,result:{...i,[t.resultProperty]:a.flatMap(s=>{if(!F(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?[]:[dd(s,u)]})}}}n(Vo,"filterAndProjectItems");function ud(e){let{envelope:t,responseBody:r,projectionMaps:o,allowedSets:i}=e;if(Array.isArray(r)){if(t.shape!=="batch")return r;let u=new Map;for(let l of t.messages){let p=jr(ht(l)),_=p===void 0?void 0:$o(l.id);p!==void 0&&_!==void 0&&u.set(_,p)}return u.size===0?r:r.map(l=>{if(!F(l)||"error"in l)return l;let p=$o(l.id),_=p===void 0?void 0:u.get(p),A=_===void 0?void 0:o[_.option];return _===void 0||A===void 0?l:Vo(l,_,A,i?.[_.option])})}if(t.shape!=="single"||!F(r)||"error"in r)return r;let a=t.messages[0],s=jr(a===void 0?void 0:ht(a)),c=s===void 0?void 0:o[s.option];return s===void 0||c===void 0?r:Vo(r,s,c,i?.[s.option])}n(ud,"filterResponseBody");function ld(e){return e.headers.get("content-type")?.includes("json")??!1}n(ld,"isJsonResponse");var Hr=class extends Lt{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=nd(o),this.#t=rd(o,r)}async handler(t,r){let o=await Jo(t);if(o===null)return t;let i=this.#t!==void 0&&this.#o(o)?await this.#a(t,r):void 0;for(let s of o.messages){let c=s.type==="request"?id(s):ad(s);if(c===void 0)continue;let u=this.#e[c.option];if(u===void 0)continue;let l=i?.[c.option];if(!u.has(c.target)||l!==void 0&&!l.has(c.target))return sd(s.type==="request"?s.id:s.id??void 0)}if(!this.#i(o))return t;let a=this.#e;return r.addResponseSendingHook(async s=>{if(!ld(s))return s;let c;try{c=await s.clone().json()}catch{return s}let u=ud({envelope:o,responseBody:c,projectionMaps:a,allowedSets:i});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}#o(t){return t.messages.some(r=>{let o=ht(r);return o===void 0?!1:Ie.some(i=>this.#e[i.option]===void 0?!1:i.listMethod===o||i.directMethods.includes(o))})}#i(t){return t.messages.some(r=>{let o=jr(ht(r));return o!==void 0&&this.#e[o.option]!==void 0})}async#a(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 Ie)this.#e[u.option]!==void 0&&(c[u.option]=new Set);return c}let a={};for(let s of Ie){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 p of u)typeof p=="string"&&c.has(p)&&l.add(p);a[s.option]=l}return a}};var Lr;Lr=globalThis.crypto;async function pd(e){return(await Lr).getRandomValues(new Uint8Array(e))}n(pd,"getRandomValues");async function md(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await pd(e-o.length);for(let a of i)a<r&&(o+=t[a%t.length])}return o}n(md,"random");async function fd(e){return await md(e)}n(fd,"generateVerifier");async function hd(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(hd,"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 fd(e),r=await hd(t);return{code_verifier:t,code_challenge:r}}n(Nr,"pkceChallenge");Z();var j=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"}),or=Nt({resource:m().url(),authorization_servers:w(j).optional(),jwks_uri:m().url().optional(),scopes_supported:w(m()).optional(),bearer_methods_supported:w(m()).optional(),resource_signing_alg_values_supported:w(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:se().optional(),authorization_details_types_supported:w(m()).optional(),dpop_signing_alg_values_supported:w(m()).optional(),dpop_bound_access_tokens_required:se().optional()}),gt=Nt({issuer:m(),authorization_endpoint:j,token_endpoint:j,registration_endpoint:j.optional(),scopes_supported:w(m()).optional(),response_types_supported:w(m()),response_modes_supported:w(m()).optional(),grant_types_supported:w(m()).optional(),token_endpoint_auth_methods_supported:w(m()).optional(),token_endpoint_auth_signing_alg_values_supported:w(m()).optional(),service_documentation:j.optional(),revocation_endpoint:j.optional(),revocation_endpoint_auth_methods_supported:w(m()).optional(),revocation_endpoint_auth_signing_alg_values_supported:w(m()).optional(),introspection_endpoint:m().optional(),introspection_endpoint_auth_methods_supported:w(m()).optional(),introspection_endpoint_auth_signing_alg_values_supported:w(m()).optional(),code_challenge_methods_supported:w(m()).optional(),client_id_metadata_document_supported:se().optional()}),gd=Nt({issuer:m(),authorization_endpoint:j,token_endpoint:j,userinfo_endpoint:j.optional(),jwks_uri:j,registration_endpoint:j.optional(),scopes_supported:w(m()).optional(),response_types_supported:w(m()),response_modes_supported:w(m()).optional(),grant_types_supported:w(m()).optional(),acr_values_supported:w(m()).optional(),subject_types_supported:w(m()),id_token_signing_alg_values_supported:w(m()),id_token_encryption_alg_values_supported:w(m()).optional(),id_token_encryption_enc_values_supported:w(m()).optional(),userinfo_signing_alg_values_supported:w(m()).optional(),userinfo_encryption_alg_values_supported:w(m()).optional(),userinfo_encryption_enc_values_supported:w(m()).optional(),request_object_signing_alg_values_supported:w(m()).optional(),request_object_encryption_alg_values_supported:w(m()).optional(),request_object_encryption_enc_values_supported:w(m()).optional(),token_endpoint_auth_methods_supported:w(m()).optional(),token_endpoint_auth_signing_alg_values_supported:w(m()).optional(),display_values_supported:w(m()).optional(),claim_types_supported:w(m()).optional(),claims_supported:w(m()).optional(),service_documentation:m().optional(),claims_locales_supported:w(m()).optional(),ui_locales_supported:w(m()).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:j.optional(),op_tos_uri:j.optional(),client_id_metadata_document_supported:se().optional()}),ir=ye({...gd.shape,...gt.pick({code_challenge_methods_supported:!0}).shape}),Ke=ye({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:Yn.number().optional(),scope:m().optional(),refresh_token:m().optional()}).strip(),Qo=ye({error:m(),error_description:m().optional(),error_uri:m().optional()}),Xo=j.optional().or(Wn("").transform(()=>{})),yd=ye({redirect_uris:w(j),token_endpoint_auth_method:m().optional(),grant_types:w(m()).optional(),response_types:w(m()).optional(),client_name:m().optional(),client_uri:j.optional(),logo_uri:Xo,scope:m().optional(),contacts:w(m()).optional(),tos_uri:Xo,policy_uri:m().optional(),jwks_uri:j.optional(),jwks:Kn().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),ar=ye({client_id:m(),client_secret:m().optional(),client_id_issued_at:xr().optional(),client_secret_expires_at:xr().optional()}).strip(),yt=yd.merge(ar),sg=ye({error:m(),error_description:m().optional()}).strip(),cg=ye({token:m(),token_type_hint:m().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}},_t=class extends k{static{n(this,"InvalidRequestError")}};_t.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 Me=class extends k{static{n(this,"UnauthorizedClientError")}};Me.errorCode="unauthorized_client";var wt=class extends k{static{n(this,"UnsupportedGrantTypeError")}};wt.errorCode="unsupported_grant_type";var bt=class extends k{static{n(this,"InvalidScopeError")}};bt.errorCode="invalid_scope";var Rt=class extends k{static{n(this,"AccessDeniedError")}};Rt.errorCode="access_denied";var pe=class extends k{static{n(this,"ServerError")}};pe.errorCode="server_error";var It=class extends k{static{n(this,"TemporarilyUnavailableError")}};It.errorCode="temporarily_unavailable";var Ct=class extends k{static{n(this,"UnsupportedResponseTypeError")}};Ct.errorCode="unsupported_response_type";var St=class extends k{static{n(this,"UnsupportedTokenTypeError")}};St.errorCode="unsupported_token_type";var vt=class extends k{static{n(this,"InvalidTokenError")}};vt.errorCode="invalid_token";var At=class extends k{static{n(this,"MethodNotAllowedError")}};At.errorCode="method_not_allowed";var xt=class extends k{static{n(this,"TooManyRequestsError")}};xt.errorCode="too_many_requests";var qe=class extends k{static{n(this,"InvalidClientMetadataError")}};qe.errorCode="invalid_client_metadata";var kt=class extends k{static{n(this,"InsufficientScopeError")}};kt.errorCode="insufficient_scope";var Tt=class extends k{static{n(this,"InvalidTargetError")}};Tt.errorCode="invalid_target";var ri={[_t.errorCode]:_t,[Ee.errorCode]:Ee,[Oe.errorCode]:Oe,[Me.errorCode]:Me,[wt.errorCode]:wt,[bt.errorCode]:bt,[Rt.errorCode]:Rt,[pe.errorCode]:pe,[It.errorCode]:It,[Ct.errorCode]:Ct,[St.errorCode]:St,[vt.errorCode]:vt,[At.errorCode]:At,[xt.errorCode]:xt,[qe.errorCode]:qe,[kt.errorCode]:kt,[Tt.errorCode]:Tt};function _d(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(_d,"isClientAuthMethod");var Jr="code",Gr="S256";function wd(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&_d(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(wd,"selectClientAuthMethod");function bd(e,t,r,o){let{client_id:i,client_secret:a}=t;switch(e){case"client_secret_basic":Rd(i,a,r);return;case"client_secret_post":Id(i,a,o);return;case"none":Cd(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(bd,"applyClientAuthentication");function Rd(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(Rd,"applyBasicAuth");function Id(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(Id,"applyPostAuth");function Cd(e,t){t.set("client_id",e)}n(Cd,"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 Me)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,p=i;if(!p&&s?.resourceMetadataUrl&&(p=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:p},a)}catch{}(l!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:p?.toString(),resourceMetadata:c,authorizationServerMetadata:l})}else{let O=await Td(t,{resourceMetadataUrl:p,fetchFn:a});u=O.authorizationServerUrl,l=O.authorizationServerMetadata,c=O.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:p?.toString(),resourceMetadata:c,authorizationServerMetadata:l})}let _=await Sd(t,e,c),A=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,z=e.clientMetadataUrl;if(z&&!Kr(z))throw new qe(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${z}`);if(O&&z)y={client_id:z},await e.saveClientInformation?.(y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Ln=await Md(u,{metadata:l,clientMetadata:e.clientMetadata,scope:A,fetchFn:a});await e.saveClientInformation(Ln),y=Ln}}let E=!e.redirectUrl;if(r!==void 0||E){let O=await Od(e,u,{metadata:l,resource:_,authorizationCode:r,fetchFn:a});return await e.saveTokens(O),"AUTHORIZED"}let T=await e.tokens();if(T?.refresh_token)try{let O=await Ed(u,{metadata:l,clientInformation:y,refreshToken:T.refresh_token,resource:_,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(O),"AUTHORIZED"}catch(O){if(!(!(O instanceof k)||O instanceof pe))throw O}let H=e.state?await e.state():void 0,{authorizationUrl:Be,codeVerifier:X}=await Ud(u,{metadata:l,clientInformation:y,state:H,redirectUrl:e.redirectUrl,scope:A,resource:_});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 Sd(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(Sd,"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 xd(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 or.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 vd(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(vd,"buildWellKnownPath");async function ni(e,t,r=fetch){return await Wr(e,{"MCP-Protocol-Version":t},r)}n(ni,"tryMetadataDiscovery");function Ad(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(Ad,"shouldAttemptFallback");async function xd(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=vd(t,i.pathname);s=new URL(u,o?.metadataServerUrl??i),s.search=i.search}let c=await ni(s,a,r);if(!o?.metadataUrl&&Ad(c,i.pathname)){let u=new URL(`/.well-known/${t}`,i);c=await ni(u,a,r)}return c}n(xd,"discoverMetadataWithFallback");function kd(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(kd,"buildDiscoveryUrls");async function si(e,{fetchFn:t=fetch,protocolVersion:r=kr}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=kd(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"?gt.parse(await c.json()):ir.parse(await c.json())}}}n(si,"discoverAuthorizationServerMetadata");async function Td(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(Td,"discoverOAuthServerInfo");async function Ud(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,p=u.code_challenge;return c.searchParams.set("response_type",Jr),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",p),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(Ud,"startAuthorization");function Pd(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(Pd,"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 p=t?.token_endpoint_auth_methods_supported??[],_=wd(o,p);bd(_,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 Ed(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(Ed,"refreshAuthorization");async function Od(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=Pd(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(Od,"fetchToken");async function Md(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 yt.parse(await s.json())}n(Md,"registerClient");var Vr="zuplo.com",qd=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),Dd=[".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 zd(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(zd,"strictFaviconHref");var sr=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):zd(e)}n(Yr,"resolveIconHref");function jd(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(jd,"hostnameFromHost");function Hd(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(Hd,"isLocalOrAddressHost");function Bd(e){let t=jd(e).toLowerCase().replace(/\.$/,"");if(Hd(t)||Dd.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=qd.has(o)?3:2;return r.slice(-i).join(".")}n(Bd,"inferFaviconDomain");function Xr(e){return{src:Yr(Bd(e)),mimeType:"image/png",sizes:["128x128"]}}n(Xr,"resolveMcpFaviconIcon");function cr(e){try{return Xr(new URL(e).host)}catch{return}}n(cr,"resolveMcpFaviconIconFromUrl");function Se(e){let t=ee().connectionsById.get(e);if(!t)throw new x(`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 dr(e){let t=ee().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new x(`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(dr,"getUpstreamAuthConfig");function We(e,t){let r=dr({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new x(`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=dr({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new x(`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 Ld(e){try{await e.cancel()}catch{}}n(Ld,"cancelReader");async function ur(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 Ld(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(ur,"readBoundedByteStream");var Nd=2,Jd=1024*1024,Gd=1e4,Fd=new Set([301,302,303,307,308]),$d=["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 Zd(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(Zd,"assertContentLengthWithinLimit");async function Kd(e,t,r){return Zd(e,t,r),ur(e.body,{maxBytes:t,createLimitError:n(()=>new h({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}}),"createLimitError")})}n(Kd,"readBoundedResponseBody");function Wd(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(Wd,"responseFromBufferedBody");function Vd(e,t){if(!Fd.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(Vd,"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 Yd(e,t){throw e instanceof h&&Jt(e.extensionMembers?.[g])?e:new h({message:"Outbound fetch failed.",extensionMembers:{[g]:t}},{cause:e})}n(Yd,"normalizeFetchError");function Ut(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&&J(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(Ut,"logOutboundFailure");async function Xd(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";Ut(e,{event:l?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:i,method:c,host:M(a),error:u,extra:{abortReason:s()}}),Yd(u,i)}}n(Xd,"fetchWithNormalizedError");function Qd(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(Qd,"assertRedirectAllowed");function eu(e,t){let r=new Headers(e);for(let o of $d)r.delete(o);for(let o of t)r.delete(o);return r}n(eu,"stripCrossOriginHeaders");function tu(e,t,r,o,i){let a={...e,method:t,redirect:"manual",signal:r};return o&&(a.headers=eu(e.headers,i)),a}n(tu,"buildRedirectInit");function ru(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(ru,"buildInitialRequestInit");function nu(e){let t=Ve(e.currentInput,e.currentInit);Qd({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:tu(e.currentInit,t,e.signal,i,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(nu,"followRedirect");async function en(e,t,r){let o=r.problemCode??"invalid_request",i=r.maxRedirects??Nd,a=r.maxResponseBytes??Jd,s=r.timeoutMs??Gd,c=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],l=r.context,p=new AbortController,_=li(p,t.signal),A=!1,y=setTimeout(()=>{A=!0,p.abort()},s),E=e,T=ru(e,t,p.signal),H;try{H=pi(Qr(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(X){throw Ut(l,{event:"outbound_url_blocked",problemCode:o,method:Ve(e,t),host:M(Qr(e)),error:X}),clearTimeout(y),_?.(),X}let Be=0;try{for(;;){let X=await Xd(l,c,E,T,o,H,()=>A?`timeout_after_${s}ms`:void 0),O=Vd(X,H);if(O!==void 0)try{let z=nu({currentInput:E,currentInit:T,currentUrl:H,redirectUrl:O,redirects:Be,maxRedirects:i,problemCode:o,validateUrl:r.validateUrl,signal:p.signal,additionalCrossOriginStrippedHeaders:u});E=z.currentInput,T=z.currentInit,H=z.currentUrl,Be=z.redirects;continue}catch(z){throw Ut(l,{event:"outbound_redirect_blocked",problemCode:o,method:Ve(E,T),host:M(H),error:z,extra:{redirects:Be,maxRedirects:i,redirectTargetHost:M(O)}}),z}try{return Wd(X,await Kd(X,a,o))}catch(z){throw Ut(l,{event:"outbound_response_size_exceeded",problemCode:o,method:Ve(E,T),host:M(H),error:z,extra:{maxResponseBytes:a,status:X.status}}),z}}}finally{clearTimeout(y),_?.()}}n(en,"runSafeOutboundExchange");async function Pt(e,t,r){let o=await en(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(i){throw Ut(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Ve(e,t),host:M(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(Pt,"runSafeOutboundJsonExchange");function mi(e,t={},r={}){return en(e,t,{...r,validateUrl:mt})}n(mi,"fetchConfiguredOutbound");function fi(e,t={},r={}){return Pt(e,t,{...r,validateUrl:mt})}n(fi,"fetchConfiguredOutboundJson");function lr(e,t={},r={}){return Pt(e,t,{...r,validateUrl:Oo})}n(lr,"fetchIdentityProviderJson");function hi(e,t={},r={}){return Pt(e,t,{...r,validateUrl:Xt})}n(hi,"fetchCimdClientMetadataJson");function gi(e,t={},r={}){return Pt(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 ou}from"jose";var iu=new TextEncoder,au="MCP gateway could not initialize secure key material.",su=32,yi=new Map,_i=new Map,cu;function du(){return cu??Nn.instance.authPrivateKey}n(du,"readAuthPrivateKey");function wi(e){return new Q(au,e===void 0?void 0:{cause:e})}n(wi,"createGeneratedKeyMaterialError");function bi(e,t){let r=ou.decode(t);if(r.byteLength!==su)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(bi,"decodeJwkKeyField");function uu(e){let t=du();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=iu.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(uu,"decodeGeneratedKeyMaterial");function lu(e){let t=yi.get(e);return t||(t=uu(e),yi.set(e,t)),t}n(lu,"getMasterKeyMaterial");async function oe(e){let t=_i.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(lu(e.keyMaterialPurpose));return _i.set(e.purpose,r),r}n(oe,"readCachedDerivedKey");var pu="SHA-256",mu=32,fu="zuplo-mcp-gateway:",hu=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 gu(e,t);return r.set(t,i),i}n(ve,"deriveGatewaySigningKey");async function gu(e,t){let r=G(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=hu.encode(`${fu}${t}`),a=await crypto.subtle.deriveBits({name:"HKDF",hash:pu,salt:new Uint8Array,info:G(i)},o,mu*8);return new Uint8Array(a)}n(gu,"hkdfExpand");var vi=900,yu=900,_u=ho.extend({id:jo}),wu=_u.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),Ai=Tr.extend({id:Ho,purpose:d.literal("browser_connect")}),bu=Tr.extend({purpose:d.literal("browser_connect")}),Ru=Ai.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),xi=vi*1e3;async function ki(){return oe({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>ve(e,"oauth-state"),"derive")})}n(ki,"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 ki())}n(Ui,"signOAuthState");async function pr(e){try{let{payload:t}=await Ci(e,await ki(),{algorithms:[V],issuer:$,audience:W});return wu.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(pr,"verifyOAuthState");async function Pi(e){let t=Math.floor(Date.now()/1e3)+yu,r=bu.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 Ru.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 Iu(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(Iu,"buildConnectRequiredMessage");async function Cu(e){let t=q(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(Cu,"buildGatewayBrowserTicketUrl");function Su(e){return B().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(Su,"buildGatewayConnectPath");async function tn(e){return Cu({...e,path:Su(e.upstreamServerId),redirect:!0})}n(tn,"buildGatewayConnectUrl");async function mr(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:Iu(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(mr,"buildRedirectConnectRequiredResponse");function Mi(e){return vu({...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(Mi,"buildAdminConnectRequiredResponse");function vu(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(vu,"buildAdminSetupRequiredResponse");var qi=12;async function Di(e){let t=await crypto.subtle.digest("SHA-256",G(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,qi)}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,qi)}n(Xe,"fingerprintConnectionIdentity");function Et(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(Et,"describeAccessTokenState");Z();var zi=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function Au(e,t){return e&&e.length>0?e.join(t):void 0}n(Au,"joinOAuthScopes");function xu(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of zi)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(xu,"sanitizeAuthorizationServerMetadata");function ji(e){let t=xu(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(ji,"sanitizeOAuthDiscoveryState");function Hi(e){let t=new URL(e);for(let r of zi){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 fr(e){let t=new URL(e);return K(t)&&Qn(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(fr,"normalizeLoopbackOAuthRedirectUri");function Bi(e){return Au(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(Bi,"readProtectedResourceMetadataScope");function ku(e){return`Zuplo MCP Gateway - ${e}`}n(ku,"buildGatewayOAuthClientName");function Tu(e,t){return e&&e.length>0?e.join(t):void 0}n(Tu,"joinOAuthScopeList");function Uu(e){if(e.clientRegistration.mode!=="auto")return Tu(e.scopes,e.scopeDelimiter)}n(Uu,"readPublicClientMetadataScope");function rn(e){return new URL(B().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:ku(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=Uu(o);return{client_id:rn({origin:e,upstreamServerId:t}),...nn({origin:e,upstreamServerId:t,redirectUri:fr(new URL(o.redirectPath,e)).toString(),scope:i})}}n(Li,"buildOAuthClientMetadataDocument");Z();import{base64url as Ae}from"jose";var Pu="SHA-256",Qe="AES-GCM",Eu=12,an="zuplo-secret",sn=1,Ni="generated:auth_private_key:token-encryption",Ou=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(Pu,G(e));return crypto.subtle.importKey("raw",t,{name:Qe},!1,["encrypt","decrypt"])},"derive")})}n(on,"getEncryptionKey");function Ji(e){return G(new TextEncoder().encode(`${an}:v${e.version}:${e.keyId}`))}n(Ji,"getAssociatedData");function Mu(e){return`${an}:v${e.version}:${Ae.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(Mu,"encodeEnvelope");function qu(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 Ou.parse(JSON.parse(o))}n(qu,"decodeEnvelope");async function me(e){let t=await on(),r=crypto.getRandomValues(new Uint8Array(Eu)),o={version:sn,keyId:Ni},i=await crypto.subtle.encrypt({name:Qe,iv:r,additionalData:Ji(o)},t,new TextEncoder().encode(e));return Mu({...o,algorithm:Qe,iv:Ae.encode(r),ciphertext:Ae.encode(new Uint8Array(i))})}n(me,"encryptSecret");async function xe(e){let t=qu(e);if(t){let s=await on(),c=await crypto.subtle.decrypt({name:Qe,iv:G(Ae.decode(t.iv)),additionalData:Ji(t)},s,G(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:G(Ae.decode(r))},i,G(Ae.decode(o)));return new TextDecoder().decode(a)}n(xe,"decryptSecret");var Du=d.union([yt,ar]),zu=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:or.optional(),authorizationServerMetadata:d.union([gt,ir]).optional()}).passthrough(),ju="Bearer",Hu="__zuplo_refresh_only_upstream_access_token__";function Gi(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Gi,"splitScopes");function Bu(e){return Ne.parse(e)}n(Bu,"parsePkceCodeVerifier");function Lu(e){if(typeof e.expires_in=="number")return I(new Date(Date.now()+e.expires_in*1e3))}n(Lu,"readTokenExpiry");async function Nu(e){if(e!==void 0)return me(JSON.stringify(e))}n(Nu,"encryptJson");async function Ju(e,t){if(!e)return;let r=await xe(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(Ju,"decryptJson");function Gu(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(Gu,"clientInformationAllowsRedirectUri");function Fu(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(Fu,"clientInformationMatchesCurrentClientMetadataUrl");function $u(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n($u,"isUrlBasedClientInformation");function Zu(e,t){return t===void 0?e:{...e,scope:t}}n(Zu,"applyOAuthClientMetadataScope");function Ku(e,t){return Bi({state:e,delimiter:t})}n(Ku,"readResourceMetadataScope");function Wu(e,t){return e&&e.length>0?e.join(t):void 0}n(Wu,"joinOAuthScopeList");function Vu(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new x(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return yt.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(Vu,"buildManualOAuthClientInformation");function Yu(e,t){let r=rn({origin:new URL(t).origin,upstreamServerId:e});return Kr(r)?r:void 0}n(Yu,"buildClientMetadataUrl");function Xu(e){for(let t of e)if(t!==void 0)return t}n(Xu,"firstDefined");function Qu(e){let t=We(e.target.upstreamServerId,e.target.authProfileId),r=Wu(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:Vu({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let i=Yu(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(Qu,"buildInitialOAuthClientSetup");function el(e,t){if(t===void 0)return Xu([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(el,"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=Qu({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.clientMetadataValue=r.clientMetadata,this.configuredScope=r.configuredScope,this.scopeDelimiter=r.scopeDelimiter,this.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=el(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 Zu(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,L()?.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"),!$u({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Nu(t),await this.syncPendingState(!1)))}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=ji(zu.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,L()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:M(r.authorizationServerUrl),resourceMetadataHost:M(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=Ku(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&&L()?.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 xe(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let c={id:this.connection?.id??Qt(),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:Lu(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await R().upsertUpstreamConnection(c),L()?.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:Bu(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()+xi)),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 Ju(this.encryptedClientInformation,Du)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&(!Gu(t,this.redirectUriValue)||!Fu({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=ar.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"){L()?.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 xe(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await xe(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=L();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??Hu,token_type:ju,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=L();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 tl=3e4,rl=256*1024,nl=2,ol="does not support dynamic client registration",il=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],al=["HTTP 403 Forbidden","Access Denied","permission to access"],sl=new Set(["access_denied","invalid_client","invalid_grant","invalid_request","invalid_scope","invalid_target","unauthorized_client","unsupported_grant_type"]);function cl(e){return e instanceof Error&&e.message.includes(ol)}n(cl,"isDynamicClientRegistrationUnsupported");function dl(e){return e instanceof Error&&il.some(t=>e.message.includes(t))}n(dl,"isProtectedResourceMetadataUnavailable");function ul(e){return e instanceof Error&&al.some(t=>e.message.includes(t))}n(ul,"isUpstreamProviderAccessDenied");function ll(e){return e instanceof k&&sl.has(e.errorCode)}n(ll,"isStoredConnectionReconsentError");function pl(e){if(e.error instanceof h&&e.error.extensionMembers?.[g]!==void 0)return e.error;if(cl(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(dl(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(ul(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(pl,"mapUpstreamOAuthSetupError");function ml(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(ml,"readOAuthFetchRequest");function fl(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(fl,"responseLooksJson");function hl(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(hl,"responseLooksHtml");function gl(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(gl,"throwUpstreamHtmlError");function yl(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(yl,"readUpstreamOAuthErrorBody");function _l(e){let{error:t,errorDescription:r}=yl(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.request.method??"GET",host:M(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(_l,"logUpstreamOAuthHttpError");function $i(e){return async(t,r)=>{let o=ml(t),i=L(),a=Date.now(),s=await mi(t,r,{maxRedirects:nl,maxResponseBytes:rl,problemCode:"upstream_token_exchange_failed",timeoutMs:tl}),c=await s.clone().text();if(i?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:o.method??"GET",host:M(o.url),path:o.url.pathname,status:s.status,durationMs:Date.now()-a,responseChars:c.length},"Upstream OAuth HTTP request completed"),s.ok||_l({log:i,upstreamServerId:e,request:o,response:s,body:c}),!s.ok&&hl(s,c)&&gl({upstreamServerId:e,request:o,response:s,body:c}),!fl(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){L()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:M(e.serverUrl),resourceMetadataHost:M(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=M(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),J(t,"error",e.error),L()?.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=pl({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(Vi,"runUpstreamOAuth");async function wl(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(wl,"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=Et(e.connection),r=!!e.forceRefresh,o=!r&&t==="usable",i=L(),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||!ll(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 bl(e){let t=await pr(e.stateToken),r=await R().consumeUpstreamOAuthState({id:t.id,now:I(new Date)}),o=Rl(r);return Il({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),Cl(o),o}n(bl,"consumeStoredCallbackState");function Rl(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(Rl,"readConsumedCallbackState");function Il(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(Il,"assertStoredCallbackStateMatches");function Cl(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new h({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}})}n(Cl,"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),Mi(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),mr(t)}n(Fi,"buildOAuthConnectRequiredResponse");async function Qi(e){let t=await bl({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Kt(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 wl(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 Sl,SignJWT as vl}from"jose";var ta=1e4,ra=64*1024,na=2,Al=300,ne=d.string().min(1),xl=d.object({access_token:ne,issued_token_type:d.literal(Pr),token_type:d.string().optional(),expires_in:d.number().int().positive().optional(),scope:ne.optional()}).passthrough(),kl=d.object({id_token:ne,token_type:ne.optional(),expires_in:d.number().int().positive().optional(),refresh_token:ne.optional(),scope:ne.optional()}).passthrough(),Tl=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 Ul(e){return e.replaceAll("\\n",`
|
|
25
|
+
import{$ as Z,$b as kc,$c as vo,Ac as go,Ad as Lo,Bc as yo,Bd as No,Cb as Qn,Cc as _o,Cd as R,Db as K,Dc as wo,Dd as v,Eb as eo,Ec as ee,Ed as G,Fb as to,Fc as B,Fd as le,Gb as q,Gc as bo,Gd as U,Hb as ro,Hc as Ro,Hd as er,Ib as Le,Ic as I,Id as Dc,Jb as no,Jc as de,Jd as zc,Kb as Ne,Kc as $e,Lb as g,Lc as J,Mb as Je,Mc as M,Nb as Ge,Nc as Io,O as $n,Ob as _e,Oc as L,P as m,Pb as we,Pc as Co,Q as Zn,Qb as Jt,Qc as Re,R as xr,Rb as oo,Rc as Ur,S as se,Sb as re,Sc as Wt,T as Kn,Tb as io,Tc as Pr,U as w,Ub as ce,Uc as Vt,V as ye,Vb as b,Vc as pt,W as Nt,Wb as Gt,Wc as Ze,X as Wn,Xb as N,Xc as So,Y as Vn,Yb as be,Yc as ue,Z as Yn,Zb as Ac,Zc as Er,_ as d,_b as xc,_c as Or,ac as Tc,ad as Yt,bc as Uc,bd as Mr,cc as Pc,cd as qr,dc as Ec,dd as Ao,ec as Oc,ed as D,fa as Xn,fc as Mc,fd as xo,gc as qc,gd as ko,hc as ao,hd as Dr,ic as so,id as To,jc as co,jd as Uo,k as ae,kc as Ft,kd as zr,lc as kr,ld as Po,mc as $t,md as Pe,nc as Zt,nd as Eo,oc as dt,od as mt,pc as uo,pd as Oo,qc as lo,qd as Xt,r as Ue,rc as po,rd as ft,s as Jn,sc as ut,sd as Mo,tc as mo,td as qo,uc as Fe,ud as Do,vc as fo,vd as zo,wc as Tr,wd as jo,x as Fn,xc as ho,xd as Ho,y as Lt,yc as lt,yd as Bo,zc as Kt,zd as Qt}from"../chunk-JPPAUB3E.js";import"../chunk-US6ITPGV.js";import{a as C}from"../chunk-7WS4HIGR.js";import{a as Jo}from"../chunk-SNZSLL63.js";import{a as Gn}from"../chunk-FPZAMUNA.js";import"../chunk-QWO5UTVQ.js";import{V as Q,W as h,X as x,Y as Nn,Z as Bt}from"../chunk-VCMIY3WJ.js";import{a as n}from"../chunk-2WLR6ZDZ.js";Z();function jc(e){let t=Zt.safeParse(e);return t.success?t.data.id:void 0}n(jc,"parseJsonRpcRequestId");function Go(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return jc(t)}catch{return}}n(Go,"readJsonRpcRequestIdFromBody");function tr(e){return uo.parse({jsonrpc:$t,...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(tr,"jsonRpcErrorResponse");function Fo(e){return new po([lo.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Fo,"urlElicitationRequiredError");var nr=d.record(d.string(),d.unknown()),Hc=d.record(d.string(),d.unknown()),Ce=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:nr.optional(),roles:Ce,groups:Ce,public:d.boolean().optional()}).strict(),Lc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),_meta:nr.optional(),roles:Ce,groups:Ce,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:nr.optional(),roles:Ce,groups:Ce,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:nr.optional(),roles:Ce,groups:Ce,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(),Ie=[{option:"tools",listMethod:"tools/list",resultProperty:"tools",itemProperty:"name",directMethods:["tools/call"]},{option:"prompts",listMethod:"prompts/list",resultProperty:"prompts",itemProperty:"name",directMethods:["prompts/get"]},{option:"resources",listMethod:"resources/list",resultProperty:"resources",itemProperty:"uri",directMethods:["resources/read"]},{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 F(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(F,"isRecord");function ht(e){return typeof e.method=="string"?e.method:void 0}n(ht,"messageMethod");function $o(e){return typeof e=="string"||typeof e=="number"||e===null?JSON.stringify(e):void 0}n($o,"correlationKey");function Zo(e){if(!Array.isArray(e))return;let t=e.filter(r=>typeof r=="string");return t.length>0?t:void 0}n(Zo,"asStringArray");function Ko(e,t){if(!F(e))return[];let r=t in e?e[t]:t.split(".").reduce((o,i)=>F(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(Ko,"readClaimValues");function Br(e,t){if(typeof e=="string")return{key:e,public:!1};if(!F(e))return;let r=e[t];if(typeof r=="string")return{key:r,roles:Zo(e.roles),groups:Zo(e.groups),public:e.public===!0}}n(Br,"normalizeEntry");function Xc(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(Xc,"isCallerAllowed");function rr(e,t,r,o){if(e===void 0)return;let i=[];for(let a of e){let s=Br(a,t);s!==void 0&&Xc(s,r,o)&&i.push(s.key)}return i}n(rr,"allowedKeys");var Yo=n((e,t,r)=>{let o=r.accessControl?.roleClaim??"roles",i=r.accessControl?.groupClaim??"groups",a=new Set(Ko(e.user?.data,o)),s=new Set(Ko(e.user?.data,i));return{tools:rr(r.tools,"name",a,s),prompts:rr(r.prompts,"name",a,s),resources:rr(r.resources,"uri",a,s),resourceTemplates:rr(r.resourceTemplates,"uriTemplate",a,s)}},"claimsCapabilityResolver");function Qc(e,t){let r=[];for(let o of Ie){let i=e[o.option];if(i!==void 0)for(let a of i){let s=Br(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}"`)}}if(r.length>0)throw new x(`MCP capability filter policy "${t}" - with accessControl.mode "rolesAndGroups", a capability cannot set both "public": true and roles/groups ("public" opens it to everyone, roles/groups restrict it). Remove one of the two on: ${r.join(", ")}`)}n(Qc,"assertNoConflictingMarkup");function ed(e,t){let r=[];for(let o of Ie){let i=e[o.option];if(i!==void 0)for(let a of i){let s=Br(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 x(`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(ed,"assertNoMarkup");function td(e,t){let r=e.identifier;if(r===void 0)throw new x(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);if(r.module===null||typeof r.module!="object")throw new x(`MCP capability filter policy "${t}" - accessControl.identifier.module must reference a module, e.g. $import(./modules/mcp-access-control)`);if(!r.export)throw new x(`MCP capability filter policy "${t}" - accessControl.identifier.export must be specified`);let o=r.module[r.export];if(typeof o!="function")throw new x(`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(td,"buildCustomResolver");function rd(e,t){let r=e.accessControl,o=r?.mode??"allPublic";if(o==="function"){if(r===void 0)throw new x(`MCP capability filter policy "${t}" - accessControl.mode "function" requires accessControl.identifier`);return td(r,t)}if(o==="rolesAndGroups")return Qc(e,t),Yo;ed(e,t)}n(rd,"buildCapabilityResolver");function nd(e){let t={};for(let r of Ie){let o=e[r.option];if(o===void 0)continue;let i=new Map;for(let a of o){let s=cd(a,r.itemProperty);s!==void 0&&i.set(s.key,s)}t[r.option]=i}return t}n(nd,"buildProjectionMaps");function jr(e){return e===void 0?void 0:Ie.find(t=>t.listMethod===e)}n(jr,"findListRule");function od(e){return e===void 0?void 0:Ie.find(t=>t.directMethods.includes(e))}n(od,"findDirectRule");function id(e){switch(e.method){case"tools/call":return{option:"tools",target:e.params.name};case"prompts/get":return{option:"prompts",target:e.params.name};case"resources/read":return{option:"resources",target:e.params.uri};default:return}}n(id,"directCapabilityAccess");function ad(e){let t=od(ht(e));if(t===void 0||!F(e.raw))return;let r=e.raw.params;if(!F(r))return;let o=r[t.itemProperty==="uri"?"uri":"name"];return typeof o=="string"?{option:t.option,target:o}:void 0}n(ad,"rawDirectCapabilityAccess");function sd(e){return Response.json(tr({...e==null?{}:{id:e},error:{code:dt.MethodNotFound,message:"Method not found"}}))}n(sd,"methodNotFoundResponse");function cd(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!F(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(cd,"buildProjection");function Wo(e){let t=e.base[e.property],r=e.overlay[e.property];return F(r)?F(t)?{...t,...r}:r:t}n(Wo,"mergeRecordProperty");function dd(e,t){let r={...e,...t.overlay},o=Wo({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let i=Wo({base:e,overlay:t.overlay,property:"_meta"});return i!==void 0&&(r._meta=i),r}n(dd,"applyProjection");function Vo(e,t,r,o){if(!F(e))return e;let i=e.result;if(!F(i))return e;let a=i[t.resultProperty];return!Array.isArray(a)||!a.every(s=>F(s)&&typeof s[t.itemProperty]=="string")?e:{...e,result:{...i,[t.resultProperty]:a.flatMap(s=>{if(!F(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?[]:[dd(s,u)]})}}}n(Vo,"filterAndProjectItems");function ud(e){let{envelope:t,responseBody:r,projectionMaps:o,allowedSets:i}=e;if(Array.isArray(r)){if(t.shape!=="batch")return r;let u=new Map;for(let l of t.messages){let p=jr(ht(l)),_=p===void 0?void 0:$o(l.id);p!==void 0&&_!==void 0&&u.set(_,p)}return u.size===0?r:r.map(l=>{if(!F(l)||"error"in l)return l;let p=$o(l.id),_=p===void 0?void 0:u.get(p),A=_===void 0?void 0:o[_.option];return _===void 0||A===void 0?l:Vo(l,_,A,i?.[_.option])})}if(t.shape!=="single"||!F(r)||"error"in r)return r;let a=t.messages[0],s=jr(a===void 0?void 0:ht(a)),c=s===void 0?void 0:o[s.option];return s===void 0||c===void 0?r:Vo(r,s,c,i?.[s.option])}n(ud,"filterResponseBody");function ld(e){return e.headers.get("content-type")?.includes("json")??!1}n(ld,"isJsonResponse");var Hr=class extends Lt{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=nd(o),this.#t=rd(o,r)}async handler(t,r){let o=await Jo(t);if(o===null)return t;let i=this.#t!==void 0&&this.#o(o)?await this.#a(t,r):void 0;for(let s of o.messages){let c=s.type==="request"?id(s):ad(s);if(c===void 0)continue;let u=this.#e[c.option];if(u===void 0)continue;let l=i?.[c.option];if(!u.has(c.target)||l!==void 0&&!l.has(c.target))return sd(s.type==="request"?s.id:s.id??void 0)}if(!this.#i(o))return t;let a=this.#e;return r.addResponseSendingHook(async s=>{if(!ld(s))return s;let c;try{c=await s.clone().json()}catch{return s}let u=ud({envelope:o,responseBody:c,projectionMaps:a,allowedSets:i});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}#o(t){return t.messages.some(r=>{let o=ht(r);return o===void 0?!1:Ie.some(i=>this.#e[i.option]===void 0?!1:i.listMethod===o||i.directMethods.includes(o))})}#i(t){return t.messages.some(r=>{let o=jr(ht(r));return o!==void 0&&this.#e[o.option]!==void 0})}async#a(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 Ie)this.#e[u.option]!==void 0&&(c[u.option]=new Set);return c}let a={};for(let s of Ie){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 p of u)typeof p=="string"&&c.has(p)&&l.add(p);a[s.option]=l}return a}};var Lr;Lr=globalThis.crypto;async function pd(e){return(await Lr).getRandomValues(new Uint8Array(e))}n(pd,"getRandomValues");async function md(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await pd(e-o.length);for(let a of i)a<r&&(o+=t[a%t.length])}return o}n(md,"random");async function fd(e){return await md(e)}n(fd,"generateVerifier");async function hd(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(hd,"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 fd(e),r=await hd(t);return{code_verifier:t,code_challenge:r}}n(Nr,"pkceChallenge");Z();var j=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"}),or=Nt({resource:m().url(),authorization_servers:w(j).optional(),jwks_uri:m().url().optional(),scopes_supported:w(m()).optional(),bearer_methods_supported:w(m()).optional(),resource_signing_alg_values_supported:w(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:se().optional(),authorization_details_types_supported:w(m()).optional(),dpop_signing_alg_values_supported:w(m()).optional(),dpop_bound_access_tokens_required:se().optional()}),gt=Nt({issuer:m(),authorization_endpoint:j,token_endpoint:j,registration_endpoint:j.optional(),scopes_supported:w(m()).optional(),response_types_supported:w(m()),response_modes_supported:w(m()).optional(),grant_types_supported:w(m()).optional(),token_endpoint_auth_methods_supported:w(m()).optional(),token_endpoint_auth_signing_alg_values_supported:w(m()).optional(),service_documentation:j.optional(),revocation_endpoint:j.optional(),revocation_endpoint_auth_methods_supported:w(m()).optional(),revocation_endpoint_auth_signing_alg_values_supported:w(m()).optional(),introspection_endpoint:m().optional(),introspection_endpoint_auth_methods_supported:w(m()).optional(),introspection_endpoint_auth_signing_alg_values_supported:w(m()).optional(),code_challenge_methods_supported:w(m()).optional(),client_id_metadata_document_supported:se().optional()}),gd=Nt({issuer:m(),authorization_endpoint:j,token_endpoint:j,userinfo_endpoint:j.optional(),jwks_uri:j,registration_endpoint:j.optional(),scopes_supported:w(m()).optional(),response_types_supported:w(m()),response_modes_supported:w(m()).optional(),grant_types_supported:w(m()).optional(),acr_values_supported:w(m()).optional(),subject_types_supported:w(m()),id_token_signing_alg_values_supported:w(m()),id_token_encryption_alg_values_supported:w(m()).optional(),id_token_encryption_enc_values_supported:w(m()).optional(),userinfo_signing_alg_values_supported:w(m()).optional(),userinfo_encryption_alg_values_supported:w(m()).optional(),userinfo_encryption_enc_values_supported:w(m()).optional(),request_object_signing_alg_values_supported:w(m()).optional(),request_object_encryption_alg_values_supported:w(m()).optional(),request_object_encryption_enc_values_supported:w(m()).optional(),token_endpoint_auth_methods_supported:w(m()).optional(),token_endpoint_auth_signing_alg_values_supported:w(m()).optional(),display_values_supported:w(m()).optional(),claim_types_supported:w(m()).optional(),claims_supported:w(m()).optional(),service_documentation:m().optional(),claims_locales_supported:w(m()).optional(),ui_locales_supported:w(m()).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:j.optional(),op_tos_uri:j.optional(),client_id_metadata_document_supported:se().optional()}),ir=ye({...gd.shape,...gt.pick({code_challenge_methods_supported:!0}).shape}),Ke=ye({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:Yn.number().optional(),scope:m().optional(),refresh_token:m().optional()}).strip(),Qo=ye({error:m(),error_description:m().optional(),error_uri:m().optional()}),Xo=j.optional().or(Wn("").transform(()=>{})),yd=ye({redirect_uris:w(j),token_endpoint_auth_method:m().optional(),grant_types:w(m()).optional(),response_types:w(m()).optional(),client_name:m().optional(),client_uri:j.optional(),logo_uri:Xo,scope:m().optional(),contacts:w(m()).optional(),tos_uri:Xo,policy_uri:m().optional(),jwks_uri:j.optional(),jwks:Kn().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),ar=ye({client_id:m(),client_secret:m().optional(),client_id_issued_at:xr().optional(),client_secret_expires_at:xr().optional()}).strip(),yt=yd.merge(ar),sg=ye({error:m(),error_description:m().optional()}).strip(),cg=ye({token:m(),token_type_hint:m().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}},_t=class extends k{static{n(this,"InvalidRequestError")}};_t.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 Me=class extends k{static{n(this,"UnauthorizedClientError")}};Me.errorCode="unauthorized_client";var wt=class extends k{static{n(this,"UnsupportedGrantTypeError")}};wt.errorCode="unsupported_grant_type";var bt=class extends k{static{n(this,"InvalidScopeError")}};bt.errorCode="invalid_scope";var Rt=class extends k{static{n(this,"AccessDeniedError")}};Rt.errorCode="access_denied";var pe=class extends k{static{n(this,"ServerError")}};pe.errorCode="server_error";var It=class extends k{static{n(this,"TemporarilyUnavailableError")}};It.errorCode="temporarily_unavailable";var Ct=class extends k{static{n(this,"UnsupportedResponseTypeError")}};Ct.errorCode="unsupported_response_type";var St=class extends k{static{n(this,"UnsupportedTokenTypeError")}};St.errorCode="unsupported_token_type";var vt=class extends k{static{n(this,"InvalidTokenError")}};vt.errorCode="invalid_token";var At=class extends k{static{n(this,"MethodNotAllowedError")}};At.errorCode="method_not_allowed";var xt=class extends k{static{n(this,"TooManyRequestsError")}};xt.errorCode="too_many_requests";var qe=class extends k{static{n(this,"InvalidClientMetadataError")}};qe.errorCode="invalid_client_metadata";var kt=class extends k{static{n(this,"InsufficientScopeError")}};kt.errorCode="insufficient_scope";var Tt=class extends k{static{n(this,"InvalidTargetError")}};Tt.errorCode="invalid_target";var ri={[_t.errorCode]:_t,[Ee.errorCode]:Ee,[Oe.errorCode]:Oe,[Me.errorCode]:Me,[wt.errorCode]:wt,[bt.errorCode]:bt,[Rt.errorCode]:Rt,[pe.errorCode]:pe,[It.errorCode]:It,[Ct.errorCode]:Ct,[St.errorCode]:St,[vt.errorCode]:vt,[At.errorCode]:At,[xt.errorCode]:xt,[qe.errorCode]:qe,[kt.errorCode]:kt,[Tt.errorCode]:Tt};function _d(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(_d,"isClientAuthMethod");var Jr="code",Gr="S256";function wd(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&_d(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(wd,"selectClientAuthMethod");function bd(e,t,r,o){let{client_id:i,client_secret:a}=t;switch(e){case"client_secret_basic":Rd(i,a,r);return;case"client_secret_post":Id(i,a,o);return;case"none":Cd(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(bd,"applyClientAuthentication");function Rd(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(Rd,"applyBasicAuth");function Id(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(Id,"applyPostAuth");function Cd(e,t){t.set("client_id",e)}n(Cd,"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 Me)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,p=i;if(!p&&s?.resourceMetadataUrl&&(p=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:p},a)}catch{}(l!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:p?.toString(),resourceMetadata:c,authorizationServerMetadata:l})}else{let O=await Td(t,{resourceMetadataUrl:p,fetchFn:a});u=O.authorizationServerUrl,l=O.authorizationServerMetadata,c=O.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:p?.toString(),resourceMetadata:c,authorizationServerMetadata:l})}let _=await Sd(t,e,c),A=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,z=e.clientMetadataUrl;if(z&&!Kr(z))throw new qe(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${z}`);if(O&&z)y={client_id:z},await e.saveClientInformation?.(y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Ln=await Md(u,{metadata:l,clientMetadata:e.clientMetadata,scope:A,fetchFn:a});await e.saveClientInformation(Ln),y=Ln}}let E=!e.redirectUrl;if(r!==void 0||E){let O=await Od(e,u,{metadata:l,resource:_,authorizationCode:r,fetchFn:a});return await e.saveTokens(O),"AUTHORIZED"}let T=await e.tokens();if(T?.refresh_token)try{let O=await Ed(u,{metadata:l,clientInformation:y,refreshToken:T.refresh_token,resource:_,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(O),"AUTHORIZED"}catch(O){if(!(!(O instanceof k)||O instanceof pe))throw O}let H=e.state?await e.state():void 0,{authorizationUrl:Be,codeVerifier:X}=await Ud(u,{metadata:l,clientInformation:y,state:H,redirectUrl:e.redirectUrl,scope:A,resource:_});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 Sd(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(Sd,"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 xd(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 or.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 vd(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(vd,"buildWellKnownPath");async function ni(e,t,r=fetch){return await Wr(e,{"MCP-Protocol-Version":t},r)}n(ni,"tryMetadataDiscovery");function Ad(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(Ad,"shouldAttemptFallback");async function xd(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=vd(t,i.pathname);s=new URL(u,o?.metadataServerUrl??i),s.search=i.search}let c=await ni(s,a,r);if(!o?.metadataUrl&&Ad(c,i.pathname)){let u=new URL(`/.well-known/${t}`,i);c=await ni(u,a,r)}return c}n(xd,"discoverMetadataWithFallback");function kd(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(kd,"buildDiscoveryUrls");async function si(e,{fetchFn:t=fetch,protocolVersion:r=kr}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=kd(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"?gt.parse(await c.json()):ir.parse(await c.json())}}}n(si,"discoverAuthorizationServerMetadata");async function Td(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(Td,"discoverOAuthServerInfo");async function Ud(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,p=u.code_challenge;return c.searchParams.set("response_type",Jr),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",p),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(Ud,"startAuthorization");function Pd(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(Pd,"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 p=t?.token_endpoint_auth_methods_supported??[],_=wd(o,p);bd(_,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 Ed(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(Ed,"refreshAuthorization");async function Od(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=Pd(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(Od,"fetchToken");async function Md(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 yt.parse(await s.json())}n(Md,"registerClient");var Vr="zuplo.com",qd=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),Dd=[".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 zd(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(zd,"strictFaviconHref");var sr=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):zd(e)}n(Yr,"resolveIconHref");function jd(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(jd,"hostnameFromHost");function Hd(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(Hd,"isLocalOrAddressHost");function Bd(e){let t=jd(e).toLowerCase().replace(/\.$/,"");if(Hd(t)||Dd.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=qd.has(o)?3:2;return r.slice(-i).join(".")}n(Bd,"inferFaviconDomain");function Xr(e){return{src:Yr(Bd(e)),mimeType:"image/png",sizes:["128x128"]}}n(Xr,"resolveMcpFaviconIcon");function cr(e){try{return Xr(new URL(e).host)}catch{return}}n(cr,"resolveMcpFaviconIconFromUrl");function Se(e){let t=ee().connectionsById.get(e);if(!t)throw new x(`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 dr(e){let t=ee().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new x(`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(dr,"getUpstreamAuthConfig");function We(e,t){let r=dr({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new x(`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=dr({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new x(`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 Ld(e){try{await e.cancel()}catch{}}n(Ld,"cancelReader");async function ur(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 Ld(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(ur,"readBoundedByteStream");var Nd=2,Jd=1024*1024,Gd=1e4,Fd=new Set([301,302,303,307,308]),$d=["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 Zd(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(Zd,"assertContentLengthWithinLimit");async function Kd(e,t,r){return Zd(e,t,r),ur(e.body,{maxBytes:t,createLimitError:n(()=>new h({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}}),"createLimitError")})}n(Kd,"readBoundedResponseBody");function Wd(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(Wd,"responseFromBufferedBody");function Vd(e,t){if(!Fd.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(Vd,"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 Yd(e,t){throw e instanceof h&&Jt(e.extensionMembers?.[g])?e:new h({message:"Outbound fetch failed.",extensionMembers:{[g]:t}},{cause:e})}n(Yd,"normalizeFetchError");function Ut(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&&J(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(Ut,"logOutboundFailure");async function Xd(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";Ut(e,{event:l?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:i,method:c,host:M(a),error:u,extra:{abortReason:s()}}),Yd(u,i)}}n(Xd,"fetchWithNormalizedError");function Qd(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(Qd,"assertRedirectAllowed");function eu(e,t){let r=new Headers(e);for(let o of $d)r.delete(o);for(let o of t)r.delete(o);return r}n(eu,"stripCrossOriginHeaders");function tu(e,t,r,o,i){let a={...e,method:t,redirect:"manual",signal:r};return o&&(a.headers=eu(e.headers,i)),a}n(tu,"buildRedirectInit");function ru(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(ru,"buildInitialRequestInit");function nu(e){let t=Ve(e.currentInput,e.currentInit);Qd({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:tu(e.currentInit,t,e.signal,i,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(nu,"followRedirect");async function en(e,t,r){let o=r.problemCode??"invalid_request",i=r.maxRedirects??Nd,a=r.maxResponseBytes??Jd,s=r.timeoutMs??Gd,c=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],l=r.context,p=new AbortController,_=li(p,t.signal),A=!1,y=setTimeout(()=>{A=!0,p.abort()},s),E=e,T=ru(e,t,p.signal),H;try{H=pi(Qr(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(X){throw Ut(l,{event:"outbound_url_blocked",problemCode:o,method:Ve(e,t),host:M(Qr(e)),error:X}),clearTimeout(y),_?.(),X}let Be=0;try{for(;;){let X=await Xd(l,c,E,T,o,H,()=>A?`timeout_after_${s}ms`:void 0),O=Vd(X,H);if(O!==void 0)try{let z=nu({currentInput:E,currentInit:T,currentUrl:H,redirectUrl:O,redirects:Be,maxRedirects:i,problemCode:o,validateUrl:r.validateUrl,signal:p.signal,additionalCrossOriginStrippedHeaders:u});E=z.currentInput,T=z.currentInit,H=z.currentUrl,Be=z.redirects;continue}catch(z){throw Ut(l,{event:"outbound_redirect_blocked",problemCode:o,method:Ve(E,T),host:M(H),error:z,extra:{redirects:Be,maxRedirects:i,redirectTargetHost:M(O)}}),z}try{return Wd(X,await Kd(X,a,o))}catch(z){throw Ut(l,{event:"outbound_response_size_exceeded",problemCode:o,method:Ve(E,T),host:M(H),error:z,extra:{maxResponseBytes:a,status:X.status}}),z}}}finally{clearTimeout(y),_?.()}}n(en,"runSafeOutboundExchange");async function Pt(e,t,r){let o=await en(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(i){throw Ut(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Ve(e,t),host:M(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(Pt,"runSafeOutboundJsonExchange");function mi(e,t={},r={}){return en(e,t,{...r,validateUrl:mt})}n(mi,"fetchConfiguredOutbound");function fi(e,t={},r={}){return Pt(e,t,{...r,validateUrl:mt})}n(fi,"fetchConfiguredOutboundJson");function lr(e,t={},r={}){return Pt(e,t,{...r,validateUrl:Oo})}n(lr,"fetchIdentityProviderJson");function hi(e,t={},r={}){return Pt(e,t,{...r,validateUrl:Xt})}n(hi,"fetchCimdClientMetadataJson");function gi(e,t={},r={}){return Pt(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 ou}from"jose";var iu=new TextEncoder,au="MCP gateway could not initialize secure key material.",su=32,yi=new Map,_i=new Map,cu;function du(){return cu??Nn.instance.authPrivateKey}n(du,"readAuthPrivateKey");function wi(e){return new Q(au,e===void 0?void 0:{cause:e})}n(wi,"createGeneratedKeyMaterialError");function bi(e,t){let r=ou.decode(t);if(r.byteLength!==su)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(bi,"decodeJwkKeyField");function uu(e){let t=du();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=iu.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(uu,"decodeGeneratedKeyMaterial");function lu(e){let t=yi.get(e);return t||(t=uu(e),yi.set(e,t)),t}n(lu,"getMasterKeyMaterial");async function oe(e){let t=_i.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(lu(e.keyMaterialPurpose));return _i.set(e.purpose,r),r}n(oe,"readCachedDerivedKey");var pu="SHA-256",mu=32,fu="zuplo-mcp-gateway:",hu=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 gu(e,t);return r.set(t,i),i}n(ve,"deriveGatewaySigningKey");async function gu(e,t){let r=G(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=hu.encode(`${fu}${t}`),a=await crypto.subtle.deriveBits({name:"HKDF",hash:pu,salt:new Uint8Array,info:G(i)},o,mu*8);return new Uint8Array(a)}n(gu,"hkdfExpand");var vi=900,yu=900,_u=ho.extend({id:jo}),wu=_u.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),Ai=Tr.extend({id:Ho,purpose:d.literal("browser_connect")}),bu=Tr.extend({purpose:d.literal("browser_connect")}),Ru=Ai.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),xi=vi*1e3;async function ki(){return oe({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>ve(e,"oauth-state"),"derive")})}n(ki,"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 ki())}n(Ui,"signOAuthState");async function pr(e){try{let{payload:t}=await Ci(e,await ki(),{algorithms:[V],issuer:$,audience:W});return wu.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(pr,"verifyOAuthState");async function Pi(e){let t=Math.floor(Date.now()/1e3)+yu,r=bu.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 Ru.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 Iu(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(Iu,"buildConnectRequiredMessage");async function Cu(e){let t=q(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(Cu,"buildGatewayBrowserTicketUrl");function Su(e){return B().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(Su,"buildGatewayConnectPath");async function tn(e){return Cu({...e,path:Su(e.upstreamServerId),redirect:!0})}n(tn,"buildGatewayConnectUrl");async function mr(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:Iu(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(mr,"buildRedirectConnectRequiredResponse");function Mi(e){return vu({...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(Mi,"buildAdminConnectRequiredResponse");function vu(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(vu,"buildAdminSetupRequiredResponse");var qi=12;async function Di(e){let t=await crypto.subtle.digest("SHA-256",G(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,qi)}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,qi)}n(Xe,"fingerprintConnectionIdentity");function Et(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(Et,"describeAccessTokenState");Z();var zi=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function Au(e,t){return e&&e.length>0?e.join(t):void 0}n(Au,"joinOAuthScopes");function xu(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of zi)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(xu,"sanitizeAuthorizationServerMetadata");function ji(e){let t=xu(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(ji,"sanitizeOAuthDiscoveryState");function Hi(e){let t=new URL(e);for(let r of zi){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 fr(e){let t=new URL(e);return K(t)&&Qn(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(fr,"normalizeLoopbackOAuthRedirectUri");function Bi(e){return Au(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(Bi,"readProtectedResourceMetadataScope");function ku(e){return`Zuplo MCP Gateway - ${e}`}n(ku,"buildGatewayOAuthClientName");function Tu(e,t){return e&&e.length>0?e.join(t):void 0}n(Tu,"joinOAuthScopeList");function Uu(e){if(e.clientRegistration.mode!=="auto")return Tu(e.scopes,e.scopeDelimiter)}n(Uu,"readPublicClientMetadataScope");function rn(e){return new URL(B().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:ku(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=Uu(o);return{client_id:rn({origin:e,upstreamServerId:t}),...nn({origin:e,upstreamServerId:t,redirectUri:fr(new URL(o.redirectPath,e)).toString(),scope:i})}}n(Li,"buildOAuthClientMetadataDocument");Z();import{base64url as Ae}from"jose";var Pu="SHA-256",Qe="AES-GCM",Eu=12,an="zuplo-secret",sn=1,Ni="generated:auth_private_key:token-encryption",Ou=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(Pu,G(e));return crypto.subtle.importKey("raw",t,{name:Qe},!1,["encrypt","decrypt"])},"derive")})}n(on,"getEncryptionKey");function Ji(e){return G(new TextEncoder().encode(`${an}:v${e.version}:${e.keyId}`))}n(Ji,"getAssociatedData");function Mu(e){return`${an}:v${e.version}:${Ae.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(Mu,"encodeEnvelope");function qu(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 Ou.parse(JSON.parse(o))}n(qu,"decodeEnvelope");async function me(e){let t=await on(),r=crypto.getRandomValues(new Uint8Array(Eu)),o={version:sn,keyId:Ni},i=await crypto.subtle.encrypt({name:Qe,iv:r,additionalData:Ji(o)},t,new TextEncoder().encode(e));return Mu({...o,algorithm:Qe,iv:Ae.encode(r),ciphertext:Ae.encode(new Uint8Array(i))})}n(me,"encryptSecret");async function xe(e){let t=qu(e);if(t){let s=await on(),c=await crypto.subtle.decrypt({name:Qe,iv:G(Ae.decode(t.iv)),additionalData:Ji(t)},s,G(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:G(Ae.decode(r))},i,G(Ae.decode(o)));return new TextDecoder().decode(a)}n(xe,"decryptSecret");var Du=d.union([yt,ar]),zu=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:or.optional(),authorizationServerMetadata:d.union([gt,ir]).optional()}).passthrough(),ju="Bearer",Hu="__zuplo_refresh_only_upstream_access_token__";function Gi(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Gi,"splitScopes");function Bu(e){return Ne.parse(e)}n(Bu,"parsePkceCodeVerifier");function Lu(e){if(typeof e.expires_in=="number")return I(new Date(Date.now()+e.expires_in*1e3))}n(Lu,"readTokenExpiry");async function Nu(e){if(e!==void 0)return me(JSON.stringify(e))}n(Nu,"encryptJson");async function Ju(e,t){if(!e)return;let r=await xe(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(Ju,"decryptJson");function Gu(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(Gu,"clientInformationAllowsRedirectUri");function Fu(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(Fu,"clientInformationMatchesCurrentClientMetadataUrl");function $u(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n($u,"isUrlBasedClientInformation");function Zu(e,t){return t===void 0?e:{...e,scope:t}}n(Zu,"applyOAuthClientMetadataScope");function Ku(e,t){return Bi({state:e,delimiter:t})}n(Ku,"readResourceMetadataScope");function Wu(e,t){return e&&e.length>0?e.join(t):void 0}n(Wu,"joinOAuthScopeList");function Vu(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new x(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return yt.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(Vu,"buildManualOAuthClientInformation");function Yu(e,t){let r=rn({origin:new URL(t).origin,upstreamServerId:e});return Kr(r)?r:void 0}n(Yu,"buildClientMetadataUrl");function Xu(e){for(let t of e)if(t!==void 0)return t}n(Xu,"firstDefined");function Qu(e){let t=We(e.target.upstreamServerId,e.target.authProfileId),r=Wu(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:Vu({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let i=Yu(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(Qu,"buildInitialOAuthClientSetup");function el(e,t){if(t===void 0)return Xu([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(el,"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=Qu({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.clientMetadataValue=r.clientMetadata,this.configuredScope=r.configuredScope,this.scopeDelimiter=r.scopeDelimiter,this.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=el(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 Zu(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,L()?.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"),!$u({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Nu(t),await this.syncPendingState(!1)))}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=ji(zu.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,L()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:M(r.authorizationServerUrl),resourceMetadataHost:M(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=Ku(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&&L()?.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 xe(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let c={id:this.connection?.id??Qt(),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:Lu(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await R().upsertUpstreamConnection(c),L()?.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:Bu(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()+xi)),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 Ju(this.encryptedClientInformation,Du)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&(!Gu(t,this.redirectUriValue)||!Fu({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=ar.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"){L()?.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 xe(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await xe(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=L();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??Hu,token_type:ju,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=L();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 tl=3e4,rl=256*1024,nl=2,ol="does not support dynamic client registration",il=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],al=["HTTP 403 Forbidden","Access Denied","permission to access"],sl=new Set(["access_denied","invalid_client","invalid_grant","invalid_request","invalid_scope","invalid_target","unauthorized_client","unsupported_grant_type"]);function cl(e){return e instanceof Error&&e.message.includes(ol)}n(cl,"isDynamicClientRegistrationUnsupported");function dl(e){return e instanceof Error&&il.some(t=>e.message.includes(t))}n(dl,"isProtectedResourceMetadataUnavailable");function ul(e){return e instanceof Error&&al.some(t=>e.message.includes(t))}n(ul,"isUpstreamProviderAccessDenied");function ll(e){return e instanceof k&&sl.has(e.errorCode)}n(ll,"isStoredConnectionReconsentError");function pl(e){if(e.error instanceof h&&e.error.extensionMembers?.[g]!==void 0)return e.error;if(cl(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(dl(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(ul(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(pl,"mapUpstreamOAuthSetupError");function ml(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(ml,"readOAuthFetchRequest");function fl(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(fl,"responseLooksJson");function hl(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(hl,"responseLooksHtml");function gl(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(gl,"throwUpstreamHtmlError");function yl(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(yl,"readUpstreamOAuthErrorBody");function _l(e){let{error:t,errorDescription:r}=yl(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.request.method??"GET",host:M(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(_l,"logUpstreamOAuthHttpError");function $i(e){return async(t,r)=>{let o=ml(t),i=L(),a=Date.now(),s=await mi(t,r,{maxRedirects:nl,maxResponseBytes:rl,problemCode:"upstream_token_exchange_failed",timeoutMs:tl}),c=await s.clone().text();if(i?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:o.method??"GET",host:M(o.url),path:o.url.pathname,status:s.status,durationMs:Date.now()-a,responseChars:c.length},"Upstream OAuth HTTP request completed"),s.ok||_l({log:i,upstreamServerId:e,request:o,response:s,body:c}),!s.ok&&hl(s,c)&&gl({upstreamServerId:e,request:o,response:s,body:c}),!fl(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){L()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:M(e.serverUrl),resourceMetadataHost:M(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=M(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),J(t,"error",e.error),L()?.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=pl({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(Vi,"runUpstreamOAuth");async function wl(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(wl,"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=Et(e.connection),r=!!e.forceRefresh,o=!r&&t==="usable",i=L(),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||!ll(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 bl(e){let t=await pr(e.stateToken),r=await R().consumeUpstreamOAuthState({id:t.id,now:I(new Date)}),o=Rl(r);return Il({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),Cl(o),o}n(bl,"consumeStoredCallbackState");function Rl(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(Rl,"readConsumedCallbackState");function Il(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(Il,"assertStoredCallbackStateMatches");function Cl(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new h({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}})}n(Cl,"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),Mi(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),mr(t)}n(Fi,"buildOAuthConnectRequiredResponse");async function Qi(e){let t=await bl({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Kt(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 wl(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 Sl,SignJWT as vl}from"jose";var ta=1e4,ra=64*1024,na=2,Al=300,ne=d.string().min(1),xl=d.object({access_token:ne,issued_token_type:d.literal(Pr),token_type:d.string().optional(),expires_in:d.number().int().positive().optional(),scope:ne.optional()}).passthrough(),kl=d.object({id_token:ne,token_type:ne.optional(),expires_in:d.number().int().positive().optional(),refresh_token:ne.optional(),scope:ne.optional()}).passthrough(),Tl=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 Ul(e){return e.replaceAll("\\n",`
|
|
26
26
|
`)}n(Ul,"normalizePem");async function Pl(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??Al,o=await Sl(Ul(e.clientAuth.privateKeyPem),t),i={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new vl({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(Pl,"createPrivateKeyJwtClientAssertion");async function El(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",Vt),e.form.set("client_assertion",await Pl({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}n(El,"appendClientAuthentication");async function cn(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await El({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)=>lr(t,r,{context:e,maxRedirects:na,maxResponseBytes:ra,problemCode:"upstream_token_exchange_failed",timeoutMs:ta})}n(oa,"defaultIdpFetchJson");function Ol(e){return(t,r)=>fi(t,r,{context:e,maxRedirects:na,maxResponseBytes:ra,problemCode:"upstream_token_exchange_failed",timeoutMs:ta})}n(Ol,"defaultResourceAsFetchJson");function hr(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(hr,"runtimeError");function dn(e){if(!e.response.ok)throw hr({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 Ml(e){let t=kl.safeParse(e.json);if(!t.success)throw hr({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(Ml,"parseIdpRefreshTokenResponse");function ql(e){let t=xl.safeParse(e.json);if(!t.success)throw hr({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(ql,"parseIdJagTokenExchangeResponse");function Dl(e){let t=Tl.safeParse(e.json);if(!t.success)throw hr({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(Dl,"parseAccessTokenResponse");async function ia(e){let t=new URLSearchParams({grant_type:Wt,requested_token_type:Pr,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"}),ql({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"}),Ml({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??Ol(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"}),Dl({json:i,response:o,tokenUrl:e.resourceAs.tokenUrl})}n(sa,"exchangeIdJagForAccessToken");function zl(e){return Et(e)==="usable"}n(zl,"hasUsableAccessToken");function jl(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(jl,"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 Hl(e){let t=await xe(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 L()?.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(Hl,"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=Et(t),o=!!e.forceRefresh,i=!o&&r==="usable",a=L(),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&&zl(t))return{kind:"authorized",credential:{type:"bearer_token",token:await xe(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),p=ui(e.upstreamServerId,e.authProfileId),_=p.resourceAs.resource??l.transport.baseUrl,A=e.requestedScope??(p.scopes.length===0?void 0:p.scopes.join(p.scopeDelimiter)),y=await Hl({connection:t,connectionFingerprint:s,encryptedSubjectToken:c,subjectTokenType:u,idp:{tokenUrl:p.idp.tokenUrl},clientAuth:p.idp.clientAuth,context:e.context}),E=await ia({idp:{tokenUrl:p.idp.tokenUrl},subjectToken:y.subjectToken,subjectTokenType:y.subjectTokenType,audience:p.resourceAs.audience,resource:_,scope:A,clientAuth:p.idp.clientAuth,context:e.context}),T=E.scope??A,H=await sa({resourceAs:{tokenUrl:p.resourceAs.tokenUrl},assertion:E.assertion,resource:_,scope:T,clientAuth:p.resourceAs.clientAuth,context:e.context});if(jl(H),t!==void 0){let X=(H.scope??T)?.split(/[,\s]+/).filter(Boolean)??[],O=H.expiresIn===void 0?void 0:I(new Date(Date.now()+H.expiresIn*1e3)),z=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(H.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:z.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:H.accessToken}}}n(da,"authorizeUpstreamIdJagRequest");function Bl(e){return fr(new URL(e.callbackPath,q(e.requestUrl,e.requestHeaders))).toString()}n(Bl,"buildGatewayOAuthRedirectUri");async function ua(e){let t=Se(e.upstreamServerId),r=We(e.upstreamServerId,e.authProfileId),o=Bl({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:q(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 pr(e.callbackRequest.state)).authProfileId;if(dr({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 Ll(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(Ll,"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 gr(e,t){let o=ee().byOperationId.get(t);if(!o)throw new x(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new x(`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 x(`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 Ll({connection:o.connection,operationId:t})}n(gr,"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 Nl=dt.InvalidRequest,Jl=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function Gl(e,t){return{credentialType:e.type,forceRefresh:t}}n(Gl,"buildCredentialResolvedAttributes");function Fl(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(Fl,"connectRequiredReasonCode");function ga(e){v(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:Gl(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:Fl(e.payload.state),reasonClass:"auth",attributes:t})}n(ya,"emitCredentialMissingAnalyticsEvents");function $l(e){let t=e.route.raw();return Ft.parse(t?.operationId)}n($l,"readOperationId");async function Zl(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(Zl,"buildCredentialHeaders");var Kl=new Set(["authorization","cookie","cookie2"]);function Wl(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(Wl,"readJsonRequestMethod");function Vl(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(Vl,"isJsonResponse");function ln(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(ln,"isRecord");function Yl(e){return Array.isArray(e)&&e.length>0}n(Yl,"hasIconList");function Xl(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=cr(ao(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(Xl,"readFallbackServerIcons");function Ql(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)||Yl(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n(Ql,"addMissingServerIcons");function ep(e,t){let r=new Headers(e.headers);for(let o of Kl)r.delete(o);for(let[o,i]of t)r.set(o,i);return new Gn(e,{headers:r})}n(ep,"applyUpstreamHeaders");function tp(e){let t=new Headers(e.headers);for(let r of Jl)t.delete(r);return t}n(tp,"buildProxyHeaders");async function rp(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(rp,"readRetryBody");function _a(e,t){let r=t.authUrl===void 0?void 0:Fo({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(tr({id:Go(e),error:{code:r?.code??Nl,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(_a,"connectRequiredJsonRpcResponse");async function np(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(np,"applyRefreshedCredentialHeaders");function op(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await np({request:e.request,context:e.context,headers:tp(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 Bt.fetch(i.url,i.init)})}n(op,"installUpstreamAuthRetryHook");function ip(e){if(Wl(e.requestBody)!=="initialize")return;let t=Xl({connection:e.connection,context:e.context});t===void 0||t.length===0||e.context.addResponseSendingHook(async r=>{if(!Vl(r))return r;let o;try{o=await r.clone().json()}catch{return r}let i=Ql({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(ip,"installInitializeIconHook");async function pn(e,t,r){let o=$l(t),i=await rp(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 Zl(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=ep(e,u.headers);return op({request:l,context:t,requestBody:i,routeAuth:c}),ip({context:t,requestBody:i,connection:r}),l}n(pn,"mcpTokenExchangePolicy");var mn=class extends Lt{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 ap(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}n(ap,"escapeHtml");function sp(e){return e===null||typeof e!="object"?!1:e[wa]===!0}n(sp,"isHtml");function ba(e){return e==null||e===!1?"":Array.isArray(e)?e.map(ba).join(""):sp(e)?e.value:ap(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 cp="text/html; charset=utf-8";function it(e){try{return new URL(e).host}catch{return""}}n(it,"safeHostFromUrl");function ie(e){let t=up(e.kind??"authorization_failed"),r=dp(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:hp({diagnostic:r,upstreamHtml:e.upstreamHtml}),action:mp(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":cp,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(ie,"browserErrorPageResponse");function dp(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??lp(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??pp(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}n(dp,"buildBrowserErrorDiagnostic");function up(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(up,"readBrowserErrorPagePresentation");function lp(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(lp,"readBrowserErrorStage");function pp(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(pp,"readBrowserErrorSuggestedFix");function mp(e){return e===void 0?te:S`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(mp,"renderAction");function fp(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(`
|