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