@zuplo/runtime 6.70.36 → 6.70.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,12 +22,8 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$ as j,A as sn,B as qe,J as si,K as ci,L as c,M as ui,N as C,O as U,P as di,Q as pi,R as B,S as l,T as m,U as $,V as O,W as cn,X as un,Y as T,Z as se,_ as f,a as ot,aa as li,b as ii,ba as dn,ca as mi,da as hi,ea as i,fa as z,ga as fi,j as he,k as ai,m as lr,ma as gi,q as on,s as it,x as an}from"../chunk-YTQ3TTI6.js";import{d as at}from"../chunk-TOF2KNST.js";import{a as v}from"../chunk-A2CSR4RF.js";import{$ as re,a as n,aa as w,ba as _,ca as nt,da as oi}from"../chunk-2VLXJLVI.js";z();z();var Id=new Set(["localhost","::1"]);function ve(e){return e.replace(/^\[(.*)\]$/,"$1").replace(/\.+$/,"").toLowerCase()}n(ve,"normalizeHostname");function Z(e){let t=ve(e.hostname);return e.protocol==="http:"&&(Id.has(t)||/^127(?:\.\d{1,3}){3}$/.test(t))}n(Z,"isLoopbackHttpUrl");var yi=new qe("gateway-route");function wi(e,t){yi.set(e,t)}n(wi,"setGatewayRouteContext");function mr(e){return yi.get(e)}n(mr,"readGatewayRouteContext");var Si=new qe("mcp-oauth-runtime-config");function st(e,t){Si.set(e,t)}n(st,"setMcpOAuthRuntimeConfig");function Ri(e){let t=Si.get(e);if(!t)throw new _("MCP gateway OAuth config has not been set on the request context. An `mcp-oauth-inbound` policy (or `mcp-auth0-oauth-inbound`) must run before this handler, or the internal OAuth route wrapper must have populated the context.");return t}n(Ri,"requireMcpOAuthRuntimeConfig");var zt=i.string().trim().min(1),Ud=60,Td=24*60*60,Pd=15*Ud,Od=10*365*Td,Et={accessTokenTtlSeconds:Pd,refreshTokenTtlSeconds:Od,cimdEnabled:!0},zd=i.object({issuer:i.url(),jwksUrl:i.url(),audience:zt.optional()}),Ed=i.object({url:i.url(),tokenUrl:i.url().optional(),clientId:zt.optional(),clientSecret:zt.optional(),scope:zt.default("openid profile email"),audience:zt.optional(),remoteTimeoutMs:i.coerce.number().int().positive().default(1e4),stateTtlSeconds:i.coerce.number().int().positive().default(900),sessionTtlSeconds:i.coerce.number().int().positive().default(28800)}).strict().superRefine((e,t)=>{if(!bi(e.url))for(let r of["tokenUrl","clientId","clientSecret"])e[r]||t.addIssue({code:i.ZodIssueCode.custom,message:`${r} is required for federated browser login`,path:[r]})}),Md=i.object({accessTokenTtlSeconds:i.coerce.number().int().positive().default(Et.accessTokenTtlSeconds),refreshTokenTtlSeconds:i.coerce.number().int().positive().default(Et.refreshTokenTtlSeconds),cimdEnabled:i.boolean().default(Et.cimdEnabled)}).strict().default(Et),pn=i.object({oidc:zd,browserLogin:Ed,gateway:Md.optional().default(Et)}).strict();function _i(e){return bi(e.browserLogin.url)?"local_dev":"federated_oidc"}n(_i,"readBrowserLoginKind");function bi(e){let t;try{t=new URL(e)}catch{return!1}return Z(t)&&t.pathname==="/oauth/dev-login"}n(bi,"isLoopbackDevLoginUrl");function Ci(e){return pn.parse(e)}n(Ci,"parseMcpOAuthRuntimeConfig");function K(){let e;try{e=an()}catch(t){throw new re("MCP gateway OAuth config can only be read during a request. Wrap tests in `runWithRequestContext` and ensure MCP OAuth routes are registered through `McpGatewayPlugin`.",{cause:t})}return Ri(e)}n(K,"getGatewayOAuthConfig");function hr(e,t,r){let o=e.safeParse(t);if(o.success)return o.data;throw new _(`${r} is misconfigured. Validation failed:
26
- ${qd(o.error)}`,{cause:o.error})}n(hr,"parseConfigOrThrow");function qd(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
27
- `)}n(qd,"formatZodIssues");var ln=class extends it{static{n(this,"McpOAuthInboundPolicy")}constructor(t,r){let o=mn(t,r);super(o,r)}async handler(t,r){return ot("policy.inbound.mcp-oauth"),st(r,this.options),Mt(t,r)}};function mn(e,t="mcp-oauth-inbound"){return hr(pn,e,`MCP OAuth policy "${t}"`)}n(mn,"mcpOAuthOptionsToRuntimeConfig");var hn=["mcp-oauth-inbound","mcp-auth0-oauth-inbound"],xi={"mcp-oauth-inbound":"McpOAuthInboundPolicy","mcp-auth0-oauth-inbound":"McpAuth0OAuthInboundPolicy"};function Hd(e,t,r){switch(e){case"mcp-oauth-inbound":return mn(r,t);case"mcp-auth0-oauth-inbound":return Ii(r,t);default:return}}n(Hd,"parseMcpOAuthPolicyConfig");function Ai(e){return e!==void 0&&hn.some(t=>t===e)}n(Ai,"isMcpOAuthInboundPolicyType");function fn(e){switch(e.policyType){case"mcp-oauth-inbound":return e.handler.export===xi["mcp-oauth-inbound"];case"mcp-auth0-oauth-inbound":return e.handler.export===xi["mcp-auth0-oauth-inbound"];default:return!1}}n(fn,"isMcpOAuthRuntimeConfigPolicy");function vi(e){if(!e)return;let t=e.filter(fn);if(t.length>1){let a=t.map(s=>`"${s.name}" (${s.policyType})`).join(", ");throw new _(`MCP gateway found multiple OAuth policies in policies.json: ${a}. Use exactly one MCP OAuth policy for the gateway so internal OAuth routes resolve a single runtime config.`)}let r=t[0];if(!r)return;let o=Hd(r.policyType,r.name,r.handler.options);if(!o)throw new _(`MCP gateway: policy '${r.name}' has unsupported MCP OAuth policy type '${r.policyType}'.`);return{policyName:r.name,config:o}}n(vi,"resolveMcpOAuthRuntimeConfigFromPolicies");var y="gatewayCode",ct={runtime:{invalid_request:{code:"invalid_request",status:400,title:"Bad Request",publicDetail:"The request did not match the route contract.",oauthError:"invalid_request"},forbidden:{code:"forbidden",status:403,title:"Forbidden",publicDetail:"The request is not allowed.",oauthError:"invalid_request"},not_found:{code:"not_found",status:404,title:"Not Found",publicDetail:"The requested resource was not found.",oauthError:"invalid_request"},too_many_requests:{code:"too_many_requests",status:429,title:"Too Many Requests",publicDetail:"The request exceeded the allowed rate.",oauthError:"invalid_request"},internal_server_error:{code:"internal_server_error",status:500,title:"Internal Server Error",publicDetail:"The gateway failed to process the request.",oauthError:"server_error"}},config:{mcp_route_not_enabled:{code:"mcp_route_not_enabled",status:404,title:"Not Found",publicDetail:"The requested MCP route is not enabled."},unknown_upstream_server:{code:"unknown_upstream_server",status:400,title:"Bad Request",publicDetail:"The requested upstream server is not configured.",oauthError:"invalid_request"},unknown_mcp_route:{code:"unknown_mcp_route",status:400,title:"Bad Request",publicDetail:"The requested MCP route is not configured.",oauthError:"invalid_target"},unknown_auth_profile:{code:"unknown_auth_profile",status:400,title:"Bad Request",publicDetail:"The requested upstream auth profile is not configured.",oauthError:"invalid_request"},mcp_route_upstream_mismatch:{code:"mcp_route_upstream_mismatch",status:400,title:"Bad Request",publicDetail:"The requested MCP route does not belong to the selected upstream server.",oauthError:"invalid_request"}},downstream_auth:{authentication_required:{code:"authentication_required",status:401,title:"Unauthorized",publicDetail:"Authentication is required to access this route.",oauthError:"invalid_client"},identity_context_missing:{code:"identity_context_missing",status:403,title:"Forbidden",publicDetail:"Authenticated requests must include a gateway principal subject.",oauthError:"invalid_request"}},downstream_oauth:{browser_login_verification_failed:{code:"browser_login_verification_failed",status:400,title:"Connection failed",publicDetail:"The gateway could not verify the browser login response. Retry the login flow.",callbackFailure:!0,oauthError:"invalid_request"}},upstream_auth:{provider_access_denied:{code:"provider_access_denied",status:400,title:"Connection failed",publicDetail:"The upstream authorization request was denied. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_invalid:{code:"oauth_state_invalid",status:400,title:"Connection failed",publicDetail:"The upstream connection request could not be verified. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_expired:{code:"oauth_state_expired",status:400,title:"Connection failed",publicDetail:"The upstream connection request expired. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_reused:{code:"oauth_state_reused",status:400,title:"Connection failed",publicDetail:"This upstream connection request was already used. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_callback_mismatch:{code:"oauth_callback_mismatch",status:400,title:"Connection failed",publicDetail:"The upstream callback did not match the initiating connection request.",callbackFailure:!0,oauthError:"invalid_request"},upstream_token_exchange_failed:{code:"upstream_token_exchange_failed",status:400,title:"Connection failed",publicDetail:"The gateway could not complete the upstream token exchange. Retry the connection flow.",callbackFailure:!0,oauthError:"invalid_request"},upstream_client_registration_required:{code:"upstream_client_registration_required",status:400,title:"Upstream OAuth client registration required",publicDetail:"The upstream authorization server supports neither gateway-hosted Client ID Metadata Documents nor Dynamic Client Registration. Register an upstream OAuth client manually before retrying.",oauthError:"invalid_request"},upstream_token_response_invalid:{code:"upstream_token_response_invalid",status:400,title:"Connection failed",publicDetail:"The upstream token response was invalid. Retry the connection flow.",callbackFailure:!0,oauthError:"invalid_request"}},upstream_mcp:{upstream_capability_invocation_failed:{code:"upstream_capability_invocation_failed",status:502,title:"Bad Gateway",publicDetail:"The upstream capability invocation failed. Retry later or reconnect the upstream if the issue persists."},upstream_capability_unavailable:{code:"upstream_capability_unavailable",status:503,title:"Service Unavailable",publicDetail:"The upstream capability is unavailable. Retry later or reconnect the upstream if the issue persists."},upstream_import_failed:{code:"upstream_import_failed",status:502,title:"Bad Gateway",publicDetail:"The upstream capability import failed. Retry later or reconnect the upstream if the issue persists."}}},fr={...ct.runtime,...ct.config,...ct.downstream_auth,...ct.downstream_oauth,...ct.upstream_auth,...ct.upstream_mcp};function Ie(e){return typeof e=="string"&&Object.hasOwn(fr,e)}n(Ie,"isGatewayProblemCode");function ki(e){return Ie(e)&&W(e).callbackFailure===!0}n(ki,"isGatewayCallbackFailureCode");function W(e){return fr[e]}n(W,"readGatewayProblemDefinition");function Ui(e){switch(e){case 400:return"invalid_request";case 401:return"authentication_required";case 403:return"forbidden";case 404:return"not_found";case 429:return"too_many_requests";default:return"internal_server_error"}}n(Ui,"readDefaultGatewayProblemCodeForStatus");var Dd=/^\$\{env\.([A-Za-z_][A-Za-z0-9_]*)\}$/;function Ti(e,t){let r;try{r=new URL(e)}catch{throw new _(`${t} must be an absolute URL.`)}if(r.protocol!=="https:"&&r.protocol!=="http:")throw new _(`${t} must be an HTTP(S) URL.`);return e}n(Ti,"assertHttpUrl");function Pi(e){return e.options??{}}n(Pi,"readHandlerOptions");function jd(e){let t=Dd.exec(e);if(t){let r=t[1],o=at[r];if(typeof o!="string"||o==="")throw new _(`MCP route handler rewritePattern references env.${r}, but that environment variable is not set.`);return Ti(o,`env.${r}`)}if(e.includes("${"))throw new _("MCP token exchange requires a static route handler rewritePattern. Dynamic request-based rewrite patterns are not supported for MCP upstream OAuth.");return Ti(e,"MCP route handler rewritePattern")}n(jd,"readRewritePatternUrl");function gn(e){let t=Pi(e);if(typeof t.rewritePattern=="string"&&t.rewritePattern!=="")return jd(t.rewritePattern);throw new _("MCP route must configure handler.options.rewritePattern.")}n(gn,"readMcpRouteUpstreamUrl");function Oi(e){let t=Pi(e.handler),r=new URL(gn(e.handler));if(t.forwardSearch!==!1)for(let[a,s]of new URL(e.request.url).searchParams)r.searchParams.append(a,s);let o={method:e.request.method,body:e.body,headers:e.headers,redirect:t.followRedirects===!0?"follow":"manual",zuplo:typeof t.mtlsCertificate=="string"&&t.mtlsCertificate.length>0?{mtlsCertificate:t.mtlsCertificate}:void 0};return{url:r.toString(),init:o}}n(Oi,"buildMcpRouteUpstreamFetch");z();var Ld=["shared-oauth","user-oauth"],Bd=["none","client_secret_basic","client_secret_post"],oe=i.string().min(1).brand(),G=i.string().min(1),ce=i.string().min(1).brand(),MR=i.string().min(1).brand(),yn=i.enum(Ld),wn=i.enum(Bd);z();var Rn="2025-11-25";var Gd="io.modelcontextprotocol/related-task",dt="2.0",F=li(e=>e!==null&&(typeof e=="object"||typeof e=="function")),zi=O([c(),C().int()]),Ei=c(),HR=$({ttl:C().optional(),pollInterval:C().optional()}),$d=m({ttl:C().optional()}),Zd=m({taskId:c()}),_n=$({progressToken:zi.optional(),[Gd]:Zd.optional()}),ue=m({_meta:_n.optional()}),yr=ue.extend({task:$d.optional()});var X=m({method:c(),params:ue.loose().optional()}),fe=m({_meta:_n.optional()}),ge=m({method:c(),params:fe.loose().optional()}),Q=$({_meta:_n.optional()}),wr=O([c(),C().int()]),bn=m({jsonrpc:f(dt),id:wr,...X.shape}).strict();var Fd=m({jsonrpc:f(dt),...ge.shape}).strict();var Mi=m({jsonrpc:f(dt),id:wr,result:Q}).strict();var ke;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ke||(ke={}));var Sr=m({jsonrpc:f(dt),id:wr.optional(),error:m({code:C().int(),message:c(),data:B().optional()})}).strict();var DR=O([bn,Fd,Mi,Sr]),jR=O([Mi,Sr]),qi=Q.strict(),Kd=fe.extend({requestId:wr.optional(),reason:c().optional()}),Hi=ge.extend({method:f("notifications/cancelled"),params:Kd}),Wd=m({src:c(),mimeType:c().optional(),sizes:l(c()).optional(),theme:se(["light","dark"]).optional()}),Ht=m({icons:l(Wd).optional()}),ut=m({name:c(),title:c().optional()}),pt=ut.extend({...ut.shape,...Ht.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),Jd=un(m({applyDefaults:U().optional()}),T(c(),B())),Vd=dn(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,un(m({form:Jd.optional(),url:F.optional()}),T(c(),B()).optional())),Yd=$({list:F.optional(),cancel:F.optional(),requests:$({sampling:$({createMessage:F.optional()}).optional(),elicitation:$({create:F.optional()}).optional()}).optional()}),Xd=$({list:F.optional(),cancel:F.optional(),requests:$({tools:$({call:F.optional()}).optional()}).optional()}),Qd=m({experimental:T(c(),F).optional(),sampling:m({context:F.optional(),tools:F.optional()}).optional(),elicitation:Vd.optional(),roots:m({listChanged:U().optional()}).optional(),tasks:Yd.optional(),extensions:T(c(),F).optional()}),ep=ue.extend({protocolVersion:c(),capabilities:Qd,clientInfo:pt}),tp=X.extend({method:f("initialize"),params:ep});var rp=m({experimental:T(c(),F).optional(),logging:F.optional(),completions:F.optional(),prompts:m({listChanged:U().optional()}).optional(),resources:m({subscribe:U().optional(),listChanged:U().optional()}).optional(),tools:m({listChanged:U().optional()}).optional(),tasks:Xd.optional(),extensions:T(c(),F).optional()}),np=Q.extend({protocolVersion:c(),capabilities:rp,serverInfo:pt,instructions:c().optional()}),op=ge.extend({method:f("notifications/initialized"),params:fe.optional()});var Di=X.extend({method:f("ping"),params:ue.optional()}),ip=m({progress:C(),total:j(C()),message:j(c())}),ap=m({...fe.shape,...ip.shape,progressToken:zi}),ji=ge.extend({method:f("notifications/progress"),params:ap}),sp=ue.extend({cursor:Ei.optional()}),Dt=X.extend({params:sp.optional()}),jt=Q.extend({nextCursor:Ei.optional()}),cp=se(["working","input_required","completed","failed","cancelled"]),Lt=m({taskId:c(),status:cp,ttl:O([C(),di()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:j(C()),statusMessage:j(c())}),Li=Q.extend({task:Lt}),up=fe.merge(Lt),Bi=ge.extend({method:f("notifications/tasks/status"),params:up}),Ni=X.extend({method:f("tasks/get"),params:ue.extend({taskId:c()})}),Gi=Q.merge(Lt),$i=X.extend({method:f("tasks/result"),params:ue.extend({taskId:c()})}),LR=Q.loose(),Zi=Dt.extend({method:f("tasks/list")}),Fi=jt.extend({tasks:l(Lt)}),Ki=X.extend({method:f("tasks/cancel"),params:ue.extend({taskId:c()})}),BR=Q.merge(Lt),Wi=m({uri:c(),mimeType:j(c()),_meta:T(c(),B()).optional()}),Ji=Wi.extend({text:c()}),Cn=c().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Vi=Wi.extend({blob:Cn}),Bt=se(["user","assistant"]),lt=m({audience:l(Bt).optional(),priority:C().min(0).max(1).optional(),lastModified:ci.datetime({offset:!0}).optional()}),Yi=m({...ut.shape,...Ht.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(C()),annotations:lt.optional(),_meta:j($({}))}),dp=m({...ut.shape,...Ht.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:lt.optional(),_meta:j($({}))}),pp=Dt.extend({method:f("resources/list")}),lp=jt.extend({resources:l(Yi)}),mp=Dt.extend({method:f("resources/templates/list")}),hp=jt.extend({resourceTemplates:l(dp)}),xn=ue.extend({uri:c()}),fp=xn,gp=X.extend({method:f("resources/read"),params:fp}),yp=Q.extend({contents:l(O([Ji,Vi]))}),wp=ge.extend({method:f("notifications/resources/list_changed"),params:fe.optional()}),Sp=xn,Rp=X.extend({method:f("resources/subscribe"),params:Sp}),_p=xn,bp=X.extend({method:f("resources/unsubscribe"),params:_p}),Cp=fe.extend({uri:c()}),xp=ge.extend({method:f("notifications/resources/updated"),params:Cp}),Ap=m({name:c(),description:j(c()),required:j(U())}),vp=m({...ut.shape,...Ht.shape,description:j(c()),arguments:j(l(Ap)),_meta:j($({}))}),Ip=Dt.extend({method:f("prompts/list")}),kp=jt.extend({prompts:l(vp)}),Up=ue.extend({name:c(),arguments:T(c(),c()).optional()}),Tp=X.extend({method:f("prompts/get"),params:Up}),An=m({type:f("text"),text:c(),annotations:lt.optional(),_meta:T(c(),B()).optional()}),vn=m({type:f("image"),data:Cn,mimeType:c(),annotations:lt.optional(),_meta:T(c(),B()).optional()}),In=m({type:f("audio"),data:Cn,mimeType:c(),annotations:lt.optional(),_meta:T(c(),B()).optional()}),Pp=m({type:f("tool_use"),name:c(),id:c(),input:T(c(),B()),_meta:T(c(),B()).optional()}),Op=m({type:f("resource"),resource:O([Ji,Vi]),annotations:lt.optional(),_meta:T(c(),B()).optional()}),zp=Yi.extend({type:f("resource_link")}),kn=O([An,vn,In,zp,Op]),Ep=m({role:Bt,content:kn}),Mp=Q.extend({description:c().optional(),messages:l(Ep)}),qp=ge.extend({method:f("notifications/prompts/list_changed"),params:fe.optional()}),Hp=m({title:c().optional(),readOnlyHint:U().optional(),destructiveHint:U().optional(),idempotentHint:U().optional(),openWorldHint:U().optional()}),Dp=m({taskSupport:se(["required","optional","forbidden"]).optional()}),Xi=m({...ut.shape,...Ht.shape,description:c().optional(),inputSchema:m({type:f("object"),properties:T(c(),F).optional(),required:l(c()).optional()}).catchall(B()),outputSchema:m({type:f("object"),properties:T(c(),F).optional(),required:l(c()).optional()}).catchall(B()).optional(),annotations:Hp.optional(),execution:Dp.optional(),_meta:T(c(),B()).optional()}),jp=Dt.extend({method:f("tools/list")}),Lp=jt.extend({tools:l(Xi)}),Qi=Q.extend({content:l(kn).default([]),structuredContent:T(c(),B()).optional(),isError:U().optional()}),NR=Qi.or(Q.extend({toolResult:B()})),Bp=yr.extend({name:c(),arguments:T(c(),B()).optional()}),Np=X.extend({method:f("tools/call"),params:Bp}),Gp=ge.extend({method:f("notifications/tools/list_changed"),params:fe.optional()}),GR=m({autoRefresh:U().default(!0),debounceMs:C().int().nonnegative().default(300)}),ea=se(["debug","info","notice","warning","error","critical","alert","emergency"]),$p=ue.extend({level:ea}),Zp=X.extend({method:f("logging/setLevel"),params:$p}),Fp=fe.extend({level:ea,logger:c().optional(),data:B()}),Kp=ge.extend({method:f("notifications/message"),params:Fp}),Wp=m({name:c().optional()}),Jp=m({hints:l(Wp).optional(),costPriority:C().min(0).max(1).optional(),speedPriority:C().min(0).max(1).optional(),intelligencePriority:C().min(0).max(1).optional()}),Vp=m({mode:se(["auto","required","none"]).optional()}),Yp=m({type:f("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:l(kn).default([]),structuredContent:m({}).loose().optional(),isError:U().optional(),_meta:T(c(),B()).optional()}),Xp=cn("type",[An,vn,In]),gr=cn("type",[An,vn,In,Pp,Yp]),Qp=m({role:Bt,content:O([gr,l(gr)]),_meta:T(c(),B()).optional()}),el=yr.extend({messages:l(Qp),modelPreferences:Jp.optional(),systemPrompt:c().optional(),includeContext:se(["none","thisServer","allServers"]).optional(),temperature:C().optional(),maxTokens:C().int(),stopSequences:l(c()).optional(),metadata:F.optional(),tools:l(Xi).optional(),toolChoice:Vp.optional()}),tl=X.extend({method:f("sampling/createMessage"),params:el}),rl=Q.extend({model:c(),stopReason:j(se(["endTurn","stopSequence","maxTokens"]).or(c())),role:Bt,content:Xp}),nl=Q.extend({model:c(),stopReason:j(se(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Bt,content:O([gr,l(gr)])}),ol=m({type:f("boolean"),title:c().optional(),description:c().optional(),default:U().optional()}),il=m({type:f("string"),title:c().optional(),description:c().optional(),minLength:C().optional(),maxLength:C().optional(),format:se(["email","uri","date","date-time"]).optional(),default:c().optional()}),al=m({type:se(["number","integer"]),title:c().optional(),description:c().optional(),minimum:C().optional(),maximum:C().optional(),default:C().optional()}),sl=m({type:f("string"),title:c().optional(),description:c().optional(),enum:l(c()),default:c().optional()}),cl=m({type:f("string"),title:c().optional(),description:c().optional(),oneOf:l(m({const:c(),title:c()})),default:c().optional()}),ul=m({type:f("string"),title:c().optional(),description:c().optional(),enum:l(c()),enumNames:l(c()).optional(),default:c().optional()}),dl=O([sl,cl]),pl=m({type:f("array"),title:c().optional(),description:c().optional(),minItems:C().optional(),maxItems:C().optional(),items:m({type:f("string"),enum:l(c())}),default:l(c()).optional()}),ll=m({type:f("array"),title:c().optional(),description:c().optional(),minItems:C().optional(),maxItems:C().optional(),items:m({anyOf:l(m({const:c(),title:c()}))}),default:l(c()).optional()}),ml=O([pl,ll]),hl=O([ul,dl,ml]),fl=O([hl,ol,il,al]),gl=yr.extend({mode:f("form").optional(),message:c(),requestedSchema:m({type:f("object"),properties:T(c(),fl),required:l(c()).optional()})}),Un=yr.extend({mode:f("url"),message:c(),elicitationId:c(),url:c().url()}),yl=O([gl,Un]),wl=X.extend({method:f("elicitation/create"),params:yl}),Sl=fe.extend({elicitationId:c()}),Rl=ge.extend({method:f("notifications/elicitation/complete"),params:Sl}),_l=Q.extend({action:se(["accept","decline","cancel"]),content:dn(e=>e===null?void 0:e,T(c(),O([c(),C(),U(),l(c())])).optional())}),bl=m({type:f("ref/resource"),uri:c()});var Cl=m({type:f("ref/prompt"),name:c()}),xl=ue.extend({ref:O([Cl,bl]),argument:m({name:c(),value:c()}),context:m({arguments:T(c(),c()).optional()}).optional()}),Al=X.extend({method:f("completion/complete"),params:xl});var vl=Q.extend({completion:$({values:l(c()).max(100),total:j(C().int()),hasMore:j(U())})}),Il=m({uri:c().startsWith("file://"),name:c().optional(),_meta:T(c(),B()).optional()}),kl=X.extend({method:f("roots/list"),params:ue.optional()}),Ul=Q.extend({roots:l(Il)}),Tl=ge.extend({method:f("notifications/roots/list_changed"),params:fe.optional()}),$R=O([Di,tp,Al,Zp,Tp,Ip,pp,mp,gp,Rp,bp,Np,jp,Ni,$i,Zi,Ki]),ZR=O([Hi,ji,op,Tl,Bi]),FR=O([qi,rl,nl,_l,Ul,Gi,Fi,Li]),KR=O([Di,tl,wl,kl,Ni,$i,Zi,Ki]),WR=O([Hi,ji,Kp,xp,wp,Gp,qp,Bi,Rl]),JR=O([qi,np,vl,Mp,kp,lp,hp,yp,Qi,Lp,Gi,Fi,Li]),Sn=class e extends Error{static{n(this,"McpError")}constructor(t,r,o){super(`MCP error ${t}: ${r}`),this.code=t,this.data=o,this.name="McpError"}static fromError(t,r,o){if(t===ke.UrlElicitationRequired&&o){let a=o;if(a.elicitations)return new qt(a.elicitations,r)}return new e(t,r,o)}},qt=class extends Sn{static{n(this,"UrlElicitationRequiredError")}constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(ke.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};z();var ra=oe,Pl=i.object({mode:i.literal("auto")}).strict(),Ol=i.object({mode:i.literal("manual"),clientId:i.string().trim().min(1),clientSecret:i.string().min(1).optional(),tokenEndpointAuthMethod:wn.default("client_secret_basic")}).strict().superRefine((e,t)=>{e.tokenEndpointAuthMethod!=="none"&&!e.clientSecret&&t.addIssue({code:i.ZodIssueCode.custom,message:`${e.tokenEndpointAuthMethod} requires clientSecret`,path:["clientSecret"]})}),na=i.discriminatedUnion("mode",[Pl,Ol]),zl=na.default({mode:"auto"}),El=i.object({scopes:i.array(i.string().min(1)).default([]),scopeDelimiter:i.string().min(1).default(" "),clientRegistration:zl}).strict(),ta=El.extend({redirectPath:i.string().startsWith("/auth/connections/")}).strict(),Ml=i.discriminatedUnion("mode",[i.object({mode:i.literal("shared-oauth"),oauth:ta}).strict(),i.object({mode:i.literal("user-oauth"),oauth:ta}).strict()]),ql=i.object({baseUrl:i.url(),resourceMetadataUrl:i.url()}).strict(),r_=i.object({displayName:i.string().min(1),description:i.string().min(1).optional(),serverInfo:pt.optional(),transport:ql}).strict(),Hl=i.object({id:ra,displayName:i.string().min(1),description:i.string().min(1).optional(),serverInfo:pt.optional(),protectedResourceMetadataUrl:i.url().optional(),authMode:yn,authConfig:Ml}).strict().refine(e=>e.authMode===e.authConfig.mode,{message:"authMode must match authConfig.mode",path:["authConfig","mode"]}),Dl={id:ra.optional(),displayName:i.string().min(1),summary:i.string().min(1).optional(),serverInfo:pt.optional(),protectedResourceMetadataUrl:i.url().optional()},jl=i.object({...Dl,authMode:yn,scopes:i.array(i.string().min(1)).default([]),scopeDelimiter:i.string().min(1).default(" "),clientRegistration:na.optional(),clientId:i.string().trim().min(1).optional(),clientSecret:i.string().min(1).optional(),tokenEndpointAuthMethod:wn.optional()}).strict();function Ll(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
28
- `)}n(Ll,"formatZodIssues");function Bl(e){let t="mcp-token-exchange-";if(!e.startsWith(t))throw new _(`MCP token exchange policy ${e} must use the ${t}{upstream-id} naming convention when id is omitted.`);return oe.parse(e.slice(t.length))}n(Bl,"inferUpstreamConnectionIdFromPolicyName");function oa(e){let t=new URL(e),r=t.pathname==="/"?"":t.pathname;return`${t.origin}/.well-known/oauth-protected-resource${r}`}n(oa,"buildDefaultProtectedResourceMetadataUrl");function mt(e,t){return ce.parse(`${e}:${t}`)}n(mt,"buildUpstreamAuthProfileId");function Nl(e,t){let r=e.clientRegistration??(e.clientId===void 0?{mode:"auto"}:{mode:"manual",clientId:e.clientId,tokenEndpointAuthMethod:e.tokenEndpointAuthMethod??"client_secret_basic",...e.clientSecret===void 0?{}:{clientSecret:e.clientSecret}});return{mode:e.authMode,oauth:{scopes:e.scopes,scopeDelimiter:e.scopeDelimiter,redirectPath:`/auth/connections/${encodeURIComponent(t)}/callback`,clientRegistration:r}}}n(Nl,"resolveAuthConfig");function Rr(e,t){try{let r=jl.parse(e),o=r.id??(t===void 0?void 0:Bl(t));if(o===void 0)throw new _("MCP token exchange policy options must include id when policy name is unavailable.");return Hl.parse({id:o,displayName:r.displayName,...r.summary===void 0?{}:{description:r.summary},...r.serverInfo===void 0?{}:{serverInfo:r.serverInfo},...r.protectedResourceMetadataUrl===void 0?{}:{protectedResourceMetadataUrl:r.protectedResourceMetadataUrl},authMode:r.authMode,authConfig:Nl(r,o)})}catch(r){if(r instanceof i.ZodError){let o=t===void 0?"MCP token exchange policy":`Policy "${t}"`;throw new _(`${o} is misconfigured. Missing/invalid options in policies.json:
29
- ${Ll(r)}`,{cause:r})}throw r}}n(Rr,"parseUpstreamTokenExchangePolicyOptions");function ia(e){return e.mode==="shared-oauth"||e.mode==="user-oauth"}n(ia,"isUpstreamOAuthAuthConfig");var Gl="mcp-token-exchange-inbound";function $l(e,t,r){let o=new _(t,r===void 0?void 0:{cause:r});return o.extensionMembers={[y]:e},o}n($l,"configurationProblem");function _r(e){return e===Gl}n(_r,"isMcpTokenExchangePolicyType");function Zl(e){let t=mt(e.connection.id,e.connection.authMode);return{policyName:e.policyName,upstreamServerId:e.connection.id,displayName:e.connection.displayName,...e.connection.description===void 0?{}:{description:e.connection.description},...e.connection.serverInfo===void 0?{}:{serverInfo:e.connection.serverInfo},mcpUrl:e.mcpUrl,protectedResourceMetadataUrl:e.connection.protectedResourceMetadataUrl??oa(e.mcpUrl),authMode:e.connection.authMode,authProfileId:t,authConfig:e.connection.authConfig}}n(Zl,"buildRegisteredConnection");function Fl(e){let t=new Map;for(let r of e){if(t.has(r.name))throw new _(`Duplicate policy name ${r.name} in policies.json.`);t.set(r.name,{name:r.name,policyType:r.policyType,handler:{options:r.handler.options}})}return t}n(Fl,"buildPolicyMap");function Kl(e){if(typeof e.raw!="function")throw new _(`MCP route ${e.path} must declare operationId in routes.oas.json. The operationId is used as the stable MCP route identity for OAuth tokens, storage, upstream auth state, and analytics.`);let t=e.raw();if(!t||typeof t.operationId!="string"||t.operationId==="")throw new _(`MCP route ${e.path} must declare operationId in routes.oas.json. The operationId is used as the stable MCP route identity for OAuth tokens, storage, upstream auth state, and analytics.`);return G.parse(t.operationId)}n(Kl,"readOperationId");function Wl(e){let t=[];for(let r of e.route.policies?.inbound??[]){let o=e.policyByName.get(r);o&&_r(o.policyType)&&t.push(o)}if(t.length>1)throw new _(`MCP route ${e.route.path} must bind at most one MCP token exchange policy; found ${t.length}.`);if(t.length!==0)return e.readConnectionForPolicy(t[0],gn(e.route.handler))}n(Wl,"readRouteUpstreamConnection");function Jl(e){let t=new Map,r=new Map,o=new Map,a=new Set;function s(u,d){let p=o.get(u.name);if(p)return p;let h=Rr(u.handler.options,u.name);if(a.has(h.id))throw new _(`Duplicate upstream MCP connection id ${h.id} in policies.json.`);a.add(h.id);let g=Zl({policyName:u.name,connection:h,mcpUrl:d});return o.set(u.name,g),g}n(s,"readConnectionForPolicy");for(let u of e.routes){let d=u.policies?.inbound??[];if(d.length===0||!d.map(k=>e.policyByName.get(k)).filter(k=>k!==void 0).some(k=>Ai(k.policyType)||_r(k.policyType)))continue;let h=Kl(u);if(t.has(h))throw new _(`Duplicate MCP route operationId ${h} across routes.`);if(r.has(u.path))throw new _(`Duplicate MCP route path ${u.path} across routes.`);let g=Wl({route:u,policyByName:e.policyByName,readConnectionForPolicy:s}),D={operationId:h,routePath:u.path,...g===void 0?{}:{connection:g}};t.set(h,D),r.set(u.path,D)}return{byOperationId:t,byRoutePath:r,connectionsByPolicyName:o}}n(Jl,"buildMcpRoutes");function Pn(e){let t=Fl(e.policies),{byOperationId:r,byRoutePath:o,connectionsByPolicyName:a}=Jl({routes:e.routes,policyByName:t}),s=new Map;for(let u of a.values())s.set(u.upstreamServerId,u);return{byOperationId:r,byRoutePath:o,connectionsById:s}}n(Pn,"buildGatewayConnectionRegistry");var Ze,Tn;function aa(e){Tn=e,Ze=void 0}n(aa,"configureGatewayConnectionRegistrySource");function sa(e){Ze=e}n(sa,"setGatewayConnectionRegistry");function ye(){if(!Ze&&Tn&&(Ze=Pn(Tn)),!Ze)throw new _("MCP gateway connection registry has not been initialized. Ensure routes.oas.json declares at least one OAuth-protected MCP route and policies.json registers the matching MCP OAuth and upstream connection policies.");return Ze}n(ye,"getGatewayConnectionRegistry");function He(e){let r=ye().byOperationId.get(e);if(!r)throw $l("unknown_mcp_route",`Unknown MCP route: ${e}`,new Error(`Unknown MCP route "${e}". Ensure routes.oas.json declares this operationId and policies.json registers the matching MCP upstream connection policy.`));return r}n(He,"getRegisteredMcpRoute");function ca(e){let r=ye().byRoutePath.get(e);if(!r)throw new _(`MCP route ${e} is not registered. Ensure routes.oas.json declares operationId on this MCP route and its inbound policies include MCP OAuth or MCP token exchange.`);return r}n(ca,"getRegisteredMcpRouteByRoutePath");function ua(){return Ze}n(ua,"tryGetGatewayConnectionRegistry");z();var b=i.string().datetime({offset:!0}).brand();function x(e){return b.parse(e.toISOString())}n(x,"toIsoTimestamp");function Ue(e,t){return new Date(e.getTime()+t*1e3)}n(Ue,"addSeconds");z();function P(e){return new URL(e).origin}n(P,"readGatewayRequestOrigin");function Te(e){return P(e)}n(Te,"readGatewayOAuthIssuer");function On(e){return e.length>512?`${e.slice(0,512)}\u2026`:e}n(On,"truncate");function da(e){return"cause"in e?e.cause:void 0}n(da,"readCause");function ie(e,t,r){if(!(r instanceof Error)){r!=null&&(e[`${t}Message`]=On(String(r)));return}e[`${t}Name`]=r.name,e[`${t}Message`]=On(r.message);let o=da(r);for(let a=1;a<=4&&o instanceof Error;a+=1){let s=a===1?"cause":`cause${a}`;e[`${s}Name`]=o.name,e[`${s}Message`]=On(o.message),o=da(o)}}n(ie,"addErrorLogFields");function we(e){if(e!==void 0)try{return typeof e=="string"?new URL(e).host:e.host}catch{return}}n(we,"safeHost");function pa(e,t){let r=Object.entries(t).filter(o=>o[1]!==void 0);r.length!==0&&e.log.setLogProperties?.(Object.fromEntries(r))}n(pa,"setLogProperties");function br(e,t){pa(e,{subjectId:t.subjectId})}n(br,"applyGatewayPrincipalLogProperties");function la(e,t){pa(e,{upstreamServerId:t.upstreamServerId,operationId:t.operationId})}n(la,"applyGatewayRouteLogProperties");function ma(e){let t=W(e);return{title:t.title,body:t.publicDetail}}n(ma,"readGatewayCallbackFailureContent");function de(e){if(!(e instanceof w))return;let t=e.extensionMembers?.[y];return Ie(t)?t:void 0}n(de,"readGatewayProblemCode");function R(e,t,r){let o=typeof e=="string"?{code:e,...t===void 0?{}:{publicDetail:t,privateDetail:t},...r===void 0?{}:{cause:r}}:e,a=W(o.code),s=o.privateDetail??(Cr(o.code)?o.publicDetail??a.publicDetail:a.publicDetail),u=Vl(o);return new w({message:s,extensionMembers:{[y]:o.code}},u===void 0?void 0:{cause:u})}n(R,"createGatewayRuntimeError");async function De(e,t,r){let o=W(r.code),a=Yl(r.code,r.detail),s=Cr(r.code)?r.title??o.title:o.title,d={problem:{...he.getProblemFromStatus(o.status,{detail:a,instance:r.instance,type:r.type}),...r.extensions??{},status:o.status,title:s,detail:a,code:r.code}};return r.headers!==void 0&&(d.additionalHeaders=r.headers),he.format(d,e,t)}n(De,"gatewayProblemResponse");function Cr(e){return W(e).status<500}n(Cr,"canExposeGatewayProblemDetail");function Vl(e){return!e.privateDetail||Cr(e.code)?e.cause:e.cause===void 0?new Error(e.privateDetail):new Error(e.privateDetail,{cause:e.cause})}n(Vl,"readRuntimeErrorCause");function Yl(e,t){let r=W(e);return Cr(e)&&t||r.publicDetail}n(Yl,"readSafeGatewayProblemDetail");var Xl=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function Ql(e){return e.protocol.replace(/:$/u,"").toLowerCase()}n(Ql,"readScheme");function em(e){return e.protocol==="https:"}n(em,"isSpecCompliantRedirectUri");function tm(e){let t=Ql(e);return t.length>0&&t!=="http"&&t!=="https"&&!Xl.has(t)}n(tm,"isNativeAppCustomSchemeRedirectUri");var fa=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:n(e=>em(e),"accepts")},{id:"oauth.redirect_uri.loopback_http",mode:"native_app",accepts:n(e=>Z(e),"accepts"),matches:n((e,t)=>Z(e)&&Z(t)&&e.pathname===t.pathname&&e.search===t.search,"matches")},{id:"oauth.redirect_uri.custom_scheme",mode:"native_app",accepts:n(e=>tm(e),"accepts")}];function ga(e){let t=fa.find(r=>r.accepts(e.url,e.context));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}n(ga,"evaluateBuiltInRedirectUriCompatibility");function ha(e){try{return new URL(e)}catch{return}}n(ha,"parseUrl");function ya(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=ha(e.registeredRedirectUri),r=ha(e.requestedRedirectUri);if(t===void 0||r===void 0)return!1;let o=e.context??{source:"registration_match"};return fa.some(a=>a.matches?.(t,r,o))}n(ya,"redirectUriMatchesBuiltInCompatibility");z();var rm=43,nm=128,om=/^[A-Za-z0-9._~-]+$/,zn="S256",xr=i.literal(zn),Ar=i.string().min(rm).max(nm).regex(om);z();var wa=["none","client_secret_post","client_secret_basic"],En=[...wa,"private_key_jwt"],im=["awaiting_login","awaiting_setup"],am=i.string().min(1).brand(),J=i.string().min(1).brand(),Nt=i.uuid().brand(),pe=i.uuid().brand(),vr=i.uuid().brand(),Sa=i.enum(wa),Ra=i.enum(En),L_=i.enum(im),_a=i.object({client_id:J,client_name:i.string().min(1),redirect_uris:i.array(i.string().min(1)).min(1),jwks_uri:i.string().min(1).optional(),token_endpoint_auth_method:Ra.default("none")}).superRefine((e,t)=>{e.token_endpoint_auth_method==="private_key_jwt"&&e.jwks_uri===void 0&&t.addIssue({code:"custom",path:["jwks_uri"],message:"jwks_uri is required for private_key_jwt clients."})}),Mn=i.object({clientId:J,clientName:i.string().min(1),redirectUris:i.array(i.string().min(1)),tokenEndpointAuthMethod:Ra,hashedClientSecret:i.string().optional(),clientSecretExpiresAt:b.optional(),clientExpiresAt:b,revokedAt:b.optional(),createdAt:b}),qn=i.object({clientId:J,resource:i.string(),operationId:G,subjectId:am,scope:i.string(),roles:i.array(i.string()),createdAt:b,expiresAt:b}),B_=qn.extend({id:pe,redirectUri:i.string(),clientState:i.string().optional(),codeChallenge:i.string(),codeChallengeMethod:xr}),Hn=qn.extend({id:Nt,currentRefreshTokenHash:i.string().optional(),previousRefreshTokenHash:i.string().optional(),previousRefreshTokenRotatedAt:b.optional(),revokedAt:b.optional(),revokedReason:i.string().optional()}),Ir=qn.extend({tokenHash:i.string(),grantId:Nt,revokedAt:b.optional()});function Dn(){return pe.parse(crypto.randomUUID())}n(Dn,"createDownstreamAuthorizationTransactionId");function jn(){return vr.parse(crypto.randomUUID())}n(jn,"createDownstreamBrowserLoginStateId");function ba(){return Nt.parse(crypto.randomUUID())}n(ba,"createDownstreamGrantId");var M="mcp:tools";function Ca(e,t){return ya({registeredRedirectUri:e,requestedRedirectUri:t,context:{source:"registration_match"}})}n(Ca,"redirectUriMatchesRegistration");function xa(e){return Z(e)&&e.pathname==="/oauth/dev-login"}n(xa,"isLoopbackDevLoginUrl");function kr(e,t){return new URL(e,Te(t)).toString()}n(kr,"buildGatewayOAuthUrl");function Ln(e){let t=He(G.parse(e.operationId));return new URL(t.routePath,P(e.requestUrl)).toString()}n(Ln,"buildScopedAuthorizationServerIssuer");function sm(e){return new URL(`/oauth/authorize/mcp/${encodeURIComponent(e.operationId)}`,P(e.requestUrl)).toString()}n(sm,"buildScopedAuthorizationEndpoint");function Bn(e){let t=K();return{issuer:Te(e),authorization_endpoint:kr("/oauth/authorize",e),token_endpoint:kr("/oauth/token",e),registration_endpoint:kr("/oauth/register",e),revocation_endpoint:kr("/oauth/revoke",e),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],scopes_supported:[M],code_challenge_methods_supported:[zn],token_endpoint_auth_methods_supported:En,revocation_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post","private_key_jwt","none"],client_id_metadata_document_supported:t.gateway.cimdEnabled,"x-zuplo-browser-login-kind":_i(t)}}n(Bn,"buildAuthorizationServerMetadata");function Aa(e){let t=Ln(e);return{...Bn(e.requestUrl),issuer:t,authorization_endpoint:sm(e)}}n(Aa,"buildScopedAuthorizationServerMetadata");var va="2025-06-18";async function Ia(e,t){try{let r=G.parse(e.params.operationId),o=He(r);return Response.json(cm(o.operationId,e.url))}catch(r){let o=de(r);return De(e,t,{code:o==="unknown_mcp_route"?o:"not_found",detail:(r instanceof Error?r.message:void 0)??"The requested protected resource metadata document was not found."})}}n(Ia,"protectedResourceMetadataHandler");function cm(e,t){return{resource:ht(e,t),resource_name:e,authorization_servers:[Ln({operationId:e,requestUrl:t})],bearer_methods_supported:["header"],scopes_supported:[M],mcp_protocol_version:va}}n(cm,"buildProtectedResourceMetadataResponseBody");function ht(e,t){let r=He(e);return new URL(r.routePath,P(t)).toString()}n(ht,"buildCanonicalMcpResourceForRoute");function ka(e,t){return new URL(`/.well-known/oauth-protected-resource/mcp/${encodeURIComponent(e)}`,P(t)).toString()}n(ka,"buildProtectedResourceMetadataUrlForRoute");var um=i.record(i.string(),i.unknown()),Ua=i.string().min(1),dm=i.union([Ua.transform(e=>[e]),i.array(Ua)]),q=i.string().min(1).brand(),pm=["zuploSubjectId","zuplo_subject_id","gatewaySubjectId","gateway_subject_id","subjectId","subject_id","https://zuplo.com/subject_id"],lm=["https://zuplo.com/roles","roles","role","permissions","groups"],Ta=new qe("gateway-principal");function mm(e){let t=um.safeParse(e);return t.success?t.data:{}}n(mm,"toClaimRecord");function hm(e){return e.issues[0]?.message??"Gateway principal is invalid"}n(hm,"readValidationFailureDetail");function fm(e,t,r){for(let s of pm){let u=q.safeParse(t[s]);if(u.success)return u.data}let o=q.safeParse(e?.sub);if(!o.success)throw R("identity_context_missing",hm(o.error));let a=typeof t.iss=="string"?t.iss:void 0;return!a||a===Te(r)?o.data:q.parse(`${a}|${o.data}`)}n(fm,"readNormalizedSubjectId");function gm(e){let t=new Set;for(let r of lm){let o=dm.safeParse(e[r]);if(o.success)for(let a of o.data)t.add(a)}return t.size>0?[...t]:void 0}n(gm,"readRoles");function Fe(e,t){let r=mm(e?.data),o={subjectId:fm(e,r,t)},a=gm(r);return a&&(o.roles=a),o}n(Fe,"parseGatewayPrincipal");function Gn(e,t){Ta.set(e,t)}n(Gn,"setGatewayPrincipal");function $n(e){return Ta.get(e)}n($n,"readGatewayPrincipal");function Pa(e,t){let r=$n(t);if(r)return r;let o=Fe(e.user,e.url);return Gn(t,o),br(t,o),o}n(Pa,"readOrHydrateGatewayPrincipal");function Ur(e){let r=['realm="OAuth"',`resource_metadata="${Nn(ka(e.operationId,e.requestUrl))}"`];return e.error!==void 0&&r.push(`error="${e.error}"`),e.errorDescription!==void 0&&r.push(`error_description="${Nn(e.errorDescription)}"`),e.scope!==void 0&&r.push(`scope="${Nn(e.scope)}"`),`Bearer ${r.join(", ")}`}n(Ur,"buildGatewayBearerChallenge");function Nn(e){let t="";for(let r=0;r<e.length;r+=1){let o=e.charCodeAt(r);o<=31||o===127||(t+=e[r])}return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}n(Nn,"sanitizeQuotedHeaderParameter");function Oa(e){let t=bn.safeParse(e);return t.success?t.data.id:void 0}n(Oa,"parseJsonRpcRequestId");function za(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Oa(t)}catch{return}}n(za,"readJsonRpcRequestIdFromBody");async function Ea(e){try{let t=await e.clone().json();return Oa(t)}catch{return}}n(Ea,"readJsonRpcRequestId");function Tr(e){return Sr.parse({jsonrpc:dt,...e.id===void 0?{}:{id:e.id},error:{code:e.error.code,message:e.error.message,...e.error.data===void 0?{}:{data:e.error.data}}})}n(Tr,"jsonRpcErrorResponse");function Ma(e){return new qt([Un.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Ma,"urlElicitationRequiredError");z();z();function qa(e){return new w({message:e,extensionMembers:{[y]:"invalid_request"}})}n(qa,"invalidReturnTo");function Pr(e){if(e===void 0||e.length===0)return;if(!e.startsWith("/")||e.startsWith("//"))throw qa("returnTo must be a same-origin relative path.");let t=new URL(e,"https://gateway.local");if(t.origin!=="https://gateway.local"||t.username||t.password||t.hash||t.pathname.startsWith("//"))throw qa("returnTo must be a same-origin relative path without credentials or fragments.");return`${t.pathname}${t.search}`}n(Pr,"parseSafeRelativeReturnTo");z();var ym=["user","shared"],ft=i.enum(ym);function gt(e){return{mode:"user",subjectId:e}}n(gt,"buildUserUpstreamConnectionOwner");function Or(){return{mode:"shared"}}n(Or,"buildSharedUpstreamConnectionOwner");var Ha=i.object({ownerMode:ft,initiatedBySubjectId:q,ownerSubjectId:q.optional(),upstreamServerId:oe,authProfileId:ce,operationId:G,returnTo:i.string().min(1).transform(e=>Pr(e)).optional()});function Da(e,t){e.ownerMode==="user"&&!e.ownerSubjectId&&t.addIssue({code:i.ZodIssueCode.custom,message:"User-owned state requires ownerSubjectId",path:["ownerSubjectId"]}),e.ownerMode==="shared"&&e.ownerSubjectId&&t.addIssue({code:i.ZodIssueCode.custom,message:"Shared state must not include ownerSubjectId",path:["ownerSubjectId"]})}n(Da,"validateUpstreamOwnerState");var yt=Ha.superRefine(Da),ja=Ha.omit({returnTo:!0}).superRefine(Da);function Gt(e){return yt.parse({ownerMode:e.owner.mode,initiatedBySubjectId:e.initiatedBySubjectId,ownerSubjectId:e.owner.mode==="user"?e.owner.subjectId:void 0,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,returnTo:e.returnTo})}n(Gt,"buildUpstreamOwnerState");function zr(e){if(e.ownerMode==="shared")return Or();if(!e.ownerSubjectId)throw new w({message:"User-owned upstream state is missing the owner subject.",extensionMembers:{[y]:"oauth_state_invalid"}});return gt(e.ownerSubjectId)}n(zr,"resolveUpstreamConnectionOwnerFromState");var wm=["active","not_connected","reconsent_required"],Sm=["basic_auth_app_password","bearer_token"],La=i.string().trim().min(1).brand(),wt=i.uuid().brand(),$t=i.uuid().brand(),Zn=i.enum(wm),Rm=i.enum(Sm),Ba=i.object({encryptedClientInformation:i.string().optional(),encryptedDiscoveryState:i.string().optional(),connectedBySubjectId:q.optional()}),_m=Ba.extend({encryptedStaticSecret:i.string().optional(),staticSecretKind:Rm.optional(),staticSecretLabel:i.string().min(1).optional(),staticSecretUsername:i.string().min(1).optional()}).strict(),bm=i.object({id:La,subjectId:q.optional(),ownerMode:ft,upstreamServerId:oe,authProfileId:ce,status:Zn,encryptedAccessToken:i.string().min(1).optional(),encryptedRefreshToken:i.string().min(1).optional(),scopes:i.array(i.string()),expiresAt:b.optional(),metadata:_m.optional(),createdAt:b,updatedAt:b});function Fn(e,t){e.ownerMode==="user"&&(e.subjectId||t.addIssue({code:i.ZodIssueCode.custom,message:"User-owned upstream connections require subjectId",path:["subjectId"]})),e.ownerMode==="shared"&&e.subjectId!==void 0&&t.addIssue({code:i.ZodIssueCode.custom,message:"Shared upstream connections must not include subjectId",path:["subjectId"]})}n(Fn,"validateUpstreamConnectionOwnerShape");var St=bm.superRefine(Fn);function Na(e){return JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId])}n(Na,"readUpstreamConnectionLookupKey");var Kn=yt.extend({id:wt,callbackPath:i.string().min(1),expiresAt:b,codeVerifier:i.string().optional(),redirectUri:i.url(),returnOrigin:i.url().optional()}).extend(Ba.shape);function Ga(e){let t=e?.status??"not_connected",r={connected:t==="active",status:t};return e?.updatedAt!==void 0&&(r.updatedAt=e.updatedAt),r}n(Ga,"readUpstreamConnectionStatus");function $a(){return La.parse(`mcpgw2uc_${crypto.randomUUID()}`)}n($a,"createUpstreamConnectionId");function Za(){return wt.parse(crypto.randomUUID())}n(Za,"createOAuthStateId");function Fa(){return $t.parse(crypto.randomUUID())}n(Fa,"createBrowserConnectTicketId");z();var Jn=i.discriminatedUnion("mode",[i.object({mode:i.literal("user"),subjectId:q}).strict(),i.object({mode:i.literal("shared")}).strict()]),Wa=i.object({owner:Jn,upstreamServerId:oe,authProfileId:ce}).strict(),Ja=i.object({items:i.array(Wa).min(1).max(100)}).strict(),Vn=i.object({items:i.array(i.object({key:i.object({ownerMode:ft,subjectId:q.optional(),upstreamServerId:oe,authProfileId:ce}).strict(),connection:St.strict().optional()}).strict())}).strict(),Va=St.omit({createdAt:!0,updatedAt:!0}).strict().superRefine(Fn),Ya=St.strict(),Xa=i.object({owner:Jn,upstreamServerId:oe,authProfileId:ce}).strict(),Qa=i.object({owner:Jn,upstreamServerId:oe,authProfileId:ce,connection:St.strict().optional(),connectionStatus:i.object({connected:i.boolean(),status:Zn,updatedAt:St.shape.updatedAt.optional()}).strict()}).strict(),Cm=i.enum(["none","client_secret_basic","client_secret_post","private_key_jwt"]),Ke=i.object({clientId:J,clientName:i.string().min(1),tokenEndpointAuthMethod:Cm}).strict(),Yn=i.discriminatedUnion("method",[i.object({method:i.literal("none"),clientId:J}).strict(),i.object({method:i.enum(["client_secret_basic","client_secret_post"]),clientId:J,clientSecretHashInput:i.string().min(1)}).strict(),i.object({method:i.literal("private_key_jwt"),clientId:J}).strict()]),Xn=i.object({id:pe,currentStateHash:i.string().min(1),clientId:J,redirectUri:i.string().min(1),resource:i.string().min(1),operationId:G,clientState:i.string().optional(),scope:i.string(),codeChallenge:i.string().min(1),codeChallengeMethod:i.literal("S256"),setupApprovedAt:b.optional(),createdAt:b,expiresAt:b,consumedAt:b.optional()}).strict(),Ka=Xn.omit({id:!0,consumedAt:!0}).extend({transactionId:pe,client:Ke.optional()}).strict(),Qn=i.object({subjectId:q,roles:i.array(i.string()).optional()}).strict(),xm=Xn.extend({phase:i.literal("awaiting_login")}).strict(),Wn=Xn.extend({phase:i.literal("awaiting_setup"),principal:Qn}).strict(),Am=i.discriminatedUnion("phase",[xm,Wn]),Er=i.object({transaction:Am,client:Ke}).strict(),es=Mn.omit({revokedAt:!0}).strict(),ts=i.discriminatedUnion("kind",[i.object({kind:i.literal("registered"),client:Ke}).strict(),i.object({kind:i.literal("already_exists")}).strict()]),rs=i.object({clientId:J}).strict(),ns=i.discriminatedUnion("kind",[i.object({kind:i.literal("found"),client:Mn.strict()}).strict(),i.object({kind:i.literal("missing")}).strict()]),os=i.discriminatedUnion("phase",[Ka.extend({phase:i.literal("awaiting_login")}).strict(),Ka.extend({phase:i.literal("awaiting_setup"),principal:Qn}).strict()]),is=i.discriminatedUnion("kind",[Er.extend({kind:i.literal("started")}).strict(),i.object({kind:i.literal("invalid_client")}).strict(),i.object({kind:i.literal("redirect_uri_mismatch")}).strict(),i.object({kind:i.literal("already_exists")}).strict()]),as=i.object({transactionId:pe,currentStateHash:i.string().min(1),now:b}).strict(),ss=i.discriminatedUnion("kind",[Er.extend({kind:i.literal("available")}).strict(),i.object({kind:i.literal("stale_hash")}).strict(),i.object({kind:i.literal("consumed")}).strict(),i.object({kind:i.literal("expired")}).strict(),i.object({kind:i.literal("missing")}).strict()]),cs=i.object({transactionId:pe,expectedPhase:i.literal("awaiting_login"),currentStateHash:i.string().min(1),nextStateHash:i.string().min(1),nextPhase:i.literal("awaiting_setup"),principal:Qn,now:b}).strict(),us=i.discriminatedUnion("kind",[Er.extend({kind:i.literal("advanced")}).strict(),i.object({kind:i.literal("wrong_phase"),current:i.enum(["awaiting_login","awaiting_setup"])}).strict(),i.object({kind:i.literal("stale_hash")}).strict(),i.object({kind:i.literal("consumed")}).strict(),i.object({kind:i.literal("expired")}).strict(),i.object({kind:i.literal("missing")}).strict()]),ds=i.object({transactionId:pe,currentStateHash:i.string().min(1),currentPrincipal:i.object({subjectId:q}).strict(),now:b}).strict(),ps=i.discriminatedUnion("kind",[Er.extend({kind:i.literal("marked")}).strict(),i.object({kind:i.literal("wrong_phase"),current:i.enum(["awaiting_login","awaiting_setup"])}).strict(),i.object({kind:i.literal("principal_mismatch")}).strict(),i.object({kind:i.literal("stale_hash")}).strict(),i.object({kind:i.literal("consumed")}).strict(),i.object({kind:i.literal("expired")}).strict(),i.object({kind:i.literal("missing")}).strict()]),ls=i.discriminatedUnion("decision",[i.object({decision:i.literal("approve"),transactionId:pe,currentStateHash:i.string().min(1),currentPrincipal:i.object({subjectId:q}).strict(),authorizationCodeHash:i.string().min(1),authorizationCodeExpiresAt:b,grantId:Nt,now:b}).strict(),i.object({decision:i.literal("cancel"),transactionId:pe,currentStateHash:i.string().min(1),currentPrincipal:i.object({subjectId:q}).strict(),now:b}).strict()]),ms=i.discriminatedUnion("kind",[i.object({kind:i.literal("approved"),transaction:Wn,client:Ke}).strict(),i.object({kind:i.literal("cancelled"),transaction:Wn,client:Ke}).strict(),i.object({kind:i.literal("principal_mismatch")}).strict(),i.object({kind:i.literal("stale_hash")}).strict(),i.object({kind:i.literal("consumed_already")}).strict(),i.object({kind:i.literal("expired")}).strict(),i.object({kind:i.literal("missing")}).strict()]),hs=i.object({clientAuth:Yn,codeHash:i.string().min(1),redirectUri:i.string().min(1),resource:i.string().min(1).optional(),codeChallenge:i.string().min(1),currentRefreshTokenHash:i.string().min(1),accessTokenHash:i.string().min(1),grantExpiresAt:b,accessTokenExpiresAt:b,now:b}).strict(),fs=i.discriminatedUnion("kind",[i.object({kind:i.literal("exchanged"),client:Ke,grant:Hn.strict()}).strict(),i.object({kind:i.literal("invalid_client")}).strict(),i.object({kind:i.literal("consumed")}).strict(),i.object({kind:i.literal("missing")}).strict(),i.object({kind:i.literal("expired")}).strict(),i.object({kind:i.literal("resource_mismatch")}).strict(),i.object({kind:i.literal("binding_mismatch")}).strict()]),gs=i.object({clientAuth:Yn,currentRefreshTokenHash:i.string().min(1),nextRefreshTokenHash:i.string().min(1),accessTokenHash:i.string().min(1),resource:i.string().min(1).optional(),accessTokenExpiresAt:b,now:b}).strict(),ys=i.discriminatedUnion("kind",[i.object({kind:i.literal("rotated"),client:Ke,grant:Hn.strict(),accessToken:Ir.strict(),matched:i.literal("current")}).strict(),i.object({kind:i.literal("invalid_client")}).strict(),i.object({kind:i.literal("missing")}).strict(),i.object({kind:i.literal("expired")}).strict(),i.object({kind:i.literal("resource_mismatch")}).strict(),i.object({kind:i.literal("previous_token_grace")}).strict(),i.object({kind:i.literal("revoked")}).strict()]),ws=i.object({clientAuth:Yn,tokenHash:i.string().min(1),now:b}).strict(),Ss=i.discriminatedUnion("kind",[i.object({kind:i.literal("revoked_access_token")}).strict(),i.object({kind:i.literal("revoked_grant")}).strict(),i.object({kind:i.literal("client_mismatch")}).strict(),i.object({kind:i.literal("missing")}).strict(),i.object({kind:i.literal("invalid_client")}).strict()]),Rs=i.object({tokenHash:i.string().min(1),now:b}).strict(),_s=i.discriminatedUnion("kind",[i.object({kind:i.literal("valid"),record:Ir.strict()}).strict(),i.object({kind:i.literal("missing")}).strict(),i.object({kind:i.literal("expired")}).strict(),i.object({kind:i.literal("revoked")}).strict()]),bs=i.object({accessTokenHash:i.string().min(1),resource:i.string().min(1),operationId:G,upstreamConnectionKeys:i.array(Wa).max(100),now:b}).strict(),Cs=i.discriminatedUnion("kind",[i.object({kind:i.literal("authorized"),principal:i.object({subjectId:q,roles:i.array(i.string())}).strict(),accessToken:Ir.strict(),upstreamConnections:Vn.shape.items.optional().default([])}).strict(),i.object({kind:i.literal("missing")}).strict(),i.object({kind:i.literal("expired")}).strict(),i.object({kind:i.literal("revoked")}).strict(),i.object({kind:i.literal("resource_mismatch")}).strict(),i.object({kind:i.literal("principal_mismatch")}).strict()]),xs=i.object({record:Kn}).strict(),As=i.object({kind:i.literal("saved")}).strict(),vs=i.object({id:wt,now:b}).strict(),Is=i.discriminatedUnion("kind",[i.object({kind:i.literal("available"),record:Kn}).strict(),i.object({kind:i.literal("consumed")}).strict(),i.object({kind:i.literal("missing")}).strict()]),ks=i.object({id:$t,expiresAt:b,now:b}).strict(),Us=i.discriminatedUnion("kind",[i.object({kind:i.literal("available")}).strict(),i.object({kind:i.literal("consumed")}).strict()]);var Ts=100,vm=new Set(["undefined","null","nan"]);function Ps(e){return e!==null&&typeof e=="object"}n(Ps,"isProblemDetailsShape");var Os="bckt_";function V(e){let t=nt.instance.runtime.ZUPLO_SERVICE_BUCKET_ID;if(!t)throw We("internal_server_error","MCP Gateway runtime storage requires ZUPLO_SERVICE_BUCKET_ID.");if(!t.startsWith(Os))throw We("internal_server_error",`MCP Gateway runtime storage bucket ID must start with "${Os}".`);return`/zups/v2/buckets/${encodeURIComponent(t)}/mcp/storage/${e}`}n(V,"buildStoragePath");function Im(){return V("upstream-connections/batch-get")}n(Im,"buildBatchGetUpstreamConnectionsPath");function km(){return V("upstream-connections/upsert")}n(km,"buildUpsertUpstreamConnectionPath");function Um(){return V("authorization/read-setup")}n(Um,"buildReadAuthorizationSetupPath");function Tm(){return V("oauth/register-client")}n(Tm,"buildRegisterClientPath");function Pm(){return V("oauth/read-client")}n(Pm,"buildReadClientPath");function Om(){return V("authorization/start")}n(Om,"buildStartAuthorizationPath");function zm(){return V("authorization/read-pending")}n(zm,"buildReadPendingAuthorizationPath");function Em(){return V("authorization/advance-pending")}n(Em,"buildAdvancePendingAuthorizationPath");function Mm(){return V("authorization/mark-setup-approved")}n(Mm,"buildMarkAuthorizationSetupApprovedPath");function qm(){return V("authorization/decide-setup")}n(qm,"buildDecideAuthorizationSetupPath");function Hm(){return V("token/exchange-authorization-code")}n(Hm,"buildExchangeAuthorizationCodePath");function Dm(){return V("token/refresh")}n(Dm,"buildRefreshTokenPath");function jm(){return V("token/revoke")}n(jm,"buildRevokeOAuthTokenPath");function Lm(){return V("token/validate-access-token")}n(Lm,"buildValidateAccessTokenPath");function Bm(){return V("mcp/authorize-and-load-connections")}n(Bm,"buildAuthorizeAndLoadConnectionsPath");function Nm(){return V("upstream-oauth-state/save")}n(Nm,"buildSaveUpstreamOAuthStatePath");function Gm(){return V("upstream-oauth-state/consume")}n(Gm,"buildConsumeUpstreamOAuthStatePath");function $m(){return V("browser-connect-ticket/consume")}n($m,"buildConsumeBrowserConnectTicketPath");function Zm(e,t){return e.ownerMode===t.owner.mode&&(e.subjectId??"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}n(Zm,"responseKeyMatchesLookup");function Fm(e,t){return e.owner.mode===t.owner.mode&&(e.owner.mode==="user"?e.owner.subjectId:"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}n(Fm,"authorizationSetupMatchesLookup");function Ms(e,t){return e.ownerMode===t.owner.mode&&(e.subjectId??"")===(t.owner.mode==="user"?t.owner.subjectId:"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId}n(Ms,"connectionMatchesLookup");function Km(e,t){return e.ownerMode===t.ownerMode&&(e.subjectId??"")===(t.subjectId??"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId&&e.status===t.status&&(e.encryptedAccessToken??"")===(t.encryptedAccessToken??"")&&(e.encryptedRefreshToken??"")===(t.encryptedRefreshToken??"")&&ro(e.scopes,t.scopes)&&to(e.expiresAt,t.expiresAt)&&Wm(e.metadata,t.metadata)}n(Km,"connectionMatchesUpsertRecord");function to(e,t){return e===void 0||t===void 0?e===t:Date.parse(e)===Date.parse(t)}n(to,"optionalTimestampInstantsMatch");function zs(e,t){return Date.parse(e)<=Date.parse(t)}n(zs,"timestampInstantIsAtOrBefore");function ro(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}n(ro,"stringArraysMatch");function Wm(e,t){let r=Es(e),o=Es(t),a=Object.fromEntries(o);return r.length===o.length&&r.every(([s,u])=>a[s]===u)}n(Wm,"metadataMatches");function Es(e){return Object.entries(e??{}).filter(t=>t[1]!==void 0)}n(Es,"definedMetadataEntries");function H(e,t){throw We("internal_server_error",e,t)}n(H,"throwInvalidStorageResponse");function We(e,t,r){let o=fr[e],a=o.status<500,s=a?r:new Error(t,r===void 0?void 0:{cause:r});return new w({message:a?t:o.publicDetail,extensionMembers:{[y]:e}},s===void 0?void 0:{cause:s})}n(We,"storageRuntimeError");async function Jm(e,t){try{let r=await e.json();return r&&typeof r=="object"&&!Array.isArray(r)&&delete r.$schema,t.parse(r)}catch(r){H("Gateway Service storage response did not match the runtime storage contract.",r)}}n(Jm,"parseRuntimeHttpStorageResponse");function qs(e,t){e.length!==t.length&&H("Gateway Service storage response item count did not match the request.");for(let[r,o]of e.entries()){let a=t[r];Zm(o.key,a)||H("Gateway Service storage response key did not match the request."),o.connection!==void 0&&!Ms(o.connection,a)&&H("Gateway Service storage response connection did not match the response key.")}}n(qs,"validateUpstreamConnectionItemsMatchLookups");function Vm(e,t){Fm(e,t)||H("Gateway Service storage response authorization setup did not match the request."),e.connection!==void 0&&!Ms(e.connection,t)&&H("Gateway Service storage response authorization setup connection did not match the request.");let r=e.connection?.status==="active",o=e.connection?.status??"not_connected",a=e.connection?.updatedAt;(e.connectionStatus.connected!==r||e.connectionStatus.status!==o||!to(e.connectionStatus.updatedAt,a))&&H("Gateway Service storage response authorization setup status did not match the connection.")}n(Vm,"validateAuthorizationSetupResponseMatchesLookup");function Ym(e,t){e.kind==="registered"&&(e.client.clientId!==t.clientId||e.client.clientName!==t.clientName||e.client.tokenEndpointAuthMethod!==t.tokenEndpointAuthMethod)&&H("Gateway Service storage response registered client did not match the request.")}n(Ym,"validateRegisterClientResponseMatchesRequest");function Xm(e,t){e.kind==="found"&&e.client.clientId!==t.clientId&&H("Gateway Service storage response client did not match the request.")}n(Xm,"validateReadClientResponseMatchesRequest");function Qm(e,t){e.kind==="started"&&((e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==t.currentStateHash||e.transaction.phase!==t.phase||e.transaction.clientId!==t.clientId||e.transaction.redirectUri!==t.redirectUri||e.transaction.resource!==t.resource||e.transaction.operationId!==t.operationId||(e.transaction.clientState??"")!==(t.clientState??"")||e.transaction.scope!==t.scope||e.transaction.codeChallenge!==t.codeChallenge||e.transaction.codeChallengeMethod!==t.codeChallengeMethod)&&H("Gateway Service storage response started authorization did not match the request."),t.phase==="awaiting_setup"&&(e.transaction.phase!=="awaiting_setup"||e.transaction.principal.subjectId!==t.principal.subjectId)&&H("Gateway Service storage response started authorization principal did not match the request."))}n(Qm,"validateStartAuthorizationResponseMatchesRequest");function eo(e,t){e.kind!=="available"&&e.kind!=="advanced"&&e.kind!=="marked"||((e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==("nextStateHash"in t?t.nextStateHash:t.currentStateHash))&&H("Gateway Service storage response pending authorization did not match the request."),"nextPhase"in t&&(e.transaction.phase!==t.nextPhase||e.transaction.phase!=="awaiting_setup"||e.transaction.principal.subjectId!==t.principal.subjectId)&&H("Gateway Service storage response advanced authorization did not match the request."),"currentPrincipal"in t&&(e.transaction.phase!=="awaiting_setup"||e.transaction.principal.subjectId!==t.currentPrincipal.subjectId)&&H("Gateway Service storage response marked authorization principal did not match the request."),e.kind==="marked"&&"currentPrincipal"in t&&e.transaction.setupApprovedAt!==t.now&&H("Gateway Service storage response marked authorization setup approval timestamp did not match the request."))}n(eo,"validatePendingAuthorizationResponseMatchesRequest");function eh(e,t){e.kind!=="approved"&&e.kind!=="cancelled"||(e.transaction.id!==t.transactionId||e.transaction.currentStateHash!==t.currentStateHash||e.transaction.principal.subjectId!==t.currentPrincipal.subjectId)&&H("Gateway Service storage response authorization setup transaction did not match the request.")}n(eh,"validateAuthorizationSetupDecisionResponseMatchesRequest");function th(e,t){e.kind==="exchanged"&&(e.client.clientId!==t.clientAuth.clientId||e.client.tokenEndpointAuthMethod!==t.clientAuth.method||e.grant.clientId!==t.clientAuth.clientId||e.grant.currentRefreshTokenHash!==t.currentRefreshTokenHash||!to(e.grant.expiresAt,t.grantExpiresAt)||t.resource!==void 0&&e.grant.resource!==t.resource)&&H("Gateway Service storage response authorization-code exchange did not match the request.")}n(th,"validateExchangeAuthorizationCodeResponseMatchesRequest");function rh(e,t){e.kind==="rotated"&&((e.client.clientId!==t.clientAuth.clientId||e.client.tokenEndpointAuthMethod!==t.clientAuth.method||e.grant.clientId!==t.clientAuth.clientId||e.grant.currentRefreshTokenHash!==t.nextRefreshTokenHash||e.grant.previousRefreshTokenHash!==t.currentRefreshTokenHash||t.resource!==void 0&&e.grant.resource!==t.resource)&&H("Gateway Service storage response token refresh grant did not match the request."),(e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.grantId!==e.grant.id||!zs(e.accessToken.expiresAt,t.accessTokenExpiresAt)||!zs(e.accessToken.expiresAt,e.grant.expiresAt)||!ih(e.accessToken,e.grant))&&H("Gateway Service storage response token refresh access token did not match the request."))}n(rh,"validateRefreshTokenResponseMatchesRequest");function nh(e,t){e.kind==="valid"&&e.record.tokenHash!==t.tokenHash&&H("Gateway Service storage response access token did not match the request.")}n(nh,"validateAccessTokenValidationResponseMatchesRequest");function oh(e,t){e.kind==="authorized"&&((e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.resource!==t.resource||e.accessToken.operationId!==t.operationId||e.principal.subjectId!==e.accessToken.subjectId||!ro(e.principal.roles,e.accessToken.roles))&&H("Gateway Service storage response MCP authorization did not match the request."),qs(e.upstreamConnections,t.upstreamConnectionKeys))}n(oh,"validateAuthorizeAndLoadConnectionsResponseMatchesRequest");function ih(e,t){return e.clientId===t.clientId&&e.resource===t.resource&&e.operationId===t.operationId&&e.subjectId===t.subjectId&&e.scope===t.scope&&ro(e.roles,t.roles)}n(ih,"accessTokenMatchesGrant");async function ah(e){try{return await e.clone().json()}catch{return}}n(ah,"readProblemDetails");async function sh(e){let t=await ah(e),r=Ps(t)&&typeof t.status=="number"?t.status:e.status,o=Ps(t)&&Ie(t.code)?t.code:Ui(r);throw We(o,`Gateway Service storage request failed with HTTP ${r}.`)}n(sh,"throwRuntimeHttpStorageError");var Mr=class{static{n(this,"RuntimeHttpStorageClient")}#t;#r;constructor(t){this.#t=t.baseUrl??nt.instance.zuploEdgeApiUrl,this.#r=t.fetch??fetch}#n(t){let r;try{r=new URL(t,this.#t)}catch(o){throw We("internal_server_error",`Gateway Service storage base URL is not a valid URL. Got ${JSON.stringify(this.#t)}. Verify the gateway runtime configuration.`,o)}if(r.protocol!=="https:"&&r.protocol!=="http:")throw We("internal_server_error",`Gateway Service storage base URL must use http(s); got protocol "${r.protocol}" from ${JSON.stringify(this.#t)}.`);if(!r.hostname||vm.has(r.hostname))throw We("internal_server_error",`Gateway Service storage base URL has an invalid hostname "${r.hostname}" (parsed from ${JSON.stringify(this.#t)}). The configured value is likely coerced from an unset environment variable.`);return r}async#e(t){let r=t.requestSchema.parse(t.input),o=this.#n(t.path),a=new Headers({"Content-Type":"application/json"});ii(a);let s=await this.#r(o,{method:"POST",headers:a,body:JSON.stringify(r)});return s.ok||await sh(s),{request:r,response:await Jm(s,t.responseSchema)}}async batchGetUpstreamConnections(t){if(t.length===0)return[];let r=[],o=new Map,a=t.map(u=>{let d=Na(u),p=o.get(d);if(p!==void 0)return p;let h=r.length;return r.push(u),o.set(d,h),h}),s=[];for(let u=0;u<r.length;u+=Ts){let d=r.slice(u,u+Ts);s.push(...await this.#o(d))}return a.map(u=>s[u])}async upsertUpstreamConnection(t){let{request:r,response:o}=await this.#e({input:t,path:km(),requestSchema:Va,responseSchema:Ya});return Km(o,r)||H("Gateway Service storage response connection did not match the request."),o}async readAuthorizationSetup(t){let{request:r,response:o}=await this.#e({input:t,path:Um(),requestSchema:Xa,responseSchema:Qa});return Vm(o,r),o}async registerClient(t){let{request:r,response:o}=await this.#e({input:t,path:Tm(),requestSchema:es,responseSchema:ts});return Ym(o,r),o}async readClient(t){let{request:r,response:o}=await this.#e({input:t,path:Pm(),requestSchema:rs,responseSchema:ns});return Xm(o,r),o}async startAuthorization(t){let{request:r,response:o}=await this.#e({input:t,path:Om(),requestSchema:os,responseSchema:is});return Qm(o,r),o}async readPendingAuthorization(t){let{request:r,response:o}=await this.#e({input:t,path:zm(),requestSchema:as,responseSchema:ss});return eo(o,r),o}async advancePendingAuthorization(t){let{request:r,response:o}=await this.#e({input:t,path:Em(),requestSchema:cs,responseSchema:us});return eo(o,r),o}async markAuthorizationSetupApproved(t){let{request:r,response:o}=await this.#e({input:t,path:Mm(),requestSchema:ds,responseSchema:ps});return eo(o,r),o}async decideAuthorizationSetup(t){let{request:r,response:o}=await this.#e({input:t,path:qm(),requestSchema:ls,responseSchema:ms});return eh(o,r),o}async saveUpstreamOAuthState(t){let{response:r}=await this.#e({input:t,path:Nm(),requestSchema:xs,responseSchema:As});return r}async consumeUpstreamOAuthState(t){let{request:r,response:o}=await this.#e({input:t,path:Gm(),requestSchema:vs,responseSchema:Is});return o.kind==="available"&&o.record.id!==r.id&&H("Gateway Service storage response upstream OAuth state did not match the request."),o}async consumeBrowserConnectTicket(t){let{response:r}=await this.#e({input:t,path:$m(),requestSchema:ks,responseSchema:Us});return r}async exchangeAuthorizationCode(t){let{request:r,response:o}=await this.#e({input:t,path:Hm(),requestSchema:hs,responseSchema:fs});return th(o,r),o}async refreshToken(t){let{request:r,response:o}=await this.#e({input:t,path:Dm(),requestSchema:gs,responseSchema:ys});return rh(o,r),o}async revokeOAuthToken(t){let{response:r}=await this.#e({input:t,path:jm(),requestSchema:ws,responseSchema:Ss});return r}async validateAccessToken(t){let{request:r,response:o}=await this.#e({input:t,path:Lm(),requestSchema:Rs,responseSchema:_s});return nh(o,r),o}async authorizeAndLoadConnections(t){let{request:r,response:o}=await this.#e({input:t,path:Bm(),requestSchema:bs,responseSchema:Cs});return oh(o,r),o}async#o(t){let r={items:[...t]},{response:o}=await this.#e({input:r,path:Im(),requestSchema:Ja,responseSchema:Vn});return qs(o.items,t),o.items.map(a=>a.connection)}};var ch="__zuploMcpGatewayStorageBackend",no;function uh(){return new Mr({})}n(uh,"buildProductionStorageBackend");function A(){let e=globalThis[ch];return e||(no||(no=uh()),no)}n(A,"getStorage");function dh(e,t){let r=$n(e),o=mr(e),a=t.ownerMode??t.routeBinding?.ownerMode,s=t.upstreamAuthMode??t.routeBinding?.authMode,u=t.virtualServerName??t.routeBinding?.operationId??o?.operationId,d=t.upstreamServerName??t.routeBinding?.upstreamServerId??o?.upstreamServerId,p=t.upstreamServerTitle??t.routeBinding?.upstreamDisplayName,h=t.authProfileId??t.routeBinding?.authProfileId??o?.authProfileId;return fi(e,{...t,subjectId:r?.subjectId,ownerMode:a,upstreamAuthMode:s,virtualServerName:u,upstreamServerName:d,upstreamServerTitle:p,authProfileId:h})}n(dh,"buildMcpAnalyticsMetadata");function I(e,t){try{e.analyticsContext.addAnalyticsEvent(t.value??1,t.eventType,dh(e,t),t.unit)}catch(r){e.log?.warn?.({event:"mcp_analytics_emit_failed",errorName:r instanceof Error?r.name:"unknown"})}}n(I,"emitMcpAnalyticsEvent");import{base64url as oo}from"jose";var ph="sha256:",lh=32;function Hs(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(Hs,"copyToArrayBuffer");function Pe(){let e=crypto.getRandomValues(new Uint8Array(lh));return oo.encode(e)}n(Pe,"createOpaqueToken");async function E(e){let t=await crypto.subtle.digest("SHA-256",Hs(new TextEncoder().encode(e)));return`${ph}${oo.encode(new Uint8Array(t))}`}n(E,"hashOpaqueValue");async function Ds(e){let t=await crypto.subtle.digest("SHA-256",Hs(new TextEncoder().encode(e)));return oo.encode(new Uint8Array(t))}n(Ds,"calculatePkceS256Challenge");var mh=ke.InvalidRequest;function hh(e){let t=e.headers.get("authorization"),[r,o]=t?.split(/\s+/,2)??[];if(!(r?.toLowerCase()!=="bearer"||!o))return o}n(hh,"readBearerToken");function fh(e,t,r){return De(e,t,{code:"authentication_required",detail:"Gateway access token is required.",headers:{"WWW-Authenticate":r}})}n(fh,"gatewayAuthenticationRequiredResponse");function gh(e){switch(e){case"expired":return"expired_token";case"revoked":return"revoked_token";case"missing":return"invalid_token";default:{let t=e;return"invalid_token"}}}n(gh,"tokenValidationReasonCode");async function yh(e,t,r){let o=await A().validateAccessToken({tokenHash:await E(e),now:x(new Date)});if(o.kind!=="valid"){t.log.warn({event:"gateway_access_token_validate_failed",code:"authentication_required",validationKind:o.kind,operationId:r},"Gateway access token validation failed");let a=gh(o.kind);throw I(t,{eventType:v.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:r,reasonClass:"auth",reasonCode:a,attributes:{validationKind:o.kind}}),I(t,{eventType:v.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:r,httpStatusCode:401,reasonClass:"auth",reasonCode:a}),R("authentication_required","Gateway access token is expired, revoked, or invalid.")}return o.record}n(yh,"validateGatewayAccessToken");function wh(e,t){if(e.accessToken.resource!==e.resource||e.accessToken.operationId!==e.operationId)throw t.log.warn({event:"gateway_access_token_resource_mismatch",code:"authentication_required",expectedResource:e.resource,tokenResource:e.accessToken.resource,expectedOperationId:e.operationId,tokenOperationId:e.accessToken.operationId,clientId:e.accessToken.clientId},"Gateway access token resource does not match the requested MCP resource"),I(t,{eventType:v.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:e.operationId,reasonClass:"auth",reasonCode:"invalid_audience"}),I(t,{eventType:v.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:e.operationId,httpStatusCode:401,reasonClass:"auth",reasonCode:"invalid_audience"}),R("authentication_required","Gateway access token was not issued for this MCP resource.")}n(wh,"assertAccessTokenResource");function Sh(e,t,r){return De(e,t,{code:"forbidden",detail:"Gateway access token is missing the required MCP scope.",headers:{"WWW-Authenticate":Ur({operationId:r,requestUrl:e.url,error:"insufficient_scope",errorDescription:`The access token is missing the ${M} scope required by this MCP resource.`,scope:M})}})}n(Sh,"insufficientScopeResponse");function Rh(e){return{subjectId:e.subjectId,roles:e.roles}}n(Rh,"principalFromAccessToken");async function js(e){return Response.json(Tr({id:await Ea(e.request),error:{code:mh,message:e.message}}))}n(js,"mcpAuthorizationDeniedResponse");async function _h(e){switch((await A().authorizeAndLoadConnections({accessTokenHash:await E(e.token),resource:e.resource,operationId:e.operationId,upstreamConnectionKeys:[],now:x(new Date)})).kind){case"authorized":return;case"resource_mismatch":return js({request:e.request,message:"Gateway access token was not issued for this MCP resource."});case"principal_mismatch":return js({request:e.request,message:"Gateway access token principal does not match this MCP resource."});case"missing":case"expired":case"revoked":throw R("authentication_required","Gateway access token is expired, revoked, or invalid.")}}n(_h,"assertCompositeMcpAuthorization");function bh(e){let t=de(e.error),r={event:"gateway_access_token_rejected",code:t??"authentication_required",operationId:e.operationId};return e.error instanceof Error?(r.errorName=e.error.name,r.errorMessage=e.error.message):e.error!==void 0&&e.error!==null&&(r.errorMessage=String(e.error)),e.context.log.warn(r,"Gateway access token rejected; MCP request denied"),De(e.request,e.context,{code:t??"authentication_required",detail:e.error instanceof Error?e.error.message:"Gateway access token could not be verified.",headers:{"WWW-Authenticate":Ur({operationId:e.operationId,requestUrl:e.request.url,error:"invalid_token",errorDescription:"The access token is expired, malformed, or invalid."})}})}n(bh,"gatewayTokenRejectedResponse");async function io(e,t,r){let o=ht(r.operationId,e.url),a=hh(e),s=Ur({operationId:r.operationId,requestUrl:e.url});if(!a)return t.log.debug({event:"gateway_access_token_missing",code:"authentication_required",operationId:r.operationId,hasAuthorizationHeader:e.headers.get("authorization")!==null},"MCP request did not include a gateway access token"),I(t,{eventType:v.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:r.operationId,httpStatusCode:401,reasonClass:"auth",reasonCode:"missing_token"}),fh(e,t,s);try{let u=await yh(a,t,r.operationId);if(wh({accessToken:u,resource:o,operationId:r.operationId},t),u.scope!==M)return t.log.warn({event:"gateway_access_token_insufficient_scope",code:"forbidden",tokenScope:u.scope,requiredScope:M,operationId:r.operationId,clientId:u.clientId},"Gateway access token does not have the required MCP scope"),I(t,{eventType:v.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:r.operationId,reasonClass:"auth",reasonCode:"insufficient_scope",attributes:{tokenScope:u.scope,requiredScope:M,clientId:u.clientId}}),I(t,{eventType:v.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:r.operationId,httpStatusCode:403,reasonClass:"auth",reasonCode:"insufficient_scope"}),Sh(e,t,r.operationId);let d=await _h({token:a,resource:o,operationId:r.operationId,request:e});if(d)return d;let p=Rh(u);Gn(t,p),br(t,p),I(t,{eventType:v.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED,outcome:"success",virtualServerName:r.operationId,attributes:{clientId:u.clientId}});let h=new Headers(e.headers);return h.delete("authorization"),new lr(e,{headers:h})}catch(u){return bh({request:e,context:t,error:u,operationId:r.operationId})}}n(io,"gatewayTokenInbound");var Rt={OAUTH_PROTECTED_RESOURCE_METADATA:"oauth_metadata",VIRTUAL_MCP_SERVER:"gateway",OTHER:"other"},Ch="oauth-protected-resource-metadata",xh="/.well-known/oauth-protected-resource/";function Ah(e){let r=(typeof e.route.raw=="function"?e.route.raw():void 0)?.operationId;return typeof r=="string"?r:void 0}n(Ah,"readRouteOperationId");function vh(e){return e.hasGatewayRouteContext?Rt.VIRTUAL_MCP_SERVER:e.routeOperationId===Ch||e.routeOperationId===void 0&&e.routePath.startsWith(xh)?Rt.OAUTH_PROTECTED_RESOURCE_METADATA:Rt.OTHER}n(vh,"classifyAnalyticsRouteSurface");function Ih(e){let t=e.route.path;return{routePath:t,routeSurface:vh({routePath:t,routeOperationId:Ah(e),hasGatewayRouteContext:mr(e)!==void 0})}}n(Ih,"readAnalyticsRequestContext");function kh(e){return e.response.status===405&&e.response.headers.has("allow")&&e.routeSurface===Rt.VIRTUAL_MCP_SERVER}n(kh,"isIntentionalMethodRejection");function Uh(e){return kh(e)||e.response.status===401&&e.routeSurface===Rt.OAUTH_PROTECTED_RESOURCE_METADATA?"success":e.response.status>=400?"failure":"success"}n(Uh,"classifyRequestCompletedOutcome");async function ao(e,t){let r=Date.now(),o=Ih(t);return I(t,{eventType:v.MCP_REQUEST_RECEIVED,outcome:"success",routeSurface:o.routeSurface,httpMethod:e.method}),sn.getContextExtensions(t).addHandlerResponseHook(a=>{let s=Uh({response:a,routeSurface:o.routeSurface});I(t,{eventType:v.MCP_REQUEST_COMPLETED,outcome:s,routeSurface:o.routeSurface,httpStatusCode:a.status,httpMethod:e.method,latencyMs:Date.now()-r})}),e}n(ao,"analyticsContextInbound");function Th(e){return e instanceof Response}n(Th,"isResponse");async function Mt(e,t){let r=ca(t.route.path),o={operationId:r.operationId};wi(t,o),la(t,o);let a=await ao(e,t);return Th(a)?a:io(a,t,{operationId:r.operationId})}n(Mt,"mcpOAuthInboundPolicy");var Ph=i.string({error:"auth0Domain is required and must be a string"}).trim().min(1,"auth0Domain is required (commonly set via $env(AUTH0_DOMAIN))").refine(e=>!/[:/]/.test(e),{message:'auth0Domain must be a bare hostname (e.g. "tenant.us.auth0.com"); drop the "https://" prefix and any trailing path'}).refine(e=>e.includes("."),{message:'auth0Domain must be a fully-qualified domain name with at least one dot (e.g. "tenant.us.auth0.com"). If the value looks like "undefined" or is empty, the configured environment variable is likely unset.'}),Oh=i.object({auth0Domain:Ph,audience:i.string().trim().min(1).optional(),clientId:i.string({error:"clientId is required and must be a string"}).trim().min(1,"clientId is required (commonly set via $env(AUTH0_CLIENT_ID))"),clientSecret:i.string({error:"clientSecret is required and must be a string"}).trim().min(1,"clientSecret is required (commonly set via $env(AUTH0_CLIENT_SECRET))"),scope:i.string().trim().min(1).optional(),gateway:i.object({accessTokenTtlSeconds:i.number().int().positive().optional(),refreshTokenTtlSeconds:i.number().int().positive().optional(),cimdEnabled:i.boolean().optional()}).strict().optional(),browserLoginOverrides:i.object({remoteTimeoutMs:i.number().int().positive().optional(),stateTtlSeconds:i.number().int().positive().optional(),sessionTtlSeconds:i.number().int().positive().optional()}).strict().optional()}).strict(),so=class extends it{static{n(this,"McpAuth0OAuthInboundPolicy")}#t;constructor(t,r){let o=Ls(t,r);super(o,r),this.#t=Bs(o,r)}async handler(t,r){return ot("policy.inbound.mcp-auth0-oauth"),st(r,this.#t),Mt(t,r)}};function Ls(e,t){return hr(Oh,e,`MCP Auth0 OAuth policy "${t}"`)}n(Ls,"parseAuth0OAuthOptions");function Ii(e,t="mcp-auth0-oauth-inbound"){let r=Ls(e,t);return Bs(r,t)}n(Ii,"auth0OptionsToMcpOAuthRuntimeConfig");function Bs(e,t){let r=`https://${e.auth0Domain}/`,o=`https://${e.auth0Domain}/.well-known/jwks.json`,a=`https://${e.auth0Domain}/authorize`,s=`https://${e.auth0Domain}/oauth/token`;try{return Ci({oidc:{issuer:r,jwksUrl:o,...e.audience===void 0?{}:{audience:e.audience}},browserLogin:{url:a,tokenUrl:s,clientId:e.clientId,clientSecret:e.clientSecret,scope:e.scope??"openid profile email",...e.audience===void 0?{}:{audience:e.audience},...e.browserLoginOverrides??{}},gateway:e.gateway})}catch(u){let d=u instanceof Error?` Validation failed: ${u.message}`:"";throw new _(`MCP Auth0 OAuth policy "${t}" is misconfigured. Check the policy options in policies.json.${d}`,u instanceof Error?{cause:u}:void 0)}}n(Bs,"buildAuth0McpOAuthRuntimeConfig");function je(e){let t=ye().connectionsById.get(e);if(!t)throw new _(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,...t.description===void 0?{}:{description:t.description},...t.serverInfo===void 0?{}:{serverInfo:t.serverInfo},transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}n(je,"getUpstreamServerConfig");function zh(e){let t=ye().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new _(`Unknown auth profile "${String(e.authProfileId)}" for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares a matching auth mode for that upstream connection.`);return t.authProfileId}n(zh,"resolveUpstreamAuthProfileId");function co(e){zh(e);let t=ye().connectionsById.get(e.upstreamServerId);if(!t)throw new _(`Auth profile could not be resolved for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares the upstream connection before this handler runs.`);return t.authConfig}n(co,"getUpstreamAuthConfig");function Je(e,t){let r=co({upstreamServerId:e,authProfileId:t});if(!ia(r))throw new _(`Upstream server "${e}" does not use upstream OAuth. Select an auth mode that supports the requested upstream connect flow or remove the upstream OAuth route for this server.`);return r.oauth}n(Je,"requireUpstreamOAuthConfig");var Eh={"shared-oauth":{authMode:"shared-oauth",ownerMode:"shared",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"},"user-oauth":{authMode:"user-oauth",ownerMode:"user",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"}};function Re(e){return Eh[e]}n(Re,"describeUpstreamAuthMode");function qr(e){return Re(e).ownerMode}n(qr,"resolveOwnerModeForUpstreamAuthMode");var uo;uo=globalThis.crypto;async function Mh(e){return(await uo).getRandomValues(new Uint8Array(e))}n(Mh,"getRandomValues");async function qh(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let a=await Mh(e-o.length);for(let s of a)s<r&&(o+=t[s%t.length])}return o}n(qh,"random");async function Hh(e){return await qh(e)}n(Hh,"generateVerifier");async function Dh(e){let t=await(await uo).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(Dh,"generateChallenge");async function po(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Hh(e),r=await Dh(t);return{code_verifier:t,code_challenge:r}}n(po,"pkceChallenge");z();var ee=ui().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:mi.custom,message:"URL must be parseable",fatal:!0}),si}).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"}),Hr=$({resource:c().url(),authorization_servers:l(ee).optional(),jwks_uri:c().url().optional(),scopes_supported:l(c()).optional(),bearer_methods_supported:l(c()).optional(),resource_signing_alg_values_supported:l(c()).optional(),resource_name:c().optional(),resource_documentation:c().optional(),resource_policy_uri:c().url().optional(),resource_tos_uri:c().url().optional(),tls_client_certificate_bound_access_tokens:U().optional(),authorization_details_types_supported:l(c()).optional(),dpop_signing_alg_values_supported:l(c()).optional(),dpop_bound_access_tokens_required:U().optional()}),Zt=$({issuer:c(),authorization_endpoint:ee,token_endpoint:ee,registration_endpoint:ee.optional(),scopes_supported:l(c()).optional(),response_types_supported:l(c()),response_modes_supported:l(c()).optional(),grant_types_supported:l(c()).optional(),token_endpoint_auth_methods_supported:l(c()).optional(),token_endpoint_auth_signing_alg_values_supported:l(c()).optional(),service_documentation:ee.optional(),revocation_endpoint:ee.optional(),revocation_endpoint_auth_methods_supported:l(c()).optional(),revocation_endpoint_auth_signing_alg_values_supported:l(c()).optional(),introspection_endpoint:c().optional(),introspection_endpoint_auth_methods_supported:l(c()).optional(),introspection_endpoint_auth_signing_alg_values_supported:l(c()).optional(),code_challenge_methods_supported:l(c()).optional(),client_id_metadata_document_supported:U().optional()}),jh=$({issuer:c(),authorization_endpoint:ee,token_endpoint:ee,userinfo_endpoint:ee.optional(),jwks_uri:ee,registration_endpoint:ee.optional(),scopes_supported:l(c()).optional(),response_types_supported:l(c()),response_modes_supported:l(c()).optional(),grant_types_supported:l(c()).optional(),acr_values_supported:l(c()).optional(),subject_types_supported:l(c()),id_token_signing_alg_values_supported:l(c()),id_token_encryption_alg_values_supported:l(c()).optional(),id_token_encryption_enc_values_supported:l(c()).optional(),userinfo_signing_alg_values_supported:l(c()).optional(),userinfo_encryption_alg_values_supported:l(c()).optional(),userinfo_encryption_enc_values_supported:l(c()).optional(),request_object_signing_alg_values_supported:l(c()).optional(),request_object_encryption_alg_values_supported:l(c()).optional(),request_object_encryption_enc_values_supported:l(c()).optional(),token_endpoint_auth_methods_supported:l(c()).optional(),token_endpoint_auth_signing_alg_values_supported:l(c()).optional(),display_values_supported:l(c()).optional(),claim_types_supported:l(c()).optional(),claims_supported:l(c()).optional(),service_documentation:c().optional(),claims_locales_supported:l(c()).optional(),ui_locales_supported:l(c()).optional(),claims_parameter_supported:U().optional(),request_parameter_supported:U().optional(),request_uri_parameter_supported:U().optional(),require_request_uri_registration:U().optional(),op_policy_uri:ee.optional(),op_tos_uri:ee.optional(),client_id_metadata_document_supported:U().optional()}),Dr=m({...jh.shape,...Zt.pick({code_challenge_methods_supported:!0}).shape}),_t=m({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:hi.number().optional(),scope:c().optional(),refresh_token:c().optional()}).strip(),Gs=m({error:c(),error_description:c().optional(),error_uri:c().optional()}),Ns=ee.optional().or(f("").transform(()=>{})),Lh=m({redirect_uris:l(ee),token_endpoint_auth_method:c().optional(),grant_types:l(c()).optional(),response_types:l(c()).optional(),client_name:c().optional(),client_uri:ee.optional(),logo_uri:Ns,scope:c().optional(),contacts:l(c()).optional(),tos_uri:Ns,policy_uri:c().optional(),jwks_uri:ee.optional(),jwks:pi().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),lo=m({client_id:c(),client_secret:c().optional(),client_id_issued_at:C().optional(),client_secret_expires_at:C().optional()}).strip(),Ft=Lh.merge(lo),bx=m({error:c(),error_description:c().optional()}).strip(),Cx=m({token:c(),token_type_hint:c().optional()}).strip();function $s(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n($s,"resourceUrlFromServerUrl");function Zs({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let a=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",s=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return a.startsWith(s)}n(Zs,"checkResourceAllowed");var N=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}},Kt=class extends N{static{n(this,"InvalidRequestError")}};Kt.errorCode="invalid_request";var Ve=class extends N{static{n(this,"InvalidClientError")}};Ve.errorCode="invalid_client";var Ye=class extends N{static{n(this,"InvalidGrantError")}};Ye.errorCode="invalid_grant";var Xe=class extends N{static{n(this,"UnauthorizedClientError")}};Xe.errorCode="unauthorized_client";var Wt=class extends N{static{n(this,"UnsupportedGrantTypeError")}};Wt.errorCode="unsupported_grant_type";var Jt=class extends N{static{n(this,"InvalidScopeError")}};Jt.errorCode="invalid_scope";var Vt=class extends N{static{n(this,"AccessDeniedError")}};Vt.errorCode="access_denied";var Oe=class extends N{static{n(this,"ServerError")}};Oe.errorCode="server_error";var Yt=class extends N{static{n(this,"TemporarilyUnavailableError")}};Yt.errorCode="temporarily_unavailable";var Xt=class extends N{static{n(this,"UnsupportedResponseTypeError")}};Xt.errorCode="unsupported_response_type";var Qt=class extends N{static{n(this,"UnsupportedTokenTypeError")}};Qt.errorCode="unsupported_token_type";var er=class extends N{static{n(this,"InvalidTokenError")}};er.errorCode="invalid_token";var tr=class extends N{static{n(this,"MethodNotAllowedError")}};tr.errorCode="method_not_allowed";var rr=class extends N{static{n(this,"TooManyRequestsError")}};rr.errorCode="too_many_requests";var Qe=class extends N{static{n(this,"InvalidClientMetadataError")}};Qe.errorCode="invalid_client_metadata";var nr=class extends N{static{n(this,"InsufficientScopeError")}};nr.errorCode="insufficient_scope";var or=class extends N{static{n(this,"InvalidTargetError")}};or.errorCode="invalid_target";var Fs={[Kt.errorCode]:Kt,[Ve.errorCode]:Ve,[Ye.errorCode]:Ye,[Xe.errorCode]:Xe,[Wt.errorCode]:Wt,[Jt.errorCode]:Jt,[Vt.errorCode]:Vt,[Oe.errorCode]:Oe,[Yt.errorCode]:Yt,[Xt.errorCode]:Xt,[Qt.errorCode]:Qt,[er.errorCode]:er,[tr.errorCode]:tr,[rr.errorCode]:rr,[Qe.errorCode]:Qe,[nr.errorCode]:nr,[or.errorCode]:or};function Bh(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(Bh,"isClientAuthMethod");var mo="code",ho="S256";function Nh(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Bh(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(Nh,"selectClientAuthMethod");function Gh(e,t,r,o){let{client_id:a,client_secret:s}=t;switch(e){case"client_secret_basic":$h(a,s,r);return;case"client_secret_post":Zh(a,s,o);return;case"none":Fh(a,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(Gh,"applyClientAuthentication");function $h(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($h,"applyBasicAuth");function Zh(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(Zh,"applyPostAuth");function Fh(e,t){t.set("client_id",e)}n(Fh,"applyPublicAuth");async function Ws(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Gs.parse(JSON.parse(r)),{error:a,error_description:s,error_uri:u}=o,d=Fs[a]||Oe;return new d(s||"",u)}catch(o){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new Oe(a)}}n(Ws,"parseErrorResponse");async function go(e,t){try{return await fo(e,t)}catch(r){if(r instanceof Ve||r instanceof Xe)return await e.invalidateCredentials?.("all"),await fo(e,t);if(r instanceof Ye)return await e.invalidateCredentials?.("tokens"),await fo(e,t);throw r}}n(go,"auth");async function fo(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:a,fetchFn:s}){let u=await e.discoveryState?.(),d,p,h,g=a;if(!g&&u?.resourceMetadataUrl&&(g=new URL(u.resourceMetadataUrl)),u?.authorizationServerUrl){if(p=u.authorizationServerUrl,d=u.resourceMetadata,h=u.authorizationServerMetadata??await Vs(p,{fetchFn:s}),!d)try{d=await Js(t,{resourceMetadataUrl:g},s)}catch{}(h!==u.authorizationServerMetadata||d!==u.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(p),resourceMetadataUrl:g?.toString(),resourceMetadata:d,authorizationServerMetadata:h})}else{let Y=await Xh(t,{resourceMetadataUrl:g,fetchFn:s});p=Y.authorizationServerUrl,h=Y.authorizationServerMetadata,d=Y.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(p),resourceMetadataUrl:g?.toString(),resourceMetadata:d,authorizationServerMetadata:h})}let D=await Kh(t,e,d),k=o||d?.scopes_supported?.join(" ")||e.clientMetadata.scope,ne=await Promise.resolve(e.clientInformation());if(!ne){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let Y=h?.client_id_metadata_document_supported===!0,te=e.clientMetadataUrl;if(te&&!yo(te))throw new Qe(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${te}`);if(Y&&te)ne={client_id:te},await e.saveClientInformation?.(ne);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let ni=await nf(p,{metadata:h,clientMetadata:e.clientMetadata,scope:k,fetchFn:s});await e.saveClientInformation(ni),ne=ni}}let Se=!e.redirectUrl;if(r!==void 0||Se){let Y=await rf(e,p,{metadata:h,resource:D,authorizationCode:r,fetchFn:s});return await e.saveTokens(Y),"AUTHORIZED"}let Me=await e.tokens();if(Me?.refresh_token)try{let Y=await tf(p,{metadata:h,clientInformation:ne,refreshToken:Me.refresh_token,resource:D,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(Y),"AUTHORIZED"}catch(Y){if(!(!(Y instanceof N)||Y instanceof Oe))throw Y}let xe=e.state?await e.state():void 0,{authorizationUrl:Ot,codeVerifier:Ae}=await Qh(p,{metadata:h,clientInformation:ne,state:xe,redirectUrl:e.redirectUrl,scope:k,resource:D});return await e.saveCodeVerifier(Ae),await e.redirectToAuthorization(Ot),"REDIRECT"}n(fo,"authInternal");function yo(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(yo,"isHttpsUrl");async function Kh(e,t,r){let o=$s(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!Zs({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(Kh,"selectResourceURL");async function Js(e,t,r=fetch){let o=await Vh(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 Hr.parse(await o.json())}n(Js,"discoverOAuthProtectedResourceMetadata");async function wo(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?wo(e,void 0,r):void 0;throw o}}n(wo,"fetchWithCorsRetry");function Wh(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(Wh,"buildWellKnownPath");async function Ks(e,t,r=fetch){return await wo(e,{"MCP-Protocol-Version":t},r)}n(Ks,"tryMetadataDiscovery");function Jh(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(Jh,"shouldAttemptFallback");async function Vh(e,t,r,o){let a=new URL(e),s=o?.protocolVersion??Rn,u;if(o?.metadataUrl)u=new URL(o.metadataUrl);else{let p=Wh(t,a.pathname);u=new URL(p,o?.metadataServerUrl??a),u.search=a.search}let d=await Ks(u,s,r);if(!o?.metadataUrl&&Jh(d,a.pathname)){let p=new URL(`/.well-known/${t}`,a);d=await Ks(p,s,r)}return d}n(Vh,"discoverMetadataWithFallback");function Yh(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let a=t.pathname;return a.endsWith("/")&&(a=a.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:"oidc"}),o.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(Yh,"buildDiscoveryUrls");async function Vs(e,{fetchFn:t=fetch,protocolVersion:r=Rn}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},a=Yh(e);for(let{url:s,type:u}of a){let d=await wo(s,o,t);if(d){if(!d.ok){if(await d.body?.cancel(),d.status>=400&&d.status<500)continue;throw new Error(`HTTP ${d.status} trying to load ${u==="oauth"?"OAuth":"OpenID provider"} metadata from ${s}`)}return u==="oauth"?Zt.parse(await d.json()):Dr.parse(await d.json())}}}n(Vs,"discoverAuthorizationServerMetadata");async function Xh(e,t){let r,o;try{r=await Js(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch{}o||(o=String(new URL("/",e)));let a=await Vs(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:a,resourceMetadata:r}}n(Xh,"discoverOAuthServerInfo");async function Qh(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:a,state:s,resource:u}){let d;if(t){if(d=new URL(t.authorization_endpoint),!t.response_types_supported.includes(mo))throw new Error(`Incompatible auth server: does not support response type ${mo}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(ho))throw new Error(`Incompatible auth server: does not support code challenge method ${ho}`)}else d=new URL("/authorize",e);let p=await po(),h=p.code_verifier,g=p.code_challenge;return d.searchParams.set("response_type",mo),d.searchParams.set("client_id",r.client_id),d.searchParams.set("code_challenge",g),d.searchParams.set("code_challenge_method",ho),d.searchParams.set("redirect_uri",String(o)),s&&d.searchParams.set("state",s),a&&d.searchParams.set("scope",a),a?.includes("offline_access")&&d.searchParams.append("prompt","consent"),u&&d.searchParams.set("resource",u.href),{authorizationUrl:d,codeVerifier:h}}n(Qh,"startAuthorization");function ef(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(ef,"prepareAuthorizationCodeRequest");async function Ys(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:a,resource:s,fetchFn:u}){let d=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),p=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(s&&r.set("resource",s.href),a)await a(p,r,d,t);else if(o){let g=t?.token_endpoint_auth_methods_supported??[],D=Nh(o,g);Gh(D,o,p,r)}let h=await(u??fetch)(d,{method:"POST",headers:p,body:r});if(!h.ok)throw await Ws(h);return _t.parse(await h.json())}n(Ys,"executeTokenRequest");async function tf(e,{metadata:t,clientInformation:r,refreshToken:o,resource:a,addClientAuthentication:s,fetchFn:u}){let d=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),p=await Ys(e,{metadata:t,tokenRequestParams:d,clientInformation:r,addClientAuthentication:s,resource:a,fetchFn:u});return{refresh_token:o,...p}}n(tf,"refreshAuthorization");async function rf(e,t,{metadata:r,resource:o,authorizationCode:a,fetchFn:s}={}){let u=e.clientMetadata.scope,d;if(e.prepareTokenRequest&&(d=await e.prepareTokenRequest(u)),!d){if(!a)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let h=await e.codeVerifier();d=ef(a,h,e.redirectUrl)}let p=await e.clientInformation();return Ys(t,{metadata:r,tokenRequestParams:d,clientInformation:p??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:s})}n(rf,"fetchToken");async function nf(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:a}){let s;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(t.registration_endpoint)}else s=new URL("/register",e);let u=await(a??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!u.ok)throw await Ws(u);return Ft.parse(await u.json())}n(nf,"registerClient");function _e(e){return new w({message:e,extensionMembers:{[y]:"invalid_request"}})}n(_e,"invalidOutboundUrl");function of(){let e=at.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP??globalThis.process?.env?.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP;return typeof e=="string"&&e==="1"}n(of,"isTestOnlyAllowHttpLoopbackIdpEnabled");function af(){let e=at.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_CIMD??globalThis.process?.env?.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_CIMD;return typeof e=="string"&&e==="1"}n(af,"isTestOnlyAllowHttpLoopbackCimdEnabled");var sf=new Set(["undefined","null","nan"]);function Ro(e,t){if(!e.hostname)throw _e(`Outbound URL has an empty hostname (got ${JSON.stringify(t)}). This typically indicates an unset $env(...) reference or a JS template literal coercing \`undefined\` into a URL. Check the policy options or runtime config that produced this URL.`);if(sf.has(e.hostname.toLowerCase()))throw _e(`Outbound URL hostname is ${JSON.stringify(e.hostname)} (from ${JSON.stringify(t)}). This almost always means an environment variable referenced by $env(...) is unset and a JS value was string-coerced into a URL. Set the missing env var or fix the policy option that produced this URL.`)}n(Ro,"assertSafeOutboundHostname");var cf=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),uf=[{first:0},{first:10},{first:127},{first:169,secondMin:254,secondMax:254},{first:172,secondMin:16,secondMax:31},{first:192,secondMin:168,secondMax:168},{first:100,secondMin:64,secondMax:127},{first:224,firstMax:239},{first:240,firstMax:255}];function Xs(e){if(!/^\d+\.\d+\.\d+\.\d+$/.test(e))return;let t=e.split(".").map(r=>Number(r));if(!(t.length!==4||t.some(r=>Number.isNaN(r)||r<0||r>255)))return t}n(Xs,"parseIpv4Octets");function df([e,t],r){let o=r.firstMax??r.first;return e<r.first||e>o?!1:r.secondMin===void 0||r.secondMax===void 0?!0:t>=r.secondMin&&t<=r.secondMax}n(df,"ipv4RangeMatches");function Qs(e){let t=Xs(e);return t!==void 0&&uf.some(r=>df(t,r))}n(Qs,"isPrivateIpv4");function So(e){if(!e||e.length>4)return;let t=Number.parseInt(e,16);return Number.isNaN(t)||t<0||t>65535?void 0:t}n(So,"parseIpv6Word");function pf(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}n(pf,"formatIpv4FromWords");function lf(e){let t=e.slice(7),r=Xs(t);if(r!==void 0)return r.join(".");let[o,a,s]=t.split(":"),u=So(o),d=So(a);return s===void 0&&u!==void 0&&d!==void 0?pf(u,d):void 0}n(lf,"parseIpv6MappedIpv4");function mf(e){return So(e.split(":").find(Boolean))}n(mf,"readFirstIpv6Hextet");function hf(e){let t=ve(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let o=lf(t);return o===void 0||Qs(o)}let r=mf(t);return r===void 0?!1:(r&65024)===64512||(r&65472)===65152}n(hf,"isPrivateIpv6");function _o(e){let t=ve(e);return cf.has(t)||t.endsWith(".internal")||Qs(t)||hf(t)}n(_o,"isBlockedOutboundHostname");function ec(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw _e(`Unsupported outbound protocol: ${t.protocol}`);Ro(t,e);let r=Z(t);if(t.protocol==="http:"&&!r)throw _e("Configured outbound HTTP URLs must target loopback hosts.");let o=ve(t.hostname);if(!r&&_o(o))throw _e(`Blocked outbound host: ${o}`);return t}n(ec,"validateConfiguredOutboundUrl");function tc(e){let t=new URL(e),r=Z(t),o=r&&of();if(t.protocol!=="https:"&&!o)throw _e("Identity provider URLs must use https.");if(t.username||t.password||t.search||t.hash)throw _e("Identity provider URLs must not include credentials, query params, or fragments.");Ro(t,e);let a=ve(t.hostname);if(!r&&_o(a))throw _e(`Blocked identity provider host: ${a}`);return t}n(tc,"validateIdentityProviderUrl");function rc(e,t){let r=new URL(e),o=r.protocol==="http:"&&Z(r)&&af();if(r.protocol!=="https:"&&!o||r.pathname==="/"||r.username||r.password||r.search||r.hash)throw _e(`CIMD ${t} must be an HTTPS URL with a path and no credentials, query, or fragment.`);if(Ro(r,e),!o&&_o(r.hostname))throw _e(`CIMD ${t} points at a blocked host.`);return r}n(rc,"validateCimdUrl");function jr(e){return rc(e,"client_id")}n(jr,"validateCimdClientMetadataUrl");function nc(e){return rc(e,"jwks_uri")}n(nc,"validateCimdClientJwksUrl");function oc(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(oc,"mergeAbortSignals");async function ff(e){try{await e.cancel()}catch{}}n(ff,"cancelReader");async function Lr(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],a=0,s=await r.read();for(;!s.done;){let p=s.value;if(a+=p.byteLength,a>t.maxBytes)throw await ff(r),t.createLimitError();o.push(p),s=await r.read()}let u=new Uint8Array(a),d=0;for(let p of o)u.set(p,d),d+=p.byteLength;return u}n(Lr,"readBoundedByteStream");var gf=2,yf=1024*1024,wf=1e4,Sf=new Set([301,302,303,307,308]),Rf=["authorization","proxy-authorization","cookie","cookie2"];function bo(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(bo,"readRequestUrl");function bt(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(bt,"readRequestMethod");function _f(e,t,r){let o=e.headers.get("content-length");if(!o)return;let a=Number.parseInt(o,10);if(Number.isFinite(a)&&a>t)throw new w({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[y]:r}})}n(_f,"assertContentLengthWithinLimit");async function bf(e,t,r){return _f(e,t,r),Lr(e.body,{maxBytes:t,createLimitError:n(()=>new w({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[y]:r}}),"createLimitError")})}n(bf,"readBoundedResponseBody");function Cf(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(Cf,"responseFromBufferedBody");function xf(e,t){if(!Sf.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(xf,"resolveRedirectUrl");function ic(e,t){try{return t.validateUrl(e)}catch(r){throw new w({message:"Outbound URL was not allowed.",extensionMembers:{[y]:t.problemCode}},{cause:r})}}n(ic,"validateOutboundUrl");function Af(e,t){throw e instanceof w&&Ie(e.extensionMembers?.[y])?e:new w({message:"Outbound fetch failed.",extensionMembers:{[y]:t}},{cause:e})}n(Af,"normalizeFetchError");function ir(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[o,a]of Object.entries(t.extra))a!==void 0&&(r[o]=a);t.error!==void 0&&ie(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(ir,"logOutboundFailure");async function vf(e,t,r,o,a,s,u){let d=bt(r,o);try{return await t(r,o)}catch(p){let h=p instanceof DOMException&&p.name==="AbortError";ir(e,{event:h?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:d,host:we(s),error:p,extra:{abortReason:u()}}),Af(p,a)}}n(vf,"fetchWithNormalizedError");function If(e){if(e.redirects>=e.maxRedirects)throw new w({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[y]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new w({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[y]:e.problemCode}})}n(If,"assertRedirectAllowed");function kf(e,t){let r=new Headers(e);for(let o of Rf)r.delete(o);for(let o of t)r.delete(o);return r}n(kf,"stripCrossOriginHeaders");function Uf(e,t,r,o,a){let s={...e,method:t,redirect:"manual",signal:r};return o&&(s.headers=kf(e.headers,a)),s}n(Uf,"buildRedirectInit");function Tf(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(Tf,"buildInitialRequestInit");function Pf(e){let t=bt(e.currentInput,e.currentInit);If({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=ic(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),a=r.origin!==o.origin,s=r.toString();return{currentInput:s,currentUrl:s,currentInit:Uf(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(Pf,"followRedirect");async function Co(e,t,r){let o=r.problemCode??"invalid_request",a=r.maxRedirects??gf,s=r.maxResponseBytes??yf,u=r.timeoutMs??wf,d=r.fetchImpl??fetch,p=r.additionalCrossOriginStrippedHeaders??[],h=r.context,g=new AbortController,D=oc(g,t.signal),k=!1,ne=setTimeout(()=>{k=!0,g.abort()},u),Se=e,Me=Tf(e,t,g.signal),xe;try{xe=ic(bo(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(Ae){throw ir(h,{event:"outbound_url_blocked",problemCode:o,method:bt(e,t),host:we(bo(e)),error:Ae}),clearTimeout(ne),D?.(),Ae}let Ot=0;try{for(;;){let Ae=await vf(h,d,Se,Me,o,xe,()=>k?`timeout_after_${u}ms`:void 0),Y=xf(Ae,xe);if(Y!==void 0)try{let te=Pf({currentInput:Se,currentInit:Me,currentUrl:xe,redirectUrl:Y,redirects:Ot,maxRedirects:a,problemCode:o,validateUrl:r.validateUrl,signal:g.signal,additionalCrossOriginStrippedHeaders:p});Se=te.currentInput,Me=te.currentInit,xe=te.currentUrl,Ot=te.redirects;continue}catch(te){throw ir(h,{event:"outbound_redirect_blocked",problemCode:o,method:bt(Se,Me),host:we(xe),error:te,extra:{redirects:Ot,maxRedirects:a,redirectTargetHost:we(Y)}}),te}try{return Cf(Ae,await bf(Ae,s,o))}catch(te){throw ir(h,{event:"outbound_response_size_exceeded",problemCode:o,method:bt(Se,Me),host:we(xe),error:te,extra:{maxResponseBytes:s,status:Ae.status}}),te}}}finally{clearTimeout(ne),D?.()}}n(Co,"runSafeOutboundExchange");async function Br(e,t,r){let o=await Co(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(a){throw ir(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:bt(e,t),host:we(bo(e)),error:a,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new w({message:"Outbound JSON response could not be parsed.",extensionMembers:{[y]:r.problemCode??"invalid_request"}},{cause:a})}}n(Br,"runSafeOutboundJsonExchange");function ac(e,t={},r={}){return Co(e,t,{...r,validateUrl:ec})}n(ac,"fetchConfiguredOutbound");function sc(e,t={},r={}){return Br(e,t,{...r,validateUrl:tc})}n(sc,"fetchIdentityProviderJson");function cc(e,t={},r={}){return Br(e,t,{...r,validateUrl:jr})}n(cc,"fetchCimdClientMetadataJson");function uc(e,t={},r={}){return Br(e,t,{...r,validateUrl:nc})}n(uc,"fetchCimdClientJwksJson");z();import{errors as yc,jwtVerify as wc,SignJWT as Sc}from"jose";var ae="zuplo-mcp-gateway",le=ae,me="HS256";import{base64url as Of}from"jose";var zf=new TextEncoder,Ef="MCP gateway could not initialize secure key material.",Mf=32,dc=new Map,pc=new Map,qf;function Hf(){return qf??nt.instance.authPrivateKey}n(Hf,"readAuthPrivateKey");function lc(e){return new re(Ef,e===void 0?void 0:{cause:e})}n(lc,"createGeneratedKeyMaterialError");function mc(e,t){let r=Of.decode(t);if(r.byteLength!==Mf)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(mc,"decodeJwkKeyField");function Df(e){let t=Hf();if(!t)throw lc();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=mc("d",r.d);mc("x",r.x);let a=zf.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),s=new Uint8Array(a.byteLength+o.byteLength);return s.set(a),s.set(o,a.byteLength),s}catch(r){throw lc(r)}}n(Df,"decodeGeneratedKeyMaterial");function jf(e){let t=dc.get(e);return t||(t=Df(e),dc.set(e,t)),t}n(jf,"getMasterKeyMaterial");async function be(e){let t=pc.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(jf(e.keyMaterialPurpose));return pc.set(e.purpose,r),r}n(be,"readCachedDerivedKey");var Lf="SHA-256";var Bf="zuplo-mcp-gateway:",Nf=new TextEncoder,hc=new WeakMap;async function Le(e,t){let r=hc.get(e);r||(r=new Map,hc.set(e,r));let o=r.get(t);if(o)return o;let a=await Gf(e,t);return r.set(t,a),a}n(Le,"deriveGatewaySigningKey");async function Gf(e,t){let r=fc(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=Nf.encode(`${Bf}${t}`),s=await crypto.subtle.deriveBits({name:"HKDF",hash:Lf,salt:new Uint8Array,info:fc(a)},o,32*8);return new Uint8Array(s)}n(Gf,"hkdfExpand");function fc(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(fc,"copyToArrayBuffer");var Rc=15*60,$f=15*60,Zf=ja.extend({id:wt}),Ff=Zf.extend({exp:i.number().int().positive(),iat:i.number().int().positive().optional()}),_c=yt.extend({id:$t,purpose:i.literal("browser_connect")}),Kf=yt.extend({purpose:i.literal("browser_connect")}),Wf=_c.extend({exp:i.number().int().positive(),iat:i.number().int().positive().optional()}),bc=Rc*1e3;async function Cc(){return be({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Le(e,"oauth-state"),"derive")})}n(Cc,"getOAuthStateKey");async function xc(){return be({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Le(e,"browser-connect"),"derive")})}n(xc,"getBrowserConnectKey");async function Ac(e){let t=Math.floor(Date.now()/1e3)+Rc;return new Sc(e).setProtectedHeader({alg:me,typ:"JWT"}).setIssuer(ae).setAudience(le).setIssuedAt().setExpirationTime(t).sign(await Cc())}n(Ac,"signOAuthState");async function Nr(e){try{let{payload:t}=await wc(e,await Cc(),{algorithms:[me],issuer:ae,audience:le});return Ff.parse(t)}catch(t){throw t instanceof yc.JWTExpired?new w({message:"OAuth state has expired",extensionMembers:{[y]:"oauth_state_expired"}},{cause:t}):new w({message:"OAuth state could not be verified",extensionMembers:{[y]:"oauth_state_invalid"}},{cause:t})}}n(Nr,"verifyOAuthState");async function vc(e){let t=Math.floor(Date.now()/1e3)+$f,r=Kf.parse(e),o=_c.parse({...r,id:Fa()});return new Sc(o).setProtectedHeader({alg:me,typ:"JWT"}).setIssuer(ae).setAudience(le).setIssuedAt().setExpirationTime(t).sign(await xc())}n(vc,"signBrowserConnectTicket");async function Ic(e){try{let{payload:t}=await wc(e,await xc(),{algorithms:[me],issuer:ae,audience:le});return Wf.parse(t)}catch(t){throw t instanceof yc.JWTExpired?new w({message:"Browser connect ticket has expired",extensionMembers:{[y]:"oauth_state_expired"}},{cause:t}):new w({message:"Browser connect ticket could not be verified",extensionMembers:{[y]:"oauth_state_invalid"}},{cause:t})}}n(Ic,"verifyBrowserConnectTicket");async function kc(e){if((await A().consumeBrowserConnectTicket({id:e.id,expiresAt:x(new Date(e.exp*1e3)),now:x(new Date)})).kind==="consumed")throw new w({message:"Browser connect ticket has already been used",extensionMembers:{[y]:"oauth_state_reused"}})}n(kc,"consumeBrowserConnectTicket");function Jf(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(Jf,"buildConnectRequiredMessage");async function Vf(e){let t=P(e.requestUrl),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 vc({...Gt(e),purpose:"browser_connect"})),r.toString()}n(Vf,"buildGatewayBrowserTicketUrl");function Yf(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}n(Yf,"buildGatewayConnectPath");async function xo(e){return Vf({...e,path:Yf(e.upstreamServerId),redirect:!0})}n(xo,"buildGatewayConnectUrl");async function Gr(e){let t={requestUrl:e.requestUrl,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 xo(t),message:Jf(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(Gr,"buildRedirectConnectRequiredResponse");function Uc(e){return Xf({...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(Uc,"buildAdminConnectRequiredResponse");function Xf(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(Xf,"buildAdminSetupRequiredResponse");z();function Ao(e){return`Zuplo MCP Gateway - ${e}`}n(Ao,"buildGatewayOAuthClientName");function Tc(e,t){let r=new URL(e,P(t));return Z(r)&&ve(r.hostname)!=="localhost"&&(r.hostname="localhost"),r.toString()}n(Tc,"buildGatewayOAuthRedirectUri");function vo(e){let t=new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin);return t.searchParams.set("authProfileId",e.authProfileId),t.toString()}n(vo,"buildOAuthClientMetadataDocumentUrl");function Pc(e){return P(e)}n(Pc,"requireOAuthClientMetadataOrigin");function Oc(e,t,r){let o=je(t),a=Je(t,r);return{client_id:vo({origin:e,upstreamServerId:t,authProfileId:r}),client_name:Ao(o.displayName),client_uri:new URL("/",e).toString(),redirect_uris:[new URL(a.redirectPath,e).toString()],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",token_endpoint_auth_method:"none"}}n(Oc,"buildOAuthClientMetadataDocument");z();import{base64url as Be}from"jose";var Qf="SHA-256",xt="AES-GCM",eg=12,ko="zuplo-secret",Uo=1,zc="generated:auth_private_key:token-encryption",tg=i.object({version:i.literal(Uo),keyId:i.literal(zc),algorithm:i.literal(xt),iv:i.string().min(1),ciphertext:i.string().min(1)}).strict();function Ct(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(Ct,"copyToArrayBuffer");async function Io(){return be({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(Qf,Ct(e));return crypto.subtle.importKey("raw",t,{name:xt},!1,["encrypt","decrypt"])},"derive")})}n(Io,"getEncryptionKey");function Ec(e){return Ct(new TextEncoder().encode(`${ko}:v${e.version}:${e.keyId}`))}n(Ec,"getAssociatedData");function rg(e){return`${ko}:v${e.version}:${Be.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(rg,"encodeEnvelope");function ng(e){let t=`${ko}:v${Uo}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(Be.decode(r));return tg.parse(JSON.parse(o))}n(ng,"decodeEnvelope");async function $r(e){let t=await Io(),r=crypto.getRandomValues(new Uint8Array(eg)),o={version:Uo,keyId:zc},a=await crypto.subtle.encrypt({name:xt,iv:r,additionalData:Ec(o)},t,new TextEncoder().encode(e));return rg({...o,algorithm:xt,iv:Be.encode(r),ciphertext:Be.encode(new Uint8Array(a))})}n($r,"encryptSecret");async function ar(e){let t=ng(e);if(t){let u=await Io(),d=await crypto.subtle.decrypt({name:xt,iv:Ct(Be.decode(t.iv)),additionalData:Ec(t)},u,Ct(Be.decode(t.ciphertext)));return new TextDecoder().decode(d)}let[r,o]=e.split(".");if(!r||!o)throw new re("Encrypted payload is malformed");let a=await Io(),s=await crypto.subtle.decrypt({name:xt,iv:Ct(Be.decode(r))},a,Ct(Be.decode(o)));return new TextDecoder().decode(s)}n(ar,"decryptSecret");var og=i.union([Ft,lo]),ig=i.object({authorizationServerUrl:i.url(),resourceMetadataUrl:i.url().optional(),resourceMetadata:Hr.optional(),authorizationServerMetadata:i.union([Zt,Dr]).optional()}).passthrough(),ag="Bearer",sg="__zuplo_refresh_only_upstream_access_token__";function cg(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(cg,"splitScopes");function ug(e){return Ar.parse(e)}n(ug,"parsePkceCodeVerifier");function dg(e){if(typeof e.expires_in=="number")return x(new Date(Date.now()+e.expires_in*1e3))}n(dg,"readTokenExpiry");async function Mc(e){if(e!==void 0)return $r(JSON.stringify(e))}n(Mc,"encryptJson");async function qc(e,t){if(!e)return;let r=await ar(e);try{return t.parse(JSON.parse(r))}catch(o){throw new w({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[y]:"oauth_state_invalid"}},{cause:o})}}n(qc,"decryptJson");function pg(e){if(e===void 0)return;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(pg,"toOAuthDiscoveryState");function lg(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(lg,"clientInformationAllowsRedirectUri");function mg(e,t,r){let o=je(e),a=Je(e,t),s;return a.scopes.length>0&&(s=a.scopes.join(a.scopeDelimiter)),{client_name:Ao(o.displayName),client_uri:new URL("/",new URL(r).origin).toString(),redirect_uris:[r],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",scope:s,token_endpoint_auth_method:"none"}}n(mg,"buildOAuthClientMetadata");function hg(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new _(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return Ft.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(hg,"buildManualOAuthClientInformation");function fg(e,t,r){let o=vo({origin:new URL(r).origin,upstreamServerId:e,authProfileId:t});return yo(o)?o:void 0}n(fg,"buildClientMetadataUrl");function Hc(e){for(let t of e)if(t!==void 0)return t}n(Hc,"firstDefined");function gg(e){let t=Je(e.target.upstreamServerId,e.target.authProfileId),r=mg(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);if(t.clientRegistration.mode==="manual")return{clientMetadata:r,configuredClientInformation:hg({clientMetadata:r,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let o=fg(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);return o===void 0?{clientMetadata:r}:{clientMetadata:r,clientMetadataUrl:o}}n(gg,"buildInitialOAuthClientSetup");function yg(e,t){if(t===void 0)return Hc([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(yg,"readEncryptedClientInformation");function wg(e){return Hc([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}n(wg,"readEncryptedDiscoveryState");var et=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredClientInformation;authorizationUrlValue;connection;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;constructor(t){let r=gg({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.clientMetadataValue=r.clientMetadata,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=yg(t,this.configuredClientInformation),this.encryptedDiscoveryState=wg(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return this.clientMetadataValue}async state(){let t=await this.createPendingState();return Ac({id:t.id,...Gt({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,this.encryptedClientInformation=await Mc(t),await this.syncPendingState(!1))}async discoveryState(){return this.loadPersistedDiscoveryState()}async saveDiscoveryState(t){this.cachedDiscoveryState=t,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await Mc(t),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=_t.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,a=r.refresh_token?await $r(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:_t.parse({...r,refresh_token:await ar(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let s={id:this.connection?.id??$a(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await $r(r.access_token),encryptedRefreshToken:a,scopes:cg(r.scope??this.clientMetadataValue.scope),expiresAt:dg(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await A().upsertUpstreamConnection(s)}async redirectToAuthorization(t){this.authorizationUrlValue=t.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:ug(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new w({message:"OAuth code verifier is missing",extensionMembers:{[y]:"oauth_state_invalid"}});return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",o=t==="all"||t==="client",a=t==="all"||t==="discovery",s=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),a&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(s),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:Za(),...Gt({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:x(new Date(Date.now()+bc)),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 A().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 qc(this.encryptedClientInformation,og)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&!lg(t,this.redirectUriValue)){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1);return}return this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async loadPersistedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;try{this.cachedDiscoveryState=pg(await qc(this.encryptedDiscoveryState,ig))}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1)}return this.discoveryStateLoaded=!0,this.cachedDiscoveryState}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 ar(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await ar(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=_t.parse({access_token:t??sg,token_type:ag,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 A().upsertUpstreamConnection(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var Sg=3e4,Rg=256*1024,_g=2;function bg(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(bg,"hasUsableAccessToken");var Cg="does not support dynamic client registration";function xg(e){return e instanceof Error&&e.message.includes(Cg)}n(xg,"isDynamicClientRegistrationUnsupported");function Ag(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(Ag,"readOAuthFetchRequest");function vg(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(vg,"responseLooksJson");function Dc(e){return async(t,r)=>{let o=Ag(t),a=await ac(t,r,{maxRedirects:_g,maxResponseBytes:Rg,problemCode:"upstream_token_exchange_failed",timeoutMs:Sg}),s=await a.clone().text();if(!vg(a,s))return a;try{JSON.parse(s)}catch(u){throw new w({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[y]:"upstream_token_exchange_failed"}},{cause:u})}return a}}n(Dc,"createUpstreamOAuthFetch");async function jc(e,t){try{return await go(e,{serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Dc(t.upstreamServerId)})}catch(r){throw xg(r)?new w({message:`The authorization server for ${t.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register a client for the gateway manually before retrying.`,extensionMembers:{[y]:"upstream_client_registration_required"}},{cause:r}):r}}n(jc,"runUpstreamOAuth");async function Ig(e,t){return go(e,{serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Dc(t.upstreamServerId)})}n(Ig,"exchangeUpstreamAuthorizationCode");async function Lc(e,t){let r=await jc(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new w({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[y]:"upstream_token_exchange_failed"}}):new w({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[y]:"upstream_token_exchange_failed"}})}n(Lc,"requireUpstreamAuthorizationRedirect");async function Bc(e){if(!e.forceRefresh&&bg(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await jc(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl});if(t==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(t!=="REDIRECT")throw new w({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`,extensionMembers:{[y]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new w({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[y]:"upstream_token_exchange_failed"}});return{kind:"connect_required",payload:await Og({requestUrl:e.target.request.url,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(Bc,"authorizeUpstreamOAuthSession");async function kg(e){let t=await Nr(e.stateToken),r=await A().consumeUpstreamOAuthState({id:t.id,now:x(new Date)}),o=Ug(r);return Tg({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),Pg(o),o}n(kg,"consumeStoredCallbackState");function Ug(e){switch(e.kind){case"consumed":throw new w({message:"OAuth state has already been used",extensionMembers:{[y]:"oauth_state_reused"}});case"missing":throw new w({message:"OAuth state is missing or expired",extensionMembers:{[y]:"oauth_state_expired"}});case"available":return e.record}}n(Ug,"readConsumedCallbackState");function Tg(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 w({message:"OAuth callback did not match the initiating request",extensionMembers:{[y]:"oauth_callback_mismatch"}})}n(Tg,"assertStoredCallbackStateMatches");function Pg(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new w({message:"OAuth state has expired",extensionMembers:{[y]:"oauth_state_expired"}})}n(Pg,"assertStoredCallbackStateFresh");async function Og(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),Uc(r)}let t={requestUrl:e.requestUrl,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),Gr(t)}n(Og,"buildOAuthConnectRequiredResponse");async function Nc(e){let t=await kg({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=zr(t),[o]=await A().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),a={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};o!==void 0&&(a.connection=o);let s=new et(a),u=await Ig(s,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(u==="AUTHORIZED")return t;throw u!=="REDIRECT"?new w({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${u}`,extensionMembers:{[y]:"upstream_token_exchange_failed"}}):new w({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[y]:"upstream_token_exchange_failed"}})}n(Nc,"finishUpstreamOAuthCallback");async function Gc(e){let t=je(e.upstreamServerId),r=Je(e.upstreamServerId,e.authProfileId),o=Tc(r.redirectPath,e.request.url),a="preloadedConnection"in e?e.preloadedConnection:(await A().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:a,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}},redirectUri:o,returnOrigin:P(e.request.url)}}}n(Gc,"prepareUpstreamOAuthRequest");async function $c(e){let t=await Gc(e),r=new et({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Lc(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n($c,"startUpstreamConnect");async function Zc(e){let t=await Gc(e),r=new et({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return Bc({target:e,provider:r,connection:t.connection,forceRefresh:e.forceRefresh,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Zc,"authorizeUpstreamRequest");async function To(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return Zc({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,forceRefresh:e.forceRefresh})}let r=t;throw new re(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(To,"resolveUpstreamCredentialForRoute");async function Fc(e){let t,r={request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,operationId:e.connectRequest.operationId,...e.connectRequest.returnTo===void 0?{}:{returnTo:e.connectRequest.returnTo}},o=Re(e.connectRequest.authMode);switch(o.connectSupport){case"oauth_authorization":t=await $c(r);break;case"none":throw new re(o.connectUnsupportedDetail??`Upstream server ${e.connectRequest.upstreamServerId} does not support browser connection flows.`)}return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}n(Fc,"startUpstreamConnectForRequest");async function Kc(e){let r=(await Nr(e.callbackRequest.state)).authProfileId,o=co({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r});if(Re(o.mode).callbackSupport!=="authorization_code")throw new re(`Upstream server ${e.callbackRequest.upstreamServerId} does not support OAuth callbacks.`);return Nc({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:je(e.callbackRequest.upstreamServerId)})}n(Kc,"finishUpstreamCallbackForRequest");function zg(e){let t=Re(e.connection.authMode);return{upstreamServerId:e.connection.upstreamServerId,operationId:e.operationId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:t.ownerMode}}n(zg,"buildRouteAuthBaseFromConnection");function Jc(e){let t=Re(e.connection.authMode);return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:mt(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:t.ownerMode}}n(Jc,"buildRouteAuthBaseFromPolicyOptions");function Vc(e,t){let o=ye().byOperationId.get(t);if(!o)throw new _(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new _(`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 _(`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 zg({connection:o.connection,operationId:t})}n(Vc,"resolveRouteAuthBase");function Wc(e,t){switch(e){case"user":return gt(t.subjectId);case"shared":return Or()}}n(Wc,"buildOwnerForPrincipal");function Zr(e,t){switch(e.ownerMode){case"shared":return{...e,owner:Wc(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"user":return{...e,owner:Wc(e.ownerMode,t),initiatedBySubjectId:t.subjectId}}}n(Zr,"resolveRouteAuthForPrincipal");var Eg=ke.InvalidRequest,Mg=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function qg(e){let t=e.route.raw();return G.parse(t?.operationId)}n(qg,"readOperationId");async function Hg(e,t,r,o){let a=await To({request:e,routeAuth:t});if(a.kind==="connect_required")return o.log.info({event:"mcp_upstream_connect_required",upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId},"MCP upstream proxy: upstream connection required"),{kind:"connect_required",payload:a.payload};let s=a.credential;switch(s.type){case"none":return{kind:"headers",headers:[]};case"bearer_token":return{kind:"headers",headers:[["authorization",`Bearer ${s.token}`]]};case"headers":return{kind:"headers",headers:Object.entries(s.headers)};case"mcp_oauth_provider":{let u=await s.provider.tokens();return u?{kind:"headers",headers:[["authorization",`${u.token_type??"Bearer"} ${u.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(Hg,"buildCredentialHeaders");var Dg=new Set(["authorization","cookie","cookie2"]);function jg(e,t){let r=new Headers(e.headers);for(let o of Dg)r.delete(o);for(let[o,a]of t)r.set(o,a);return new lr(e,{headers:r})}n(jg,"applyUpstreamHeaders");function Lg(e){let t=new Headers(e.headers);for(let r of Mg)t.delete(r);return t}n(Lg,"buildProxyHeaders");async function Bg(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(Bg,"readRetryBody");function Yc(e,t){let r=t.authUrl===void 0?void 0:Ma({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(Tr({id:za(e),error:{code:r?.code??Eg,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(Yc,"connectRequiredJsonRpcResponse");async function Ng(e){let t=await To({request:e.request,routeAuth:e.routeAuth,forceRefresh:!0});if(t.kind==="connect_required")return{kind:"connect_required",payload:t.payload};let r=new Headers(e.headers),o=t.credential;switch(o.type){case"none":return r.delete("authorization"),{kind:"headers",headers:r};case"bearer_token":return r.set("authorization",`Bearer ${o.token}`),{kind:"headers",headers:r};case"headers":for(let[a,s]of Object.entries(o.headers))r.set(a,s);return{kind:"headers",headers:r};case"mcp_oauth_provider":{let a=await o.provider.tokens();return a?(r.set("authorization",`${a.token_type??"Bearer"} ${a.access_token}`),{kind:"headers",headers:r}):(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(Ng,"applyRefreshedCredentialHeaders");function Gg(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await Ng({request:e.request,context:e.context,headers:Lg(r),routeAuth:e.routeAuth});if(o.kind==="connect_required")return Yc(e.requestBody,o.payload);if(o.kind==="response")return o.response;let a=Oi({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return oi.fetch(a.url,a.init)})}n(Gg,"installUpstreamAuthRetryHook");async function Po(e,t,r){let o=qg(t),a=await Bg(e),s=Jc({connection:r,operationId:o}),u=Zr(s,Pa(e,t)),d=await Hg(e,u,r,t);if(!(d instanceof Response)&&d.kind==="connect_required")return Yc(a,d.payload);if(d instanceof Response)return d;let p=jg(e,d.headers);return Gg({request:p,context:t,requestBody:a,routeAuth:u}),p}n(Po,"mcpTokenExchangePolicy");var Oo=class extends it{static{n(this,"McpTokenExchangeInboundPolicy")}constructor(t,r){let o=Rr(t,r);super(o,r)}async handler(t,r){return ot("policy.inbound.mcp-token-exchange"),Po(t,r,this.options)}};z();var Xc=Symbol("Html");function $g(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n($g,"escapeHtml");function Zg(e){return e===null||typeof e!="object"?!1:e[Xc]===!0}n(Zg,"isHtml");function Qc(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Qc).join(""):Zg(e)?e.value:$g(String(e))}n(Qc,"renderValue");function ze(e){return{[Xc]:!0,value:e}}n(ze,"trustedHtml");var tt=ze("");function L(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=Qc(t[o]),r+=e[o+1]??"";return ze(r)}n(L,"html");function At(e){return e.value}n(At,"renderHtml");function eu(e){return L`<p data-gateway-error-code="${e.code}">${e.detail}</p>${e.guidance} ${e.action}`}n(eu,"renderBrowserErrorPage");var vt=ze('*,: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 It(e){return L`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" href="${e.iconHref}" /><style>
25
+ import{$ as xn,A as pn,Aa as A,B as mn,Ba as W,C as fn,Ca as C,D as hn,Da as jn,E as gn,Ea as Ha,F as j,Fa as Nn,G as yn,Ga as Gn,H as _,Ha as $n,I as F,Ia as Zn,J as I,K as wn,Ka as Fn,L as K,La as Kn,Ma as lt,N as _n,O as ce,P as g,Q as Rn,R as bn,S as Cn,T as at,U as ee,V as Mt,W as zt,X as Sn,Y as vn,Z as Dt,_ as Ht,a as Vr,aa as P,b as se,ba as In,c as Yr,ca as An,d as D,da as Un,e as Xr,ea as kn,f as Da,fa as Bt,g as Qr,ga as Pn,h as en,ha as Lt,i as tn,ia as jt,j as w,ja as st,k as rn,ka as ct,l as nn,la as Tn,m as H,ma as On,n as on,na as dt,o as an,oa as En,p as rt,pa as Nt,q as sn,qa as qn,r as qt,ra as Te,s as nt,sa as ut,t as ot,ta as Mn,u as Pe,ua as zn,v as cn,va as Dn,w as dn,wa as Hn,x as un,xa as Bn,y as it,ya as Ln,z as ln,za as R}from"../chunk-FYGTTP3G.js";import{B as Nr,J as Gr,L as u,M as $r,N as Et,O as Z,Q as Zr,S as f,T as Q,U as tt,_ as Fr,a as Qe,ca as Kr,da as Wr,ea as d,fa as z,j as ae,k as Br,m as Lr,ma as Jr,q as jr,s as et}from"../chunk-2GVPMQ7M.js";import"../chunk-JRXZBVXH.js";import{a as x}from"../chunk-4SACVMDH.js";import{$ as E,a as n,aa as y,ba as k,ca as Hr,da as Xe}from"../chunk-ZIKV2LUM.js";z();function Ba(e){let t=ot.safeParse(e);return t.success?t.data.id:void 0}n(Ba,"parseJsonRpcRequestId");function Wn(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Ba(t)}catch{return}}n(Wn,"readJsonRpcRequestIdFromBody");function pt(e){return cn.parse({jsonrpc:nt,...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(pt,"jsonRpcErrorResponse");function Jn(e){return new un([dn.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Jn,"urlElicitationRequiredError");var mt=d.array(d.string()),La=d.object({tools:mt.optional(),prompts:mt.optional(),resources:mt.optional(),resourceTemplates:mt.optional()}).strict(),$t=[{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 ja(e,t){return Xr(La,e,`MCP capability filter policy "${t}"`)}n(ja,"parseMcpCapabilityFilterOptions");function B(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(B,"isRecord");function Na(e,t){if(!B(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(Na,"readParamString");function Zt(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(Zt,"readRequestId");function Xn(e){return e===void 0?void 0:JSON.stringify(e)}n(Xn,"requestIdKey");function Ga(e){let t={};for(let r of $t){let o=e[r.option];o!==void 0&&(t[r.option]=new Set(o))}return t}n(Ga,"buildAllowSets");function Ft(e){return $t.find(t=>t.listMethod===e)}n(Ft,"findListRule");function $a(e){return e.requests.some(t=>{if(!B(t))return!1;let r=Ft(t.method);return r!==void 0&&e.allowSets[r.option]!==void 0})}n($a,"shouldFilterListResponses");function Za(e){for(let t of $t){let r=e.allowSets[t.option];if(r!==void 0)for(let o of t.directMethods){if(e.request.method!==o.method)continue;let i=Na(e.request.params,o.paramProperty);if(i!==void 0&&!r.has(i))return{id:Zt(e.request)}}}}n(Za,"findDisallowedDirectAccess");function Fa(e){return Response.json(pt({id:e,error:{code:Pe.MethodNotFound,message:"Method not found"}}))}n(Fa,"methodNotFoundResponse");function Vn(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.filter(a=>{if(!B(a))return!1;let s=a[t.itemProperty];return typeof s=="string"&&r.has(s)})}}}n(Vn,"filterItems");function Ka(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!B(r))continue;let o=Ft(r.method),i=Zt(r),a=Xn(i);o!==void 0&&a!==void 0&&t.set(a,o)}return t}n(Ka,"buildListRulesByResponseId");function Wa(e){if(Array.isArray(e.responseBody)){let o=Ka(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(i=>{if(!B(i)||"error"in i)return i;let a=Xn(Zt(i)),s=a===void 0?void 0:o.get(a),c=s===void 0?void 0:e.allowSets[s.option];return s===void 0||c===void 0?i:Vn(i,s,c)})}if(!B(e.requestBody)||!B(e.responseBody)||"error"in e.responseBody)return e.responseBody;let t=Ft(e.requestBody.method),r=t===void 0?void 0:e.allowSets[t.option];return t===void 0||r===void 0?e.responseBody:Vn(e.responseBody,t,r)}n(Wa,"filterJsonRpcResponse");async function Yn(e){return e.clone().json()}n(Yn,"readJson");function Ja(e){return e.headers.get("content-type")?.includes("json")??!1}n(Ja,"isJsonResponse");var Gt=class extends et{static{n(this,"McpCapabilityFilterInboundPolicy")}#e;constructor(t,r){let o=ja(t,r);super(o,r),this.#e=Ga(o)}async handler(t,r){Qe("policy.inbound.mcp-capability-filter");let o;try{o=await Yn(t)}catch{return t}let i=Array.isArray(o)?o:[o];for(let a of i){if(!B(a))continue;let s=Za({request:a,allowSets:this.#e});if(s!==void 0)return Fa(s.id)}return $a({requests:i,allowSets:this.#e})&&r.addResponseSendingHook(async a=>{if(!Ja(a))return a;let s;try{s=await Yn(a)}catch{return a}let c=Wa({requestBody:o,responseBody:s,allowSets:this.#e});if(c===s)return a;let l=new Headers(a.headers);return l.delete("content-length"),new Response(JSON.stringify(c),{status:a.status,statusText:a.statusText,headers:l})}),t}};function te(e){let t=j().connectionsById.get(e);if(!t)throw new k(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,...t.description===void 0?{}:{description:t.description},...t.serverInfo===void 0?{}:{serverInfo:t.serverInfo},transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}n(te,"getUpstreamServerConfig");function Va(e){let t=j().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new k(`Unknown auth profile "${String(e.authProfileId)}" for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares a matching auth mode for that upstream connection.`);return t.authProfileId}n(Va,"resolveUpstreamAuthProfileId");function Kt(e){Va(e);let t=j().connectionsById.get(e.upstreamServerId);if(!t)throw new k(`Auth profile could not be resolved for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares the upstream connection before this handler runs.`);return t.authConfig}n(Kt,"getUpstreamAuthConfig");function de(e,t){let r=Kt({upstreamServerId:e,authProfileId:t});if(!pn(r))throw new k(`Upstream server "${e}" does not use upstream OAuth. Select an auth mode that supports the requested upstream connect flow or remove the upstream OAuth route for this server.`);return r.oauth}n(de,"requireUpstreamOAuthConfig");var Ya={"shared-oauth":{authMode:"shared-oauth",ownerMode:"shared",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"},"user-oauth":{authMode:"user-oauth",ownerMode:"user",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"}};function N(e){return Ya[e]}n(N,"describeUpstreamAuthMode");function ft(e){return N(e).ownerMode}n(ft,"resolveOwnerModeForUpstreamAuthMode");var Wt;Wt=globalThis.crypto;async function Xa(e){return(await Wt).getRandomValues(new Uint8Array(e))}n(Xa,"getRandomValues");async function Qa(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await Xa(e-o.length);for(let a of i)a<r&&(o+=t[a%t.length])}return o}n(Qa,"random");async function es(e){return await Qa(e)}n(es,"generateVerifier");async function ts(e){let t=await(await Wt).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(ts,"generateChallenge");async function Jt(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await es(e),r=await ts(t);return{code_verifier:t,code_challenge:r}}n(Jt,"pkceChallenge");z();var U=$r().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Kr.custom,message:"URL must be parseable",fatal:!0}),Gr}).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"}),ht=tt({resource:u().url(),authorization_servers:f(U).optional(),jwks_uri:u().url().optional(),scopes_supported:f(u()).optional(),bearer_methods_supported:f(u()).optional(),resource_signing_alg_values_supported:f(u()).optional(),resource_name:u().optional(),resource_documentation:u().optional(),resource_policy_uri:u().url().optional(),resource_tos_uri:u().url().optional(),tls_client_certificate_bound_access_tokens:Z().optional(),authorization_details_types_supported:f(u()).optional(),dpop_signing_alg_values_supported:f(u()).optional(),dpop_bound_access_tokens_required:Z().optional()}),Oe=tt({issuer:u(),authorization_endpoint:U,token_endpoint:U,registration_endpoint:U.optional(),scopes_supported:f(u()).optional(),response_types_supported:f(u()),response_modes_supported:f(u()).optional(),grant_types_supported:f(u()).optional(),token_endpoint_auth_methods_supported:f(u()).optional(),token_endpoint_auth_signing_alg_values_supported:f(u()).optional(),service_documentation:U.optional(),revocation_endpoint:U.optional(),revocation_endpoint_auth_methods_supported:f(u()).optional(),revocation_endpoint_auth_signing_alg_values_supported:f(u()).optional(),introspection_endpoint:u().optional(),introspection_endpoint_auth_methods_supported:f(u()).optional(),introspection_endpoint_auth_signing_alg_values_supported:f(u()).optional(),code_challenge_methods_supported:f(u()).optional(),client_id_metadata_document_supported:Z().optional()}),rs=tt({issuer:u(),authorization_endpoint:U,token_endpoint:U,userinfo_endpoint:U.optional(),jwks_uri:U,registration_endpoint:U.optional(),scopes_supported:f(u()).optional(),response_types_supported:f(u()),response_modes_supported:f(u()).optional(),grant_types_supported:f(u()).optional(),acr_values_supported:f(u()).optional(),subject_types_supported:f(u()),id_token_signing_alg_values_supported:f(u()),id_token_encryption_alg_values_supported:f(u()).optional(),id_token_encryption_enc_values_supported:f(u()).optional(),userinfo_signing_alg_values_supported:f(u()).optional(),userinfo_encryption_alg_values_supported:f(u()).optional(),userinfo_encryption_enc_values_supported:f(u()).optional(),request_object_signing_alg_values_supported:f(u()).optional(),request_object_encryption_alg_values_supported:f(u()).optional(),request_object_encryption_enc_values_supported:f(u()).optional(),token_endpoint_auth_methods_supported:f(u()).optional(),token_endpoint_auth_signing_alg_values_supported:f(u()).optional(),display_values_supported:f(u()).optional(),claim_types_supported:f(u()).optional(),claims_supported:f(u()).optional(),service_documentation:u().optional(),claims_locales_supported:f(u()).optional(),ui_locales_supported:f(u()).optional(),claims_parameter_supported:Z().optional(),request_parameter_supported:Z().optional(),request_uri_parameter_supported:Z().optional(),require_request_uri_registration:Z().optional(),op_policy_uri:U.optional(),op_tos_uri:U.optional(),client_id_metadata_document_supported:Z().optional()}),gt=Q({...rs.shape,...Oe.pick({code_challenge_methods_supported:!0}).shape}),ye=Q({access_token:u(),id_token:u().optional(),token_type:u(),expires_in:Wr.number().optional(),scope:u().optional(),refresh_token:u().optional()}).strip(),eo=Q({error:u(),error_description:u().optional(),error_uri:u().optional()}),Qn=U.optional().or(Fr("").transform(()=>{})),ns=Q({redirect_uris:f(U),token_endpoint_auth_method:u().optional(),grant_types:f(u()).optional(),response_types:f(u()).optional(),client_name:u().optional(),client_uri:U.optional(),logo_uri:Qn,scope:u().optional(),contacts:f(u()).optional(),tos_uri:Qn,policy_uri:u().optional(),jwks_uri:U.optional(),jwks:Zr().optional(),software_id:u().optional(),software_version:u().optional(),software_statement:u().optional()}).strip(),Vt=Q({client_id:u(),client_secret:u().optional(),client_id_issued_at:Et().optional(),client_secret_expires_at:Et().optional()}).strip(),Ee=ns.merge(Vt),Zl=Q({error:u(),error_description:u().optional()}).strip(),Fl=Q({token:u(),token_type_hint:u().optional()}).strip();function to(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(to,"resourceUrlFromServerUrl");function ro({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(ro,"checkResourceAllowed");var S=class extends Error{static{n(this,"OAuthError")}constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},qe=class extends S{static{n(this,"InvalidRequestError")}};qe.errorCode="invalid_request";var ue=class extends S{static{n(this,"InvalidClientError")}};ue.errorCode="invalid_client";var le=class extends S{static{n(this,"InvalidGrantError")}};le.errorCode="invalid_grant";var pe=class extends S{static{n(this,"UnauthorizedClientError")}};pe.errorCode="unauthorized_client";var Me=class extends S{static{n(this,"UnsupportedGrantTypeError")}};Me.errorCode="unsupported_grant_type";var ze=class extends S{static{n(this,"InvalidScopeError")}};ze.errorCode="invalid_scope";var De=class extends S{static{n(this,"AccessDeniedError")}};De.errorCode="access_denied";var J=class extends S{static{n(this,"ServerError")}};J.errorCode="server_error";var He=class extends S{static{n(this,"TemporarilyUnavailableError")}};He.errorCode="temporarily_unavailable";var Be=class extends S{static{n(this,"UnsupportedResponseTypeError")}};Be.errorCode="unsupported_response_type";var Le=class extends S{static{n(this,"UnsupportedTokenTypeError")}};Le.errorCode="unsupported_token_type";var je=class extends S{static{n(this,"InvalidTokenError")}};je.errorCode="invalid_token";var Ne=class extends S{static{n(this,"MethodNotAllowedError")}};Ne.errorCode="method_not_allowed";var Ge=class extends S{static{n(this,"TooManyRequestsError")}};Ge.errorCode="too_many_requests";var me=class extends S{static{n(this,"InvalidClientMetadataError")}};me.errorCode="invalid_client_metadata";var $e=class extends S{static{n(this,"InsufficientScopeError")}};$e.errorCode="insufficient_scope";var Ze=class extends S{static{n(this,"InvalidTargetError")}};Ze.errorCode="invalid_target";var no={[qe.errorCode]:qe,[ue.errorCode]:ue,[le.errorCode]:le,[pe.errorCode]:pe,[Me.errorCode]:Me,[ze.errorCode]:ze,[De.errorCode]:De,[J.errorCode]:J,[He.errorCode]:He,[Be.errorCode]:Be,[Le.errorCode]:Le,[je.errorCode]:je,[Ne.errorCode]:Ne,[Ge.errorCode]:Ge,[me.errorCode]:me,[$e.errorCode]:$e,[Ze.errorCode]:Ze};function os(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(os,"isClientAuthMethod");var Yt="code",Xt="S256";function is(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&os(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(is,"selectClientAuthMethod");function as(e,t,r,o){let{client_id:i,client_secret:a}=t;switch(e){case"client_secret_basic":ss(i,a,r);return;case"client_secret_post":cs(i,a,o);return;case"none":ds(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(as,"applyClientAuthentication");function ss(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(ss,"applyBasicAuth");function cs(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(cs,"applyPostAuth");function ds(e,t){t.set("client_id",e)}n(ds,"applyPublicAuth");async function io(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=eo.parse(JSON.parse(r)),{error:i,error_description:a,error_uri:s}=o,c=no[i]||J;return new c(a||"",s)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new J(i)}}n(io,"parseErrorResponse");async function er(e,t){try{return await Qt(e,t)}catch(r){if(r instanceof ue||r instanceof pe)return await e.invalidateCredentials?.("all"),await Qt(e,t);if(r instanceof le)return await e.invalidateCredentials?.("tokens"),await Qt(e,t);throw r}}n(er,"auth");async function Qt(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:i,fetchFn:a}){let s=await e.discoveryState?.(),c,l,h,m=i;if(!m&&s?.resourceMetadataUrl&&(m=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(l=s.authorizationServerUrl,c=s.resourceMetadata,h=s.authorizationServerMetadata??await so(l,{fetchFn:a}),!c)try{c=await ao(t,{resourceMetadataUrl:m},a)}catch{}(h!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:m?.toString(),resourceMetadata:c,authorizationServerMetadata:h})}else{let O=await hs(t,{resourceMetadataUrl:m,fetchFn:a});l=O.authorizationServerUrl,h=O.authorizationServerMetadata,c=O.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:m?.toString(),resourceMetadata:c,authorizationServerMetadata:h})}let v=await us(t,e,c),L=o||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,X=await Promise.resolve(e.clientInformation());if(!X){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let O=h?.client_id_metadata_document_supported===!0,ke=e.clientMetadataUrl;if(ke&&!tr(ke))throw new me(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ke}`);if(O&&ke)X={client_id:ke},await e.saveClientInformation?.(X);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Dr=await Rs(l,{metadata:h,clientMetadata:e.clientMetadata,scope:L,fetchFn:a});await e.saveClientInformation(Dr),X=Dr}}let Ye=!e.redirectUrl;if(r!==void 0||Ye){let O=await _s(e,l,{metadata:h,resource:v,authorizationCode:r,fetchFn:a});return await e.saveTokens(O),"AUTHORIZED"}let zr=await e.tokens();if(zr?.refresh_token)try{let O=await ws(l,{metadata:h,clientInformation:X,refreshToken:zr.refresh_token,resource:v,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(O),"AUTHORIZED"}catch(O){if(!(!(O instanceof S)||O instanceof J))throw O}let qa=e.state?await e.state():void 0,{authorizationUrl:Ma,codeVerifier:za}=await gs(l,{metadata:h,clientInformation:X,state:qa,redirectUrl:e.redirectUrl,scope:L,resource:v});return await e.saveCodeVerifier(za),await e.redirectToAuthorization(Ma),"REDIRECT"}n(Qt,"authInternal");function tr(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(tr,"isHttpsUrl");async function us(e,t,r){let o=to(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!ro({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(us,"selectResourceURL");async function ao(e,t,r=fetch){let o=await ms(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 ht.parse(await o.json())}n(ao,"discoverOAuthProtectedResourceMetadata");async function rr(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?rr(e,void 0,r):void 0;throw o}}n(rr,"fetchWithCorsRetry");function ls(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(ls,"buildWellKnownPath");async function oo(e,t,r=fetch){return await rr(e,{"MCP-Protocol-Version":t},r)}n(oo,"tryMetadataDiscovery");function ps(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(ps,"shouldAttemptFallback");async function ms(e,t,r,o){let i=new URL(e),a=o?.protocolVersion??qt,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let l=ls(t,i.pathname);s=new URL(l,o?.metadataServerUrl??i),s.search=i.search}let c=await oo(s,a,r);if(!o?.metadataUrl&&ps(c,i.pathname)){let l=new URL(`/.well-known/${t}`,i);c=await oo(l,a,r)}return c}n(ms,"discoverMetadataWithFallback");function fs(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(fs,"buildDiscoveryUrls");async function so(e,{fetchFn:t=fetch,protocolVersion:r=qt}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=fs(e);for(let{url:a,type:s}of i){let c=await rr(a,o,t);if(c){if(!c.ok){if(await c.body?.cancel(),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}return s==="oauth"?Oe.parse(await c.json()):gt.parse(await c.json())}}}n(so,"discoverAuthorizationServerMetadata");async function hs(e,t){let r,o;try{r=await ao(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 so(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(hs,"discoverOAuthServerInfo");async function gs(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:i,state:a,resource:s}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Yt))throw new Error(`Incompatible auth server: does not support response type ${Yt}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Xt))throw new Error(`Incompatible auth server: does not support code challenge method ${Xt}`)}else c=new URL("/authorize",e);let l=await Jt(),h=l.code_verifier,m=l.code_challenge;return c.searchParams.set("response_type",Yt),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",m),c.searchParams.set("code_challenge_method",Xt),c.searchParams.set("redirect_uri",String(o)),a&&c.searchParams.set("state",a),i&&c.searchParams.set("scope",i),i?.includes("offline_access")&&c.searchParams.append("prompt","consent"),s&&c.searchParams.set("resource",s.href),{authorizationUrl:c,codeVerifier:h}}n(gs,"startAuthorization");function ys(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(ys,"prepareAuthorizationCodeRequest");async function co(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:i,resource:a,fetchFn:s}){let c=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(a&&r.set("resource",a.href),i)await i(l,r,c,t);else if(o){let m=t?.token_endpoint_auth_methods_supported??[],v=is(o,m);as(v,o,l,r)}let h=await(s??fetch)(c,{method:"POST",headers:l,body:r});if(!h.ok)throw await io(h);return ye.parse(await h.json())}n(co,"executeTokenRequest");async function ws(e,{metadata:t,clientInformation:r,refreshToken:o,resource:i,addClientAuthentication:a,fetchFn:s}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),l=await co(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:a,resource:i,fetchFn:s});return{refresh_token:o,...l}}n(ws,"refreshAuthorization");async function _s(e,t,{metadata:r,resource:o,authorizationCode:i,fetchFn:a}={}){let s=e.clientMetadata.scope,c;if(e.prepareTokenRequest&&(c=await e.prepareTokenRequest(s)),!c){if(!i)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let h=await e.codeVerifier();c=ys(i,h,e.redirectUrl)}let l=await e.clientInformation();return co(t,{metadata:r,tokenRequestParams:c,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(_s,"fetchToken");async function Rs(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");a=new URL(t.registration_endpoint)}else a=new URL("/register",e);let s=await(i??fetch)(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!s.ok)throw await io(s);return Ee.parse(await s.json())}n(Rs,"registerClient");z();import{errors as yo,jwtVerify as wo,SignJWT as _o}from"jose";var T="zuplo-mcp-gateway",q=T,M="HS256";import{base64url as bs}from"jose";var Cs=new TextEncoder,Ss="MCP gateway could not initialize secure key material.",vs=32,uo=new Map,lo=new Map,xs;function Is(){return xs??Hr.instance.authPrivateKey}n(Is,"readAuthPrivateKey");function po(e){return new E(Ss,e===void 0?void 0:{cause:e})}n(po,"createGeneratedKeyMaterialError");function mo(e,t){let r=bs.decode(t);if(r.byteLength!==vs)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(mo,"decodeJwkKeyField");function As(e){let t=Is();if(!t)throw po();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=mo("d",r.d);mo("x",r.x);let i=Cs.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 po(r)}}n(As,"decodeGeneratedKeyMaterial");function Us(e){let t=uo.get(e);return t||(t=As(e),uo.set(e,t)),t}n(Us,"getMasterKeyMaterial");async function G(e){let t=lo.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Us(e.keyMaterialPurpose));return lo.set(e.purpose,r),r}n(G,"readCachedDerivedKey");var ks="SHA-256";var Ps="zuplo-mcp-gateway:",Ts=new TextEncoder,fo=new WeakMap;async function re(e,t){let r=fo.get(e);r||(r=new Map,fo.set(e,r));let o=r.get(t);if(o)return o;let i=await Os(e,t);return r.set(t,i),i}n(re,"deriveGatewaySigningKey");async function Os(e,t){let r=ho(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=Ts.encode(`${Ps}${t}`),a=await crypto.subtle.deriveBits({name:"HKDF",hash:ks,salt:new Uint8Array,info:ho(i)},o,32*8);return new Uint8Array(a)}n(Os,"hkdfExpand");function ho(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(ho,"copyToArrayBuffer");var Ro=15*60,Es=15*60,qs=qn.extend({id:Mn}),Ms=qs.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),bo=Nt.extend({id:zn,purpose:d.literal("browser_connect")}),zs=Nt.extend({purpose:d.literal("browser_connect")}),Ds=bo.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),Co=Ro*1e3;async function So(){return G({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>re(e,"oauth-state"),"derive")})}n(So,"getOAuthStateKey");async function vo(){return G({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>re(e,"browser-connect"),"derive")})}n(vo,"getBrowserConnectKey");async function xo(e){let t=Math.floor(Date.now()/1e3)+Ro;return new _o(e).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(t).sign(await So())}n(xo,"signOAuthState");async function yt(e){try{let{payload:t}=await wo(e,await So(),{algorithms:[M],issuer:T,audience:q});return Ms.parse(t)}catch(t){throw t instanceof yo.JWTExpired?new y({message:"OAuth state has expired",extensionMembers:{[w]:"oauth_state_expired"}},{cause:t}):new y({message:"OAuth state could not be verified",extensionMembers:{[w]:"oauth_state_invalid"}},{cause:t})}}n(yt,"verifyOAuthState");async function Io(e){let t=Math.floor(Date.now()/1e3)+Es,r=zs.parse(e),o=bo.parse({...r,id:Ln()});return new _o(o).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(t).sign(await vo())}n(Io,"signBrowserConnectTicket");async function Ao(e){try{let{payload:t}=await wo(e,await vo(),{algorithms:[M],issuer:T,audience:q});return Ds.parse(t)}catch(t){throw t instanceof yo.JWTExpired?new y({message:"Browser connect ticket has expired",extensionMembers:{[w]:"oauth_state_expired"}},{cause:t}):new y({message:"Browser connect ticket could not be verified",extensionMembers:{[w]:"oauth_state_invalid"}},{cause:t})}}n(Ao,"verifyBrowserConnectTicket");async function Uo(e){if((await R().consumeBrowserConnectTicket({id:e.id,expiresAt:_(new Date(e.exp*1e3)),now:_(new Date)})).kind==="consumed")throw new y({message:"Browser connect ticket has already been used",extensionMembers:{[w]:"oauth_state_reused"}})}n(Uo,"consumeBrowserConnectTicket");function Hs(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(Hs,"buildConnectRequiredMessage");async function Bs(e){let t=I(e.requestUrl),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 Io({...Te(e),purpose:"browser_connect"})),r.toString()}n(Bs,"buildGatewayBrowserTicketUrl");function Ls(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}n(Ls,"buildGatewayConnectPath");async function nr(e){return Bs({...e,path:Ls(e.upstreamServerId),redirect:!0})}n(nr,"buildGatewayConnectUrl");async function wt(e){let t={requestUrl:e.requestUrl,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 nr(t),message:Hs(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(wt,"buildRedirectConnectRequiredResponse");function ko(e){return js({...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(ko,"buildAdminConnectRequiredResponse");function js(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(js,"buildAdminSetupRequiredResponse");z();function or(e){return`Zuplo MCP Gateway - ${e}`}n(or,"buildGatewayOAuthClientName");function Po(e,t){let r=new URL(e,I(t));return se(r)&&Vr(r.hostname)!=="localhost"&&(r.hostname="localhost"),r.toString()}n(Po,"buildGatewayOAuthRedirectUri");function ir(e){let t=new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin);return t.searchParams.set("authProfileId",e.authProfileId),t.toString()}n(ir,"buildOAuthClientMetadataDocumentUrl");function To(e){return I(e)}n(To,"requireOAuthClientMetadataOrigin");function Oo(e,t,r){let o=te(t),i=de(t,r);return{client_id:ir({origin:e,upstreamServerId:t,authProfileId:r}),client_name:or(o.displayName),client_uri:new URL("/",e).toString(),redirect_uris:[new URL(i.redirectPath,e).toString()],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",token_endpoint_auth_method:"none"}}n(Oo,"buildOAuthClientMetadataDocument");z();import{base64url as ne}from"jose";var Ns="SHA-256",_e="AES-GCM",Gs=12,sr="zuplo-secret",cr=1,Eo="generated:auth_private_key:token-encryption",$s=d.object({version:d.literal(cr),keyId:d.literal(Eo),algorithm:d.literal(_e),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();function we(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(we,"copyToArrayBuffer");async function ar(){return G({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(Ns,we(e));return crypto.subtle.importKey("raw",t,{name:_e},!1,["encrypt","decrypt"])},"derive")})}n(ar,"getEncryptionKey");function qo(e){return we(new TextEncoder().encode(`${sr}:v${e.version}:${e.keyId}`))}n(qo,"getAssociatedData");function Zs(e){return`${sr}:v${e.version}:${ne.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(Zs,"encodeEnvelope");function Fs(e){let t=`${sr}:v${cr}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(ne.decode(r));return $s.parse(JSON.parse(o))}n(Fs,"decodeEnvelope");async function _t(e){let t=await ar(),r=crypto.getRandomValues(new Uint8Array(Gs)),o={version:cr,keyId:Eo},i=await crypto.subtle.encrypt({name:_e,iv:r,additionalData:qo(o)},t,new TextEncoder().encode(e));return Zs({...o,algorithm:_e,iv:ne.encode(r),ciphertext:ne.encode(new Uint8Array(i))})}n(_t,"encryptSecret");async function Fe(e){let t=Fs(e);if(t){let s=await ar(),c=await crypto.subtle.decrypt({name:_e,iv:we(ne.decode(t.iv)),additionalData:qo(t)},s,we(ne.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,o]=e.split(".");if(!r||!o)throw new E("Encrypted payload is malformed");let i=await ar(),a=await crypto.subtle.decrypt({name:_e,iv:we(ne.decode(r))},i,we(ne.decode(o)));return new TextDecoder().decode(a)}n(Fe,"decryptSecret");var Ks=d.union([Ee,Vt]),Ws=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:ht.optional(),authorizationServerMetadata:d.union([Oe,gt]).optional()}).passthrough(),Js="Bearer",Vs="__zuplo_refresh_only_upstream_access_token__";function Ys(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Ys,"splitScopes");function Xs(e){return at.parse(e)}n(Xs,"parsePkceCodeVerifier");function Qs(e){if(typeof e.expires_in=="number")return _(new Date(Date.now()+e.expires_in*1e3))}n(Qs,"readTokenExpiry");async function Mo(e){if(e!==void 0)return _t(JSON.stringify(e))}n(Mo,"encryptJson");async function zo(e,t){if(!e)return;let r=await Fe(e);try{return t.parse(JSON.parse(r))}catch(o){throw new y({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[w]:"oauth_state_invalid"}},{cause:o})}}n(zo,"decryptJson");function ec(e){if(e===void 0)return;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(ec,"toOAuthDiscoveryState");function tc(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(tc,"clientInformationAllowsRedirectUri");function rc(e,t,r){let o=te(e),i=de(e,t),a;return i.scopes.length>0&&(a=i.scopes.join(i.scopeDelimiter)),{client_name:or(o.displayName),client_uri:new URL("/",new URL(r).origin).toString(),redirect_uris:[r],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",scope:a,token_endpoint_auth_method:"none"}}n(rc,"buildOAuthClientMetadata");function nc(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new k(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return Ee.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(nc,"buildManualOAuthClientInformation");function oc(e,t,r){let o=ir({origin:new URL(r).origin,upstreamServerId:e,authProfileId:t});return tr(o)?o:void 0}n(oc,"buildClientMetadataUrl");function Do(e){for(let t of e)if(t!==void 0)return t}n(Do,"firstDefined");function ic(e){let t=de(e.target.upstreamServerId,e.target.authProfileId),r=rc(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);if(t.clientRegistration.mode==="manual")return{clientMetadata:r,configuredClientInformation:nc({clientMetadata:r,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let o=oc(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);return o===void 0?{clientMetadata:r}:{clientMetadata:r,clientMetadataUrl:o}}n(ic,"buildInitialOAuthClientSetup");function ac(e,t){if(t===void 0)return Do([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(ac,"readEncryptedClientInformation");function sc(e){return Do([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}n(sc,"readEncryptedDiscoveryState");var fe=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredClientInformation;authorizationUrlValue;connection;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;constructor(t){let r=ic({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.clientMetadataValue=r.clientMetadata,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=ac(t,this.configuredClientInformation),this.encryptedDiscoveryState=sc(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return this.clientMetadataValue}async state(){let t=await this.createPendingState();return xo({id:t.id,...Te({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,this.encryptedClientInformation=await Mo(t),await this.syncPendingState(!1))}async discoveryState(){return this.loadPersistedDiscoveryState()}async saveDiscoveryState(t){this.cachedDiscoveryState=t,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await Mo(t),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=ye.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=r.refresh_token?await _t(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:ye.parse({...r,refresh_token:await Fe(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let a={id:this.connection?.id??Hn(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await _t(r.access_token),encryptedRefreshToken:i,scopes:Ys(r.scope??this.clientMetadataValue.scope),expiresAt:Qs(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await R().upsertUpstreamConnection(a)}async redirectToAuthorization(t){this.authorizationUrlValue=t.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:Xs(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new y({message:"OAuth code verifier is missing",extensionMembers:{[w]:"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),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:Bn(),...Te({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:_(new Date(Date.now()+Co)),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 R().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await zo(this.encryptedClientInformation,Ks)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&!tc(t,this.redirectUriValue)){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1);return}return this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async loadPersistedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;try{this.cachedDiscoveryState=ec(await zo(this.encryptedDiscoveryState,Ws))}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1)}return this.discoveryStateLoaded=!0,this.cachedDiscoveryState}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 Fe(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await Fe(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=ye.parse({access_token:t??Vs,token_type:Js,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 R().upsertUpstreamConnection(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var cc=3e4,dc=256*1024,uc=2;function lc(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(lc,"hasUsableAccessToken");var pc="does not support dynamic client registration";function mc(e){return e instanceof Error&&e.message.includes(pc)}n(mc,"isDynamicClientRegistrationUnsupported");function fc(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(fc,"readOAuthFetchRequest");function hc(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(hc,"responseLooksJson");function Ho(e){return async(t,r)=>{let o=fc(t),i=await Zn(t,r,{maxRedirects:uc,maxResponseBytes:dc,problemCode:"upstream_token_exchange_failed",timeoutMs:cc}),a=await i.clone().text();if(!hc(i,a))return i;try{JSON.parse(a)}catch(s){throw new y({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[w]:"upstream_token_exchange_failed"}},{cause:s})}return i}}n(Ho,"createUpstreamOAuthFetch");async function Bo(e,t){try{return await er(e,{serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Ho(t.upstreamServerId)})}catch(r){throw mc(r)?new y({message:`The authorization server for ${t.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register a client for the gateway manually before retrying.`,extensionMembers:{[w]:"upstream_client_registration_required"}},{cause:r}):r}}n(Bo,"runUpstreamOAuth");async function gc(e,t){return er(e,{serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Ho(t.upstreamServerId)})}n(gc,"exchangeUpstreamAuthorizationCode");async function Lo(e,t){let r=await Bo(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new y({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}}):new y({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}})}n(Lo,"requireUpstreamAuthorizationRedirect");async function jo(e){if(!e.forceRefresh&&lc(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await Bo(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl});if(t==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(t!=="REDIRECT")throw new y({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new y({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}});return{kind:"connect_required",payload:await bc({requestUrl:e.target.request.url,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(jo,"authorizeUpstreamOAuthSession");async function yc(e){let t=await yt(e.stateToken),r=await R().consumeUpstreamOAuthState({id:t.id,now:_(new Date)}),o=wc(r);return _c({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),Rc(o),o}n(yc,"consumeStoredCallbackState");function wc(e){switch(e.kind){case"consumed":throw new y({message:"OAuth state has already been used",extensionMembers:{[w]:"oauth_state_reused"}});case"missing":throw new y({message:"OAuth state is missing or expired",extensionMembers:{[w]:"oauth_state_expired"}});case"available":return e.record}}n(wc,"readConsumedCallbackState");function _c(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 y({message:"OAuth callback did not match the initiating request",extensionMembers:{[w]:"oauth_callback_mismatch"}})}n(_c,"assertStoredCallbackStateMatches");function Rc(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new y({message:"OAuth state has expired",extensionMembers:{[w]:"oauth_state_expired"}})}n(Rc,"assertStoredCallbackStateFresh");async function bc(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),ko(r)}let t={requestUrl:e.requestUrl,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),wt(t)}n(bc,"buildOAuthConnectRequiredResponse");async function No(e){let t=await yc({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=ut(t),[o]=await R().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),i={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};o!==void 0&&(i.connection=o);let a=new fe(i),s=await gc(a,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(s==="AUTHORIZED")return t;throw s!=="REDIRECT"?new y({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${s}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}}):new y({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}})}n(No,"finishUpstreamOAuthCallback");async function Go(e){let t=te(e.upstreamServerId),r=de(e.upstreamServerId,e.authProfileId),o=Po(r.redirectPath,e.request.url),i="preloadedConnection"in e?e.preloadedConnection:(await R().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:i,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}},redirectUri:o,returnOrigin:I(e.request.url)}}}n(Go,"prepareUpstreamOAuthRequest");async function $o(e){let t=await Go(e),r=new fe({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Lo(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n($o,"startUpstreamConnect");async function Zo(e){let t=await Go(e),r=new fe({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return jo({target:e,provider:r,connection:t.connection,forceRefresh:e.forceRefresh,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Zo,"authorizeUpstreamRequest");async function Re(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return Zo({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,forceRefresh:e.forceRefresh,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},...t.returnTo===void 0?{}:{returnTo:t.returnTo}})}let r=t;throw new E(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(Re,"resolveUpstreamCredentialForRoute");async function Fo(e){let t,r={request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,operationId:e.connectRequest.operationId,...e.connectRequest.returnTo===void 0?{}:{returnTo:e.connectRequest.returnTo}},o=N(e.connectRequest.authMode);switch(o.connectSupport){case"oauth_authorization":t=await $o(r);break;case"none":throw new E(o.connectUnsupportedDetail??`Upstream server ${e.connectRequest.upstreamServerId} does not support browser connection flows.`)}return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}n(Fo,"startUpstreamConnectForRequest");async function Ko(e){let r=(await yt(e.callbackRequest.state)).authProfileId,o=Kt({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r});if(N(o.mode).callbackSupport!=="authorization_code")throw new E(`Upstream server ${e.callbackRequest.upstreamServerId} does not support OAuth callbacks.`);return No({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:te(e.callbackRequest.upstreamServerId)})}n(Ko,"finishUpstreamCallbackForRequest");function Cc(e){let t=N(e.connection.authMode);return{upstreamServerId:e.connection.upstreamServerId,operationId:e.operationId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:t.ownerMode}}n(Cc,"buildRouteAuthBaseFromConnection");function Jo(e){let t=N(e.connection.authMode);return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:it(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:t.ownerMode}}n(Jo,"buildRouteAuthBaseFromPolicyOptions");function Rt(e,t){let o=j().byOperationId.get(t);if(!o)throw new k(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new k(`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 k(`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 Cc({connection:o.connection,operationId:t})}n(Rt,"resolveRouteAuthBase");function Wo(e,t){switch(e){case"user":return dt(t.subjectId);case"shared":return En()}}n(Wo,"buildOwnerForPrincipal");function be(e,t){switch(e.ownerMode){case"shared":return{...e,owner:Wo(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"user":return{...e,owner:Wo(e.ownerMode,t),initiatedBySubjectId:t.subjectId}}}n(be,"resolveRouteAuthForPrincipal");var Sc=Pe.InvalidRequest,vc=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function xc(e){let t=e.route.raw();return rt.parse(t?.operationId)}n(xc,"readOperationId");async function Ic(e,t,r,o){let i=await Re({request:e,routeAuth:t});if(i.kind==="connect_required")return 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;switch(a.type){case"none":return{kind:"headers",headers:[]};case"bearer_token":return{kind:"headers",headers:[["authorization",`Bearer ${a.token}`]]};case"headers":return{kind:"headers",headers:Object.entries(a.headers)};case"mcp_oauth_provider":{let s=await a.provider.tokens();return s?{kind:"headers",headers:[["authorization",`${s.token_type??"Bearer"} ${s.access_token}`]]}:(o.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:t.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),Response.json({error:"no_upstream_tokens"},{status:401}))}}}n(Ic,"buildCredentialHeaders");var Ac=new Set(["authorization","cookie","cookie2"]);function Uc(e,t){let r=new Headers(e.headers);for(let o of Ac)r.delete(o);for(let[o,i]of t)r.set(o,i);return new Lr(e,{headers:r})}n(Uc,"applyUpstreamHeaders");function kc(e){let t=new Headers(e.headers);for(let r of vc)t.delete(r);return t}n(kc,"buildProxyHeaders");async function Pc(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(Pc,"readRetryBody");function Vo(e,t){let r=t.authUrl===void 0?void 0:Jn({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(pt({id:Wn(e),error:{code:r?.code??Sc,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(Vo,"connectRequiredJsonRpcResponse");async function Tc(e){let t=await Re({request:e.request,routeAuth:e.routeAuth,forceRefresh:!0});if(t.kind==="connect_required")return{kind:"connect_required",payload:t.payload};let r=new Headers(e.headers),o=t.credential;switch(o.type){case"none":return r.delete("authorization"),{kind:"headers",headers:r};case"bearer_token":return r.set("authorization",`Bearer ${o.token}`),{kind:"headers",headers:r};case"headers":for(let[i,a]of Object.entries(o.headers))r.set(i,a);return{kind:"headers",headers:r};case"mcp_oauth_provider":{let i=await o.provider.tokens();return i?(r.set("authorization",`${i.token_type??"Bearer"} ${i.access_token}`),{kind:"headers",headers:r}):(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(Tc,"applyRefreshedCredentialHeaders");function Oc(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await Tc({request:e.request,context:e.context,headers:kc(r),routeAuth:e.routeAuth});if(o.kind==="connect_required")return Vo(e.requestBody,o.payload);if(o.kind==="response")return o.response;let i=on({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return Xe.fetch(i.url,i.init)})}n(Oc,"installUpstreamAuthRetryHook");async function dr(e,t,r){let o=xc(t),i=await Pc(e),a=Jo({connection:r,operationId:o}),s=be(a,Tn(e,t)),c=await Ic(e,s,r,t);if(!(c instanceof Response)&&c.kind==="connect_required")return Vo(i,c.payload);if(c instanceof Response)return c;let l=Uc(e,c.headers);return Oc({request:l,context:t,requestBody:i,routeAuth:s}),l}n(dr,"mcpTokenExchangePolicy");var ur=class extends et{static{n(this,"McpTokenExchangeInboundPolicy")}constructor(t,r){let o=ln(t,r);super(o,r)}async handler(t,r){return Qe("policy.inbound.mcp-token-exchange"),dr(t,r,this.options)}};z();var Yo=Symbol("Html");function Ec(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n(Ec,"escapeHtml");function qc(e){return e===null||typeof e!="object"?!1:e[Yo]===!0}n(qc,"isHtml");function Xo(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Xo).join(""):qc(e)?e.value:Ec(String(e))}n(Xo,"renderValue");function V(e){return{[Yo]:!0,value:e}}n(V,"trustedHtml");var he=V("");function b(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=Xo(t[o]),r+=e[o+1]??"";return V(r)}n(b,"html");function Ce(e){return e.value}n(Ce,"renderHtml");function Qo(e){return b`<p data-gateway-error-code="${e.code}">${e.detail}</p>${e.guidance} ${e.action}`}n(Qo,"renderBrowserErrorPage");var Se=V('*,: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 ve(e){return b`<!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>
30
26
  ${e.styles}
31
- </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(It,"renderShell");var zo="zuplo.com";function tu(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(tu,"s2FaviconHref");function Fg(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(Fg,"strictFaviconHref");var Fr=tu(zo);function Kr(e){let t=e.toLowerCase();return t===zo||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?tu(zo):Fg(e)}n(Kr,"resolveIconHref");function Wr(e){return L`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}n(Wr,"renderShellIcon");var Kg="text/html; charset=utf-8";function kt(e){try{return new URL(e).host}catch{return""}}n(kt,"safeHostFromUrl");function Ce(e){let t=Kr(e.host),r=Wg(e.kind??"authorization_failed");return new Response(At(It({title:e.title??r.title,iconHref:t,styles:vt,headerIcon:Wr({iconHref:t,fallbackIconHref:Fr}),heading:e.title??r.title,subhead:"",body:eu({code:e.code??"unknown",detail:e.detail,guidance:L`<p class="card__description">${r.guidance}</p>`,action:Jg(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":Kg,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(Ce,"browserErrorPageResponse");function Wg(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(Wg,"readBrowserErrorPagePresentation");function Jg(e){return e===void 0?tt:L`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(Jg,"renderAction");var ru="application/json",Vg="application/x-www-form-urlencoded";function Jr(e,t){return new w({message:e,extensionMembers:{[y]:"invalid_request"}},t===void 0?void 0:{cause:t})}n(Jr,"invalidRequestError");function Yg(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}n(Yg,"normalizeContentType");function Xg(e,t){return e===t?!0:t===ru&&e.endsWith("+json")}n(Xg,"contentTypeMatches");function Qg(e,t){if(!t||t.length===0)return;let r=Yg(e.headers.get("content-type"));if(!t.some(o=>Xg(r,o)))throw Jr(`Request body must be ${t.join(" or ")}.`)}n(Qg,"assertExpectedContentType");function ey(e,t,r){let o=e.headers.get("content-length");if(!o)return;let a=Number.parseInt(o,10);if(Number.isFinite(a)&&a>t)throw Jr(`${r} exceeded the maximum allowed size.`)}n(ey,"assertContentLengthWithinLimit");async function nu(e,t){let r=t.label??"Request body";Qg(e,t.expectedContentTypes),ey(e,t.maxBytes,r);let o=await Lr(e.body,{maxBytes:t.maxBytes,createLimitError:n(()=>Jr(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(o)}n(nu,"readBoundedTextBody");async function ou(e,t){let r=await nu(e,{...t,expectedContentTypes:[ru]});try{return JSON.parse(r)}catch(o){throw Jr("Request body must be valid JSON.",o)}}n(ou,"readBoundedJsonBody");async function iu(e,t){let r=await nu(e,{...t,expectedContentTypes:[Vg]});return new URLSearchParams(r)}n(iu,"readBoundedFormUrlEncodedBody");z();z();import{errors as lu,jwtVerify as mu,SignJWT as hu}from"jose";z();import{errors as ly,jwtVerify as my,SignJWT as hy}from"jose";function Ne(e){let t=K().browserLogin[e];if(typeof t=="string"&&t.length>0)return t;throw R("internal_server_error",`browserLogin.${e} is required for federated browser login. Set it on the mcp-oauth-inbound policy options.`)}n(Ne,"requireBrowserLoginField");z();import{createRemoteJWKSet as ry,errors as sr,jwtVerify as ny}from"jose";var oy=i.object({id_token:i.string().min(1),token_type:i.string().min(1).optional(),expires_in:i.number().optional(),access_token:i.string().min(1).optional(),refresh_token:i.string().min(1).optional(),scope:i.string().min(1).optional()}),iy=i.object({error:i.string().min(1).optional(),error_description:i.string().min(1).optional(),error_uri:i.string().min(1).optional()});function ay(e){let t=iy.safeParse(e);if(!t.success)return{};let r={};return t.data.error!==void 0&&(r.idpError=t.data.error),t.data.error_description!==void 0&&(r.idpErrorDescription=t.data.error_description.slice(0,256)),t.data.error_uri!==void 0&&(r.idpErrorUri=t.data.error_uri.slice(0,256)),r}n(ay,"readIdpErrorFields");function sy(e){return e instanceof sr.JWTExpired?"expired":e instanceof sr.JWTClaimValidationFailed?"claim":e instanceof sr.JWSSignatureVerificationFailed?"signature":e instanceof sr.JWKSNoMatchingKey?"jwks_no_match":e instanceof sr.JWTInvalid?"invalid":e instanceof i.ZodError?"schema":"other"}n(sy,"readJwtFailureKind");var cy=i.object({sub:q,nonce:i.string().min(1)}).catchall(i.unknown()),Eo;function uy(e){return e instanceof Error&&"cause"in e?e.cause:e}n(uy,"readErrorCause");function dy(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}n(dy,"readRuntimeGatewayCode");function py(){if(!Eo){let e=K();Eo=ry(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return Eo}n(py,"readFederatedJwks");async function au(e){let t=K(),r=Ne("tokenUrl"),o=Ne("clientId"),a=Ne("clientSecret"),s=new URL("/oauth/callback",Te(e.requestUrl)).toString(),u=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:s,client_id:o,client_secret:a});try{let{response:d,json:p}=await sc(r,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:u},{maxResponseBytes:32768,problemCode:"browser_login_verification_failed",timeoutMs:t.browserLogin.remoteTimeoutMs,...e.context===void 0?{}:{context:e.context}});if(!d.ok){let k=ay(p);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:we(r),idpStatus:d.status,...k},"Federated browser login token exchange returned non-2xx from the identity provider"),R({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${d.status}${k.idpError?` idp_error=${k.idpError}`:""}${k.idpErrorDescription?` idp_error_description=${k.idpErrorDescription}`:""})`)})}let h=oy.parse(p),g;try{({payload:g}=await ny(h.id_token,py(),{issuer:t.oidc.issuer,audience:o}))}catch(k){let ne={};throw ie(ne,"error",k),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:sy(k),idpHost:we(r),expectedIssuer:t.oidc.issuer,...ne},"Federated id_token failed jose verification"),k}if(g.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:we(r),nonceMissingFromIdToken:g.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),R("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let D=cy.parse(g);return Fe({sub:D.sub,data:D},e.requestUrl)}catch(d){let p=de(d)??dy(d);throw p!==void 0&&p!=="browser_login_verification_failed"?d:R("browser_login_verification_failed","Federated browser login callback could not be verified.",uy(d))}}n(au,"exchangeFederatedAuthorizationCode");var qo="zuplo_mcp_session",fy=i.object({purpose:i.literal("gateway_browser_session"),sub:q,browserLoginOrigin:i.string().min(1),roles:i.array(i.string().min(1)).optional(),exp:i.number().int().positive(),iat:i.number().int().positive().optional()});function gy(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let o=r.indexOf("=");if(o<0)continue;let a=r.slice(0,o).trim(),s=r.slice(o+1).trim();if(a)try{t.set(a,decodeURIComponent(s))}catch{t.set(a,s)}}return t}n(gy,"parseCookieHeader");async function su(){return be({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Le(e,"browser-session"),"derive")})}n(su,"getBrowserSessionKey");function Mo(e){let t=new URL(P(e)),r=[`${qo}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(Mo,"buildBrowserSessionEvictionCookie");function yy(e){let t=new URL(P(e.requestUrl)),r=[`${qo}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(yy,"serializeSessionCookie");function cu(){return new URL(Ne("url")).origin}n(cu,"readBrowserLoginOrigin");function Ho(){return K().browserLogin.stateTtlSeconds}n(Ho,"readBrowserLoginStateTtlSeconds");function uu(e){if(!e.user)throw R("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return Fe(e.user,e.url)}n(uu,"resolveCurrentRequestPrincipal");async function Vr(e,t={}){let r=gy(e.headers.get("cookie")).get(qo);if(!r)return{};try{let{payload:o}=await my(r,await su(),{algorithms:[me],issuer:ae,audience:le}),a=fy.parse(o);if(a.browserLoginOrigin!==cu())return{evictCookie:Mo(e.url)};let s={subjectId:a.sub};return a.roles&&a.roles.length>0&&(s.roles=a.roles),{principal:s}}catch(o){return o instanceof ly.JWTExpired?{evictCookie:Mo(e.url)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:o instanceof Error?o.name:"unknown",errorMessage:o instanceof Error?o.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:Mo(e.url)})}}n(Vr,"readBrowserSession");async function Yr(e){let t=K().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:cu()};e.principal.roles&&(r.roles=e.principal.roles);let o=await new hy(r).setProtectedHeader({alg:me,typ:"JWT"}).setIssuer(ae).setAudience(le).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await su());return yy({value:o,requestUrl:e.requestUrl,ttlSeconds:t})}n(Yr,"createBrowserSessionCookie");async function du(e){let t={};e.context!==void 0&&(t.context=e.context);let r=await Vr(e.request,t);if(r.principal)return r.principal;let o=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(!o)throw R("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.");return au({code:o,nonce:e.stateId,requestUrl:e.request.url,...e.context===void 0?{}:{context:e.context}})}n(du,"resolveBrowserLoginCallbackPrincipal");function pu(e){let t=K().browserLogin,r=new URL(Ne("url")),o=new URL("/oauth/callback",Te(e.requestUrl));return xa(r)?(r.searchParams.set("redirect_uri",o.toString()),r.searchParams.set("state",e.state),r):(r.searchParams.set("response_type","code"),r.searchParams.set("client_id",Ne("clientId")),r.searchParams.set("redirect_uri",o.toString()),r.searchParams.set("scope",t.scope),r.searchParams.set("state",e.state),r.searchParams.set("nonce",e.nonce),t.audience&&r.searchParams.set("audience",t.audience),r)}n(pu,"buildBrowserLoginUrl");var wy={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},S=class extends Error{static{n(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,o=wy[t],a){super(r,a),this.name="OAuthProtocolError",this.errorCode=t,this.status=o}};var Sy=5*60,Ry=i.object({purpose:i.literal("gateway_browser_login"),transactionId:pe,stateId:vr,exp:i.number().int().positive(),iat:i.number().int().positive().optional()}),_y=i.object({purpose:i.literal("gateway_authorization_setup"),transactionId:pe,stateId:vr,exp:i.number().int().positive(),iat:i.number().int().positive().optional()});async function fu(){return be({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Le(e,"browser-login"),"derive")})}n(fu,"getBrowserLoginKey");async function gu(){return be({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Le(e,"authorization-csrf"),"derive")})}n(gu,"getCsrfKey");function yu(e){return{now:e.now??new Date,ttlSeconds:Ho()}}n(yu,"readPendingTransactionDependencies");function by(e,t){return e.subjectId===t.subjectId}n(by,"principalsMatch");function wu(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}n(wu,"toPendingPrincipal");function Su(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,operationId:e.transaction.operationId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:x(e.now),expiresAt:x(Ue(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw R("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:wu(e.principal)}}n(Su,"createTransactionRecord");async function Ru(e){let{id:t,...r}=e.record,o=await A().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(o.kind){case"started":return o.transaction;case"already_exists":throw R("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new S("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new S("invalid_request","redirect_uri is not registered for the client.")}}n(Ru,"startPendingTransaction");async function Cy(e){return new hu({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:me,typ:"JWT"}).setIssuer(ae).setAudience(le).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await fu())}n(Cy,"signBrowserLoginState");async function _u(e){return new hu({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:jn()}).setProtectedHeader({alg:me,typ:"JWT"}).setIssuer(ae).setAudience(le).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await gu())}n(_u,"signCsrfToken");async function Do(e){try{let{payload:t}=await mu(e,await fu(),{algorithms:[me],issuer:ae,audience:le}),r=Ry.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof lu.JWTExpired?R("oauth_state_expired","Browser login state has expired.",t):R("oauth_state_invalid","Browser login state could not be verified.",t)}}n(Do,"verifyBrowserLoginStateToken");async function Xr(e){try{let{payload:t}=await mu(e,await gu(),{algorithms:[me],issuer:ae,audience:le});return{transactionId:_y.parse(t).transactionId}}catch(t){throw t instanceof lu.JWTExpired?R("oauth_state_expired","Authorization setup state has expired.",t):R("oauth_state_invalid","Authorization setup state could not be verified.",t)}}n(Xr,"verifyCsrfToken");function jo(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}n(jo,"pendingStateErrorCode");function xy(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}n(xy,"toPendingAuthorizationGetResult");function Ay(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}n(Ay,"toPendingAuthorizationAdvanceResult");function Lo(e){return e==="principal_mismatch"?"oauth_callback_mismatch":jo(e==="consumed_already"?"consumed_already":e)}n(Lo,"setupDecisionErrorCode");async function bu(e){let t=e.now??new Date,r=await Xr(e.csrfToken),o=await A().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await E(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:x(t)});if(o.kind!=="marked")throw R(Lo(o.kind),"Authorization setup state is invalid, expired, or already used.");return Cu({kind:"available",record:o.transaction})}n(bu,"markSetupApproved");function Cu(e){if(e.kind!=="available")throw R(jo(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw R("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}n(Cu,"requireAwaitingSetup");function vy(e){if(!by(e.currentBrowserPrincipal,e.transaction.principal))throw R("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}n(vy,"requireCurrentPrincipalMatches");async function xu(e){let t=e.now??new Date,r=Ho(),o=Dn(),a=jn(),s=await Cy({transactionId:o,stateId:a,ttlSeconds:r}),u=Su({id:o,transaction:e.transaction,currentStateHash:await E(s),phase:"awaiting_login",now:t,ttlSeconds:r});if(u.phase!=="awaiting_login")throw R("oauth_state_invalid","Authorization transaction did not start in login phase.");let d=await Ru({record:u,client:e.transaction.client});if(d.phase!=="awaiting_login")throw R("oauth_state_invalid","Authorization transaction did not start in login phase.");return{transaction:d,browserLoginStateToken:s,browserLoginUrl:pu({state:s,nonce:a,operationId:u.operationId,requestUrl:e.requestUrl})}}n(xu,"startAwaitingLogin");async function Au(e){let{now:t,ttlSeconds:r}=yu(e),o=Dn(),a=await _u({transactionId:o,ttlSeconds:r}),s=Su({id:o,transaction:e.transaction,currentStateHash:await E(a),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(s.phase!=="awaiting_setup")throw R("oauth_state_invalid","Authorization transaction did not start in setup phase.");let u=await Ru({record:s,client:e.transaction.client});if(u.phase!=="awaiting_setup")throw R("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:u,csrfToken:a}}n(Au,"startAwaitingSetup");async function vu(e){let{now:t,ttlSeconds:r}=yu(e),o=await Do(e.browserLoginStateToken),a=await _u({transactionId:o.transactionId,ttlSeconds:r}),s=Ay(await A().advancePendingAuthorization({transactionId:o.transactionId,expectedPhase:"awaiting_login",currentStateHash:await E(e.browserLoginStateToken),nextStateHash:await E(a),nextPhase:"awaiting_setup",principal:wu(e.principal),now:x(t)}));if(s.kind!=="advanced")throw R(jo(s.kind),"Browser login state is invalid, expired, or already used.");if(s.record.phase!=="awaiting_setup")throw R("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:s.record,csrfToken:a}}n(vu,"completeLogin");async function Iu(e){let t=await Bo(e);return vy({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}n(Iu,"getSetup");async function Bo(e){let t=e.now??new Date,r=await Xr(e.csrfToken);return Cu(xy(await A().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await E(e.csrfToken),now:x(t)})))}n(Bo,"getSetupTransaction");async function Iy(e){let t=await Xr(e.csrfToken),r=Pe(),o=x(Ue(e.now,Sy)),a=await A().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await E(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await E(r),authorizationCodeExpiresAt:o,grantId:ba(),now:x(e.now)});if(a.kind!=="approved")throw R(a.kind==="cancelled"?"oauth_state_invalid":Lo(a.kind),"Authorization setup state is invalid, expired, or already used.");let s=new URL(a.transaction.redirectUri);return s.searchParams.set("code",r),a.transaction.clientState&&s.searchParams.set("state",a.transaction.clientState),s}n(Iy,"createAuthorizationCodeRedirectWithDecision");async function ky(e){let t=await Xr(e.csrfToken),r=await A().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await E(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:x(e.now)});if(r.kind!=="cancelled")throw R(r.kind==="approved"?"oauth_state_invalid":Lo(r.kind),"Authorization setup state is invalid, expired, or already used.");return Uy({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}n(ky,"createCancelRedirectWithDecision");function Uy(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),t}n(Uy,"buildClientCancelRedirect");async function ku(e){let t=e.now??new Date;return Iy({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(ku,"approve");async function Uu(e){let t=e.now??new Date;return ky({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Uu,"cancel");z();var Ty=1e4,Py=5*1024,Oy=2,zy=90*24*60*60,No=["authorization_code","refresh_token"],Go=["code"],Ey=i.object({client_name:i.string().min(1).optional(),redirect_uris:i.array(i.string().min(1)).min(1),grant_types:i.array(i.enum(No)).min(1).max(2).optional(),response_types:i.array(i.enum(Go)).min(1).max(1).optional(),scope:i.literal(M).optional(),token_endpoint_auth_method:Sa.default("none")});function My(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&Z(t))&&t.pathname!=="/"}catch{return!1}}n(My,"isCimdClientIdCandidate");function Ut(e,t="invalid_request",r="authorize"){if(qy(e))throw new S(t,"redirect_uris must not include raw whitespace or control characters.");let o;try{o=new URL(e)}catch{throw new S(t,"redirect_uris must be absolute URIs.")}if(o.hash||o.username||o.password)throw new S(t,"redirect_uris must not include credentials or fragments.");let a={source:r},s=ga({url:o,context:a});if(s.kind!=="rejected"){s.mode!=="strict"&&void 0;return}throw new S(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}n(Ut,"assertValidRedirectUri");function qy(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}n(qy,"hasForbiddenRawRedirectUriCharacter");async function Hy(e){let{response:t,json:r}=await cc(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:Oy,maxResponseBytes:Py,timeoutMs:Ty});if(!t.ok)throw R("invalid_request","CIMD metadata could not be fetched.");let o=_a.parse(r);for(let a of o.redirect_uris)Ut(a,"invalid_request","cimd");if(o.client_id!==e.clientId)throw R("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return o}n(Hy,"fetchCimdMetadata");async function Dy(e){let t=jr(e),r=await Hy({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}n(Dy,"resolveCimdClient");async function Qr(e,t){let r=J.parse(e);if(My(r)){if(!K().gateway.cimdEnabled)throw new S("invalid_client","OAuth client is not registered.");try{return await Dy(r)}catch{throw new S("invalid_client","OAuth client is not registered.")}}let o=await A().readClient({clientId:r});if(o.kind==="found"){let a=o.client,s={kind:"dcr",clientId:r,metadata:{client_id:a.clientId,client_name:a.clientName,redirect_uris:a.redirectUris,token_endpoint_auth_method:a.tokenEndpointAuthMethod}};return a.hashedClientSecret&&(s.hashedClientSecret=a.hashedClientSecret),s}throw new S("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}n(Qr,"resolveClient");function Tu(e,t){if(!e.metadata.redirect_uris.some(r=>Ca(r,t)))throw R("invalid_request","redirect_uri is not registered for the client.")}n(Tu,"assertRedirectRegistered");function jy(e){let t=Pu(e.grant_types),r=e.response_types??[...Go];if(!Ly(t))throw new S("invalid_client_metadata","grant_types must be a subset of authorization_code and refresh_token.");if(!By(r))throw new S("invalid_client_metadata","response_types must be code.");if(!Ny(e.scope))throw new S("invalid_client_metadata",`Only the ${M} scope is supported.`)}n(jy,"assertSupportedDcrRequest");function Pu(e){return e===void 0?[...No]:Array.from(new Set(e))}n(Pu,"normalizeGrantTypes");function Ly(e){return e.length===0?!1:e.every(t=>No.includes(t))}n(Ly,"isSupportedGrantTypes");function By(e){return e.length===Go.length&&e[0]==="code"}n(By,"isSupportedResponseTypes");function Ny(e){return e===void 0||e===M}n(Ny,"isSupportedDcrScope");function cr(e){if(e===void 0||e===M)return M;throw new S("invalid_request",`Only the ${M} scope is supported.`)}n(cr,"assertSupportedOAuthScope");function Tt(e,t){let r;try{r=new URL(t)}catch{throw new S("invalid_target","resource must be an absolute URI.")}if(r.hash)throw new S("invalid_target","resource must not include a fragment.");if(r.protocol!=="https:"&&!Z(r))throw new S("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let o=P(e),a=ua(),s=a?[...a.byOperationId.values()].find(u=>new URL(u.routePath,o).toString()===t):void 0;if(!s)throw new S("invalid_target","resource must match a published MCP route.");return s}n(Tt,"resolveResource");async function Ou(e){let t;try{t=Ey.parse(e)}catch(g){if(g instanceof i.ZodError){let D=g.issues.some(k=>k.path[0]==="redirect_uris");throw new S(D?"invalid_redirect_uri":"invalid_client_metadata",g.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:g})}throw g}jy(t);for(let g of t.redirect_uris)Ut(g,"invalid_redirect_uri","dcr");let r=new Date,o=J.parse(`dcr:${crypto.randomUUID()}`),a=Ue(r,zy),s=Math.floor(r.getTime()/1e3),u=Math.floor(a.getTime()/1e3),d={client_id:o,client_name:t.client_name??"Dynamically registered MCP client",redirect_uris:t.redirect_uris,grant_types:Pu(t.grant_types),response_types:["code"],scope:M,token_endpoint_auth_method:t.token_endpoint_auth_method,client_id_issued_at:s},p={clientId:o,clientName:String(d.client_name),redirectUris:t.redirect_uris,tokenEndpointAuthMethod:t.token_endpoint_auth_method,createdAt:x(r),clientExpiresAt:x(a)};if(t.token_endpoint_auth_method!=="none"){let g=Pe();p.hashedClientSecret=await E(g),p.clientSecretExpiresAt=x(a),d.client_secret=g,d.client_secret_expires_at=u,d.client_secret_issued_at=s}if((await A().registerClient(p)).kind==="already_exists")throw R("invalid_request","OAuth client is already registered.");return d}n(Ou,"registerDownstreamClient");function zu(e){return L`<form class="actions" method="post" action="/oauth/setup" ${e.submitOnceAttrs}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate >Cancel</button><button class="button button--primary" type="submit" name="decision" value="approve" ${e.authorizeAttrs} >Authorize</button></form>`}n(zu,"renderActions");var Tk=ze('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="4.6" x2="8" y2="8.4"/><circle cx="8" cy="11" r=".7" fill="currentColor" stroke="none"/></svg>');var Pk=ze('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),Ok=ze('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>');var zk=ze('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var Gy="data:,",Eu=L`data-submit-once="true" onsubmit="if (this.dataset.submitted === 'true') return false; this.dataset.submitted = 'true'; setTimeout(() => this.querySelectorAll('button').forEach((button) => { button.disabled = true; }), 0);"`,Mu=L`data-activate-once="true" onclick="if (this.dataset.activated === 'true') return false; this.dataset.activated = 'true'; this.setAttribute('aria-disabled', 'true'); this.style.pointerEvents = 'none';"`;function $y(e,t){if(e)try{let r=new URL(t).origin,o=new URL(e,r);return o.origin!==r||!o.pathname.startsWith("/auth/connections/")?void 0:o.toString()}catch{return}}n($y,"safeGatewayConnectHref");function Zy(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}n(Zy,"deriveMode");function Fy(e){return zu({state:e.state,submitOnceAttrs:Eu,authorizeAttrs:tt})}n(Fy,"renderActions");function $o(e,t,r){for(let o of e){if(o.ownerMode!=="user"||o.status!==r)continue;let a=$y(o.connectUrl,t);if(a)return a}}n($o,"firstUserConnectHref");function Ky(e){let t=e.connectHref?L`<a class="button button--primary" href="${e.connectHref}" ${Mu}>Connect</a>`:L`<button class="button button--primary" type="button" disabled aria-disabled="true">Connect</button>`;return L`<form class="actions" method="post" action="/oauth/setup" ${Eu}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate>Cancel</button>${t}</form>`}n(Ky,"renderSetupActions");function Wy(e){return e?L`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${Mu}>Re-connect<span class="tooltip" tabindex="0" aria-label="Reset or change how the gateway connects to the upstream service, including changing scopes.">?</span></a></span>`:tt}n(Wy,"renderReconnectAction");function Zo(e){let t=Zy(e.upstreams),r=$o(e.upstreams,e.gatewayOrigin,"not_connected"),o=$o(e.upstreams,e.gatewayOrigin,"reconsent_required"),a=$o(e.upstreams,e.gatewayOrigin,"active"),s=t==="setup"?r??o:void 0,u=L`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>`,d=t==="setup"?L`<footer class="card__footer">${Ky({state:e.state,connectHref:s})}</footer>`:L`<footer class="card__footer">${Wy(a)}${Fy({state:e.state})}</footer>`;return At(It({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:Gy,styles:vt,headerIcon:tt,heading:"MCP Gateway",subhead:tt,body:u,footer:d}))}n(Zo,"renderConsentPage");function Jy(e){try{return new URL(e).host}catch{return}}n(Jy,"safeUrlHost");function Vy(e){if(e.mode==="user-oauth"||e.mode==="shared-oauth")return e.oauth.scopes}n(Vy,"readOAuthScopes");function qu(e){return e!==void 0&&e.length>0}n(qu,"hasItems");function Yy(e){let t=e.serverInfo?.icons;return qu(t)?t:void 0}n(Yy,"readServerIcons");async function Xy(e){if(!(e.returnTo===void 0||!e.isUserOwned))return xo({requestUrl:e.requestUrl,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:e.registeredConnection.upstreamServerId,authProfileId:e.registeredConnection.authProfileId,operationId:e.route.operationId,returnTo:e.returnTo})}n(Xy,"readConnectUrl");function rt(e,t){return t===void 0?{}:{[e]:t}}n(rt,"optionalRequirementField");function Qy(e){return e.isUserOwned?Ga(e.connection):{connected:!0,status:"active"}}n(Qy,"readSetupConnectionStatus");function ew(e){let t=Vy(e);return qu(t)?t:void 0}n(ew,"readScopesRequested");function tw(e){return e.isUserOwned&&"updatedAt"in e.connectionStatus&&e.connectionStatus.updatedAt!==void 0?e.connectionStatus.updatedAt:void 0}n(tw,"readUpdatedAt");function rw(){return{tools:[],prompts:[],resources:[]}}n(rw,"readRouteCapabilities");async function nw(e){let{authConfig:t,authMode:r,description:o,displayName:a,mcpUrl:s,upstreamServerId:u,authProfileId:d}=e.registeredConnection,p=qr(r),h=p==="user",g=Qy({connection:e.connection,isUserOwned:h}),D=await Xy({...e,connected:g.connected,isUserOwned:h});return{upstreamServerId:u,authProfileId:d,authMode:r,ownerMode:p,upstreamDisplayName:a,status:g.status,connected:g.connected,capabilities:rw(),...rt("description",o),...rt("transportHost",Jy(s)),...rt("scopesRequested",ew(t)),...rt("serverIcons",Yy(e.registeredConnection)),...rt("connectUrl",D),...rt("updatedAt",tw({connectionStatus:g,isUserOwned:h})),...rt("expiresAt",e.connection?.expiresAt)}}n(nw,"buildSetupRequirement");function Hu(e){let t=ye().byOperationId.get(e);if(!t)throw R("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}n(Hu,"requireRoute");async function Fo(e){let t=Hu(e.transaction.operationId),r=gt(e.transaction.principal.subjectId),o=[],a=new Map,s=t.connection;if(s===void 0)return[];qr(s.authMode)==="user"&&(a.set(s,o.length),o.push({owner:r,upstreamServerId:s.upstreamServerId,authProfileId:s.authProfileId}));let u=await A().batchGetUpstreamConnections(o),d=[],p=qr(s.authMode)==="user",h=a.get(s);return d.push(await nw({connection:p&&h!==void 0?u[h]:void 0,registeredConnection:s,route:t,requestUrl:e.requestUrl,returnTo:e.returnTo,transaction:e.transaction,userOwner:r})),d}n(Fo,"requirementsForSetup");function ow(e){return e.route.connection?.displayName??e.route.operationId}n(ow,"readRouteDisplayName");async function Ko(e){let t=Hu(e.transaction.operationId),r=ow({route:t}),o=await A().readClient({clientId:e.transaction.clientId}),a=o.kind==="found"?o.client:void 0,s={gatewayOrigin:P(e.requestUrl),routeDisplayName:r,clientDisplayName:a?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},u=t.connection?.description;return u!==void 0&&(s.routeDescription=u),s}n(Ko,"consentContext");function Wo(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}n(Wo,"hasUnresolvedUserUpstream");var iw=["mcp_user"],aw="dev-browser-user",sw=["resource is required for /oauth/authorize.","MCP clients should start at the MCP server URL and follow its WWW-Authenticate resource_metadata link.","If your client reached this endpoint directly, use /oauth/authorize/mcp/{operationId} or add resource={protected resource URI from protected-resource metadata}."].join(" "),cw=i.object({response_type:i.literal("code"),client_id:i.string().min(1),redirect_uri:i.string().min(1),resource:i.url(),code_challenge:i.string().min(43),code_challenge_method:xr,state:i.string().min(1).optional(),scope:i.literal(M).default(M)}),uw=i.enum(["continue","approve","cancel"]).default("continue"),dw=i.object({state:i.string().min(1),decision:uw}),Ge=class extends Error{static{n(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription}};function Du(e){return typeof e=="string"&&e.length>0?e:void 0}n(Du,"readQueryString");function pw(e){let t=Array.from(ye().byOperationId.values());if(t.length!==1)return;let r=t[0];if(r!==void 0)return ht(r.operationId,e.url)}n(pw,"inferSingleRouteResource");function lw(e,t){let r=Du(e.query.resource);if(t===void 0){if(r!==void 0)return r;let a=pw(e);if(a!==void 0)return a;throw new S("invalid_target",sw)}let o=ht(t,e.url);if(r===void 0||r===o)return o;throw new S("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}n(lw,"requireAuthorizeResource");async function mw(e,t){let r={};t!==void 0&&(r.context=t);let o=await Vr(e,r);if(o.principal)return{principal:o.principal};if(!e.user)return o.evictCookie===void 0?{}:{setCookie:o.evictCookie};let a=uu(e);return{principal:a,setCookie:await Yr({principal:a,requestUrl:e.url})}}n(mw,"resolveBrowserPrincipal");async function hw(e,t){let r={};t!==void 0&&(r.context=t);let o=await Vr(e,r);if(!o.principal)throw R("authentication_required","Authorization setup requires a current browser session.");return o.principal}n(hw,"requireSetupPrincipal");function ju(e){return`/oauth/setup?state=${encodeURIComponent(e)}`}n(ju,"buildSetupReturnTo");async function Lu(e){let t=await Fo({transaction:e.transaction,requestUrl:e.requestUrl,returnTo:ju(e.csrfToken)}),r=await Ko({transaction:e.transaction,requestUrl:e.requestUrl}),o={kind:"setup_page",html:Zo({state:e.csrfToken,operationId:e.transaction.operationId,upstreams:t,...r})};return e.setCookie!==void 0&&(o.setCookie=e.setCookie),o}n(Lu,"renderSetup");function fw(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}n(fw,"toAuthorizationTransactionClient");async function Jo(e,t={}){let r=cw.parse({...e.query,resource:lw(e,t.operationId),state:Du(e.query.state)}),o=cr(r.scope);Ut(r.redirect_uri,"invalid_request","authorize");let a=new Date,s=J.parse(r.client_id),u=await Qr(r.client_id,a);Tu(u,r.redirect_uri);try{let d=Tt(e.url,r.resource),p=fw(u);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:s,operationId:d.operationId,scope:o,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved"),t.context&&I(t.context,{eventType:v.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:d.operationId,attributes:{clientId:s,scope:o,responseType:r.response_type}});let h={clientId:u?.clientId??s,...p===void 0?{}:{client:p},redirectUri:r.redirect_uri,resource:r.resource,operationId:d.operationId,scope:o,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state}},{principal:g,setCookie:D}=await mw(e,t.context);if(!g){let ne=await xu({transaction:h,requestUrl:e.url,now:a});t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:s,operationId:d.operationId},"Downstream OAuth authorize: redirecting to browser login (no session)");let Se={kind:"redirect",location:ne.browserLoginUrl};return D!==void 0&&(Se.setCookie=D),Se}let k=await Au({transaction:h,principal:g,now:a});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:s,operationId:d.operationId,subjectId:g.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),t.context&&I(t.context,{eventType:v.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:d.operationId,attributes:{clientId:s,scope:o,responseType:r.response_type,subjectId:g.subjectId}}),Lu({transaction:k.transaction,csrfToken:k.csrfToken,requestUrl:e.url,setCookie:D})}catch(d){throw gw({redirectUri:r.redirect_uri,clientState:r.state,cause:d})}}n(Jo,"authorizeDownstreamClient");function gw(e){if(e.cause instanceof Ge)return e.cause;let t=yw(e.cause);return t?new Ge({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}n(gw,"toDownstreamAuthorizeRedirectError");function yw(e){if(e instanceof S)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof i.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}n(yw,"mapToOAuthRedirectError");async function Bu(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let h=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,g=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...h===void 0?{}:{idpErrorDescription:h},...g===void 0?{}:{idpErrorUri:g}},"Identity provider redirected browser-login callback with an error"),R("provider_access_denied",h??"The delegated browser login was not completed.")}let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),R("oauth_state_invalid","Browser login callback is missing state.");let a=await Do(o),s={request:e,stateId:a.stateId};t.context!==void 0&&(s.context=t.context);let u=await du(s),d=await vu({browserLoginStateToken:o,principal:u}),p=await Lu({transaction:d.transaction,csrfToken:d.csrfToken,requestUrl:e.url});return p.setCookie=await Yr({principal:u,requestUrl:e.url}),p}n(Bu,"completeBrowserLoginCallback");async function Nu(e){let t=K(),r=new URL(e.url);if(!Z(r))throw R("forbidden","Local browser login is only available on loopback HTTP origins.");let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw R("oauth_state_invalid","Local browser login is missing state.");let a=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:"/oauth/callback",P(e.url)),s=new URL(P(e.url)).origin;if(a.origin!==s||a.pathname!=="/oauth/callback")throw R("oauth_callback_mismatch","Local browser login redirect_uri must target this gateway's /oauth/callback route.");a.searchParams.set("state",o);let u={subjectId:q.parse(aw),roles:iw};return{kind:"redirect",location:a,setCookie:await Yr({principal:u,requestUrl:e.url})}}n(Nu,"completeLocalDevBrowserLogin");function ww(e){let t=e.method==="POST"?e.body:e.query;return dw.parse(t)}n(ww,"readSetupContinueRequest");async function Gu(e){let{state:t,decision:r}=ww({method:e.request.method,query:e.request.query,body:e.body}),o=new Date,a=await Bo({csrfToken:t,now:o}),s=await hw(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await Uu({csrfToken:t,currentBrowserPrincipal:s,now:o})};let u=await Iu({csrfToken:t,currentBrowserPrincipal:s,now:o}),d=await Fo({transaction:u,requestUrl:e.request.url,returnTo:ju(t)});if(r==="approve"&&Wo(d)&&await bu({csrfToken:t,currentBrowserPrincipal:s,now:o}),Wo(d)){let p=await Ko({transaction:u,requestUrl:e.request.url});return{kind:"setup_page",html:Zo({state:t,operationId:u.operationId,upstreams:d,...p})}}return{kind:"redirect",location:await ku({csrfToken:t,currentBrowserPrincipal:s,now:o})}}n(Gu,"continueDownstreamAuthorizeSetup");z();import{createLocalJWKSet as Sw,decodeJwt as Rw,errors as ur,jwtVerify as _w}from"jose";var bw=new Set(["authorization_code","refresh_token"]),Cw="urn:ietf:params:oauth:client-assertion-type:jwt-bearer",xw=1e4,Aw=32*1024,vw=2,$u=i.object({client_id:i.string().min(1).optional(),client_secret:i.string().min(1).optional(),client_assertion_type:i.string().min(1).optional(),client_assertion:i.string().min(1).optional()}),Iw=i.discriminatedUnion("grant_type",[$u.extend({grant_type:i.literal("authorization_code"),code:i.string().min(1),redirect_uri:i.string().min(1),code_verifier:Ar,resource:i.url().optional(),scope:i.literal(M).optional()}),$u.extend({grant_type:i.literal("refresh_token"),refresh_token:i.string().min(1),resource:i.url().optional(),scope:i.literal(M).optional()})]);function kw(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!bw.has(t)))throw new S("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}n(kw,"assertSupportedGrantType");var Uw=i.object({token:i.string().min(1),client_id:i.string().min(1).optional(),token_type_hint:i.string().optional(),client_secret:i.string().min(1).optional(),client_assertion_type:i.string().min(1).optional(),client_assertion:i.string().min(1).optional()}),Tw=i.object({keys:i.array(i.record(i.string(),i.unknown())).min(1)}).passthrough();function Zu(){return K().gateway.accessTokenTtlSeconds}n(Zu,"readAccessTokenTtlSeconds");function Pw(){return K().gateway.refreshTokenTtlSeconds}n(Pw,"readRefreshTokenTtlSeconds");function Ow(e,t){let r=Zu(),o=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),a=Math.min(r,o);return{expiresAt:x(Ue(e,a)),expiresIn:a}}n(Ow,"calculateAccessTokenExpiresAt");function Fu(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new S("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new S("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new S("invalid_client","Malformed HTTP Basic client authentication.")}}n(Fu,"readBasicClientSecret");function Ku(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new S("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t!==void 0)return t;if(e.clientAssertion!==void 0){try{let r=Rw(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new S("invalid_client","Malformed private_key_jwt client assertion.")}throw new S("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new S("invalid_client","Client authentication or client_id is required.")}n(Ku,"resolveAuthenticatedClientId");function zw(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new S("invalid_request","Use only one client authentication method per request.");return e.basicClientSecret!==void 0?{clientSecret:e.basicClientSecret,clientSecretSource:"basic"}:e.bodyClientSecret!==void 0?{clientSecret:e.bodyClientSecret,clientSecretSource:"post"}:{}}n(zw,"resolveClientSecretInput");function Ew(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}n(Ew,"hasClientAssertion");function Mw(e){if(e.requestUrl===void 0)throw new S("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(e.pathname,e.requestUrl);return t.search="",t.hash="",t.toString()}n(Mw,"buildEndpointAudience");function qw(e){return e instanceof ur.JWTExpired?"expired":e instanceof ur.JWTClaimValidationFailed?"claim":e instanceof ur.JWSSignatureVerificationFailed?"signature":e instanceof ur.JWKSNoMatchingKey?"jwks_no_match":e instanceof ur.JWTInvalid?"invalid":e instanceof i.ZodError?"schema":"other"}n(qw,"readJwtFailureKind");async function Hw(e){let{response:t,json:r}=await uc(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:vw,maxResponseBytes:Aw,timeoutMs:xw});if(!t.ok)throw new S("invalid_client","Client JWKS could not be fetched.");return Tw.parse(r)}n(Hw,"fetchClientJwks");async function Dw(e){if(e.clientAssertionType!==Cw||e.clientAssertion===void 0)throw new S("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=J.parse(e.clientId),r=await Qr(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new S("invalid_client","Client is not registered for private_key_jwt authentication.");let o=r.metadata.jwks_uri;if(o===void 0)throw new S("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let a=Mw({requestUrl:e.requestUrl,pathname:e.endpointPathname});try{let s=await Hw({jwksUri:o,context:e.context});await _w(e.clientAssertion,Sw(s),{issuer:t,subject:t,audience:a,currentDate:e.now})}catch(s){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:qw(s)},"OAuth private_key_jwt client authentication failed"),new S("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}n(Dw,"verifyPrivateKeyJwtClientAssertion");async function jw(e){let t=J.parse(e.clientId);return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await E(e.clientSecret)}}n(jw,"buildRuntimeHttpClientAuth");async function Wu(e){if(Ew({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new S("invalid_request","Use only one client authentication method per request.");return Dw(e)}let t=zw({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return jw({clientId:e.clientId,...t})}n(Wu,"resolveRuntimeHttpClientAuth");async function Ju(e){kw(e.body);let t=Iw.parse(e.body),r=Fu(e.authorizationHeader),o=Ku({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date,s=await Wu({clientId:o,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,endpointPathname:"/oauth/token",now:a,context:e.context});return Lw({parsed:t,clientId:o,clientAuth:s,now:a,requestUrl:e.requestUrl,context:e.context})}n(Ju,"exchangeDownstreamToken");async function Lw(e){if(e.parsed.grant_type==="authorization_code"){Ut(e.parsed.redirect_uri,"invalid_request","token"),cr(e.parsed.scope),e.parsed.resource!==void 0&&Tt(e.requestUrl??e.parsed.resource,e.parsed.resource);let u=Pe(),d=Pe(),p=x(Ue(e.now,Pw())),h=Ow(e.now,p),g=await A().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await E(e.parsed.code),redirectUri:e.parsed.redirect_uri,...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},codeChallenge:await Ds(e.parsed.code_verifier),currentRefreshTokenHash:await E(u),accessTokenHash:await E(d),grantExpiresAt:p,accessTokenExpiresAt:h.expiresAt,now:x(e.now)});if(g.kind==="invalid_client")throw new S("invalid_client","Client authentication failed.");if(g.kind==="resource_mismatch")throw new S("invalid_target","Token request resource must match the authorization code resource.");if(g.kind!=="exchanged")throw new S("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&I(e.context,{eventType:v.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:d,token_type:"Bearer",expires_in:h.expiresIn,refresh_token:u,scope:g.grant.scope,resource:g.grant.resource}}cr(e.parsed.scope),e.parsed.resource!==void 0&&Tt(e.requestUrl??e.parsed.resource,e.parsed.resource);let t=Pe(),r=Pe(),o=x(Ue(e.now,Zu())),a=await A().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:await E(e.parsed.refresh_token),nextRefreshTokenHash:await E(t),accessTokenHash:await E(r),...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},accessTokenExpiresAt:o,now:x(e.now)});if(a.kind==="invalid_client")throw new S("invalid_client","Client authentication failed.");if(a.kind==="resource_mismatch")throw new S("invalid_target","Token request resource must match the refresh token grant resource.");if(a.kind!=="rotated")throw new S("invalid_grant","Refresh token is invalid, expired, or revoked.");Tt(e.requestUrl??a.grant.resource,a.grant.resource);let s=a.accessToken.expiresAt;return e.context&&(I(e.context,{eventType:v.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),I(e.context,{eventType:v.MCP_OAUTH_TOKEN_REFRESH_ROTATED,outcome:"success",attributes:{clientId:e.clientId}})),{access_token:r,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(s).getTime()-e.now.getTime())/1e3)),refresh_token:t,scope:a.grant.scope,resource:a.grant.resource}}n(Lw,"exchangeDownstreamTokenWithRuntimeHttp");async function Vu(e){let t=Uw.parse(e.body),r=Fu(e.authorizationHeader),o=Ku({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date;if((await A().revokeOAuthToken({clientAuth:await Wu({clientId:o,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,endpointPathname:"/oauth/revoke",now:a,context:e.context}),tokenHash:await E(t.token),now:x(a)})).kind==="invalid_client")throw new S("invalid_client","Client authentication failed.");e.context?.log.info({event:"oauth_token_revoked",clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed"),e.context&&I(e.context,{eventType:v.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}n(Vu,"revokeDownstreamToken");var Bw=64*1024,Nw=16*1024,Gw="text/html; charset=utf-8";function $w(e){let t={};for(let[r,o]of e.entries())t[r]=o;return t}n($w,"formDataToObject");async function Zw(e){return ou(e,{maxBytes:Bw,label:"Request body"})}n(Zw,"readJsonBody");async function Vo(e){return $w(await iu(e,{maxBytes:Nw,label:"Request body"}))}n(Vo,"readFormBody");async function Yu(e,t,r){let o=de(r),a=r instanceof i.ZodError?en(r):void 0,s={code:o??(r instanceof i.ZodError?"invalid_request":"internal_server_error")};return a!==void 0&&(s.detail=a),De(e,t,s)}n(Yu,"handleProblem");function dr(e){let t=new Headers(e.headers);t.set("cache-control","no-store"),t.set("pragma","no-cache");let r={error:e.error};return e.errorDescription!==void 0&&(r.error_description=e.errorDescription),Response.json(r,{status:e.status??400,headers:t})}n(dr,"oauthErrorResponse");function Fw(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}n(Fw,"readOAuthProtocolHeaders");function Kw(e,t){let r=W("internal_server_error");return dr({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:Fw(e,t)})}n(Kw,"oauthProtocolErrorResponse");function Xu(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}n(Xu,"readZodOAuthErrorCode");function Ww(e){let t={error:Xu(e)},r=en(e);return r!==void 0&&(t.errorDescription=r),dr(t)}n(Ww,"oauthZodErrorResponse");function Jw(e){let t=de(e);if(t===void 0)return;let r=W(t);if(r.oauthError===void 0)return;let o={error:r.oauthError,status:Yw(r.oauthError)};return r.oauthError==="server_error"?o.errorDescription=r.publicDetail:e instanceof Error?o.errorDescription=e.message:o.errorDescription=r.publicDetail,dr(o)}n(Jw,"oauthGatewayProblemResponse");function Vw(){let t={error:"server_error",status:500,errorDescription:W("internal_server_error").publicDetail};return dr(t)}n(Vw,"oauthFallbackErrorResponse");function Yw(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}n(Yw,"readOAuthStatus");function Yo(e,t={}){return e instanceof Ge?td(e):e instanceof S?Kw(e,t):e instanceof i.ZodError?Ww(e):Jw(e)??Vw()}n(Yo,"oauthProblemResponse");function Xo(e,t){let r=kt(e.url);if(t instanceof Ge)return td(t);if(t instanceof S){let s=W("internal_server_error");return Ce({host:r,kind:Xw(t.errorCode),title:"Authorization failed",detail:t.errorCode==="server_error"?s.publicDetail:t.message,code:t.errorCode,status:t.status})}if(t instanceof i.ZodError)return Ce({host:r,kind:"invalid_request",detail:en(t)??"The authorization request was invalid.",code:Xu(t)});let o=de(t);if(o!==void 0){let s=W(o);return Ce({host:r,kind:ed(o),detail:s.status<500&&t instanceof Error?t.message:s.publicDetail,code:s.oauthError??o,status:s.status})}let a=W("internal_server_error");return Ce({host:r,kind:"internal_error",detail:a.publicDetail,code:"server_error",status:a.status})}n(Xo,"browserOAuthProblemResponse");function Qu(e,t){let r=kt(e.url),o=de(t);if(o!==void 0){let s=W(o);return Ce({host:r,kind:ed(o),detail:s.status<500&&t instanceof Error?t.message:s.publicDetail,code:o,status:s.status})}if(t instanceof i.ZodError)return Ce({host:r,kind:"invalid_request",detail:en(t)??"The authorization request was invalid.",code:"invalid_request"});let a=W("internal_server_error");return Ce({host:r,kind:"internal_error",detail:a.publicDetail,code:"internal_server_error",status:a.status})}n(Qu,"browserGatewayProblemResponse");function Xw(e){return e==="server_error"?"internal_error":"invalid_request"}n(Xw,"readOAuthBrowserErrorKind");function ed(e){if(W(e).status>=500)return"internal_error";switch(e){case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"configuration_error";case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"upstream_client_registration_required":return"admin_required";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"invalid_request":case"authentication_required":case"forbidden":case"not_found":case"too_many_requests":case"identity_context_missing":return"invalid_request";case"upstream_capability_invocation_failed":case"upstream_capability_unavailable":case"upstream_import_failed":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}n(ed,"readGatewayBrowserErrorKind");function Ee(e,t,r){let o={event:t},a=!1;if(r instanceof S)o.oauthError=r.errorCode,o.status=r.status,ie(o,"error",r);else if(r instanceof Ge)o.oauthError=r.errorCode,ie(o,"error",r);else if(r instanceof i.ZodError){o.code="invalid_request",ie(o,"error",r);let s=r.issues[0];s&&(o.zodPath=s.path.join("."))}else{let s=de(r);if(s!==void 0){let u=W(s);o.code=s,o.status=u.status,u.oauthError!==void 0&&(o.oauthError=u.oauthError),a=u.status>=500||u.oauthError==="server_error",ie(o,"error",r)}else a=!0,ie(o,"error",r)}if(a){let s=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(o,s.message)}else e.log.warn(o,"OAuth handler rejected the request")}n(Ee,"logUnexpectedOAuthHandlerError");function td(e){let t;try{t=new URL(e.redirectUri)}catch{return dr({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}n(td,"downstreamAuthorizeRedirectErrorResponse");function en(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}n(en,"formatZodErrorDetail");function Qw(e,t){let r={event:"browser_login_callback_failed",code:de(t)??"invalid_request"};ie(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}n(Qw,"logBrowserLoginCallbackFailure");function rd(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(null,{status:302,headers:t})}n(rd,"redirectResultResponse");function tn(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":Gw,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(e.html,{status:200,headers:t})}return rd(e)}n(tn,"authorizeResultResponse");async function nd(e,t){try{return Response.json(Bn(e.url))}catch(r){return Ee(t,"oauth_authorization_server_metadata_failed",r),Yu(e,t,r)}}n(nd,"authorizationServerMetadataHandler");async function od(e,t){try{let r=G.parse(e.params.operationId),o=He(r);return Response.json(Aa({operationId:o.operationId,requestUrl:e.url}))}catch(r){return Ee(t,"oauth_authorization_server_metadata_failed",r),Yu(e,t,r)}}n(od,"scopedAuthorizationServerMetadataHandler");async function id(e,t){try{let r=await Ou(await Zw(e)),o=r,a=typeof o.client_id=="string"?o.client_id:void 0,s=typeof o.client_name=="string"?o.client_name:void 0,u=Array.isArray(o.redirect_uris)?o.redirect_uris.length:void 0,d=typeof o.token_endpoint_auth_method=="string"?o.token_endpoint_auth_method:void 0;return t.log.info({event:"oauth_dcr_client_registered",clientId:a,clientName:s,redirectUriCount:u,tokenEndpointAuthMethod:d},"OAuth Dynamic Client Registration completed"),I(t,{eventType:v.MCP_OAUTH_CLIENT_REGISTERED,outcome:"success",clientName:s,attributes:{clientId:a,redirectUriCount:u,tokenEndpointAuthMethod:d}}),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return Ee(t,"oauth_register_failed",r),Yo(r)}}n(id,"registerHandler");async function ad(e,t){try{return tn(await Jo(e,{context:t}))}catch(r){return Ee(t,"oauth_authorize_failed",r),Xo(e,r)}}n(ad,"authorizeHandler");async function sd(e,t){try{let r=G.parse(e.params.operationId),o=He(r);return tn(await Jo(e,{operationId:o.operationId,context:t}))}catch(r){return Ee(t,"oauth_authorize_scoped_failed",r),Xo(e,r)}}n(sd,"scopedAuthorizeHandler");async function cd(e,t){try{let r=await Bu(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),tn(r)}catch(r){return Qw(t,r),Qu(e,r)}}n(cd,"callbackHandler");async function ud(e,t){try{return rd(await Nu(e))}catch(r){return Ee(t,"oauth_dev_login_failed",r),Xo(e,r)}}n(ud,"devLoginHandler");async function dd(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await Gu({request:e,body:e.method==="POST"?await Vo(e):void 0,context:t});return tn(r)}catch(r){return Ee(t,"oauth_setup_failed",r),Qu(e,r)}}n(dd,"setupHandler");async function pd(e,t){try{return Response.json(await Ju({body:await Vo(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return Ee(t,"oauth_token_failed",r),Yo(r)}}n(pd,"tokenHandler");async function ld(e,t){try{return await Vu({body:await Vo(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return Ee(t,"oauth_revoke_failed",r),Yo(r)}}n(ld,"revokeHandler");var eS={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},md=new qe("upstream-request");function tS(e){let t=md.get(e);if(!t)throw new re("Upstream request context has not been set");return t}n(tS,"readUpstreamRequestContext");function rS(e,t){return t.some(r=>r===e)}n(rS,"requestContextMatchesKind");function nS(e){return typeof e=="string"?[e]:e}n(nS,"toExpectedKinds");function Pt(e,t){md.set(e,t)}n(Pt,"setUpstreamRequestContext");function pr(e,t){let r=tS(e),o=nS(t);if(!rS(r.kind,o)){let a=eS[o[0]];throw new re(`${a} request context has not been set`)}return r}n(pr,"requireUpstreamRequestContext");function hd(e){return L`<p data-gateway-error-code="${e.code}">${e.body}</p>`}n(hd,"renderBrowserResult");var oS="text/html; charset=utf-8",iS="none";function aS(e){let t=Kr(e.host);return It({title:e.title,iconHref:t,styles:vt,headerIcon:Wr({iconHref:t,fallbackIconHref:Fr}),heading:e.title,subhead:"",body:hd({body:e.body,code:e.code??iS}),footer:""})}n(aS,"browserResultHtml");function sS(e,t=200){return new Response(At(e),{status:t,headers:{"content-type":oS,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(sS,"browserResultResponse");function fd(e){return sS(aS(e))}n(fd,"browserConnectionSuccessResponse");function rn(e,t){let r=ma(t);return Ce({host:e,kind:cS(t),detail:r.body,code:t})}n(rn,"browserConnectionFailureResponse");function cS(e){switch(e){case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed"}}n(cS,"readCallbackFailureBrowserErrorKind");var uS=["callback_authorization_code","callback_provider_error","callback_invalid"];function dS(e){return"cause"in e?e.cause:void 0}n(dS,"readErrorCause");function pS(e){return e.stack?.split(`
32
- `).slice(1,4).map(t=>t.trim()).join(" | ")}n(pS,"readFirstStackFrame");function gd(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=pS(r))}n(gd,"addErrorAttributes");function Qo(e){if(!(e instanceof w))return;let t=e.extensionMembers?.[y];return Ie(t)?t:void 0}n(Qo,"readRuntimeGatewayCode");function lS(e,t,r){switch(t.kind){case"callback_provider_error":return e.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:t.upstreamServerId,providerError:t.error,...t.errorDescription===void 0?{}:{providerErrorDescription:t.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),I(e,{eventType:v.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:t.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:t.error,errorDescription:t.errorDescription}}),rn(r,"provider_access_denied");case"callback_invalid":return e.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:t.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),rn(r,"oauth_state_invalid");case"callback_authorization_code":return t}}n(lS,"requireAuthorizationCallbackRequest");function mS(e,t){I(e,{eventType:v.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}n(mS,"emitCallbackReceivedAnalyticsEvent");function hS(e,t){I(e,{eventType:v.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}n(hS,"emitTokenExchangeSucceededAnalyticsEvent");function fS(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return fd({host:kt(e.url),title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}n(fS,"buildSuccessfulCallbackResponse");function gS(e){let t={detail:e instanceof Error?e.message:void 0};return gd(t,"error",e),e instanceof Error&&gd(t,"cause",dS(e)),t}n(gS,"buildTokenExchangeFailureAttributes");function yS(e){I(e.context,{eventType:v.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:Qo(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:gS(e.error)})}n(yS,"emitTokenExchangeFailedAnalyticsEvent");function wS(e,t){let r=Qo(t);return rn(e,ki(r)?r:"upstream_token_exchange_failed")}n(wS,"tokenExchangeFailureResponse");async function ei(e,t){let r=pr(t,uS),o=kt(e.url),a=lS(t,r,o);if(a instanceof Response)return a;mS(t,a);try{let s=await Kc({request:e,callbackRequest:a});return hS(t,s),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:s.upstreamServerId,operationId:s.operationId,authProfileId:s.authProfileId,ownerMode:s.ownerMode},"Upstream OAuth token exchange completed; user connection established"),fS(e,s)}catch(s){let u={event:"upstream_oauth_token_exchange_failed",code:Qo(s)??"upstream_token_exchange_failed",upstreamServerId:a.upstreamServerId};return ie(u,"error",s),t.log.warn(u,"Upstream OAuth token exchange failed; user shown connection-failure page"),yS({context:t,callbackRequest:a,error:s}),wS(o,s)}}n(ei,"callbackHandler");function SS(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}n(SS,"clientMetadataProblemDetail");async function yd(e,t){let r=pr(t,"connect"),o=await Fc({request:e,connectRequest:r});if(I(t,{eventType:v.MCP_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:o.operationId,upstreamServerTitle:o.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:o.authProfileId,operationId:o.operationId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),r.redirect)return Response.redirect(o.authUrl,302);let a=await Gr({requestUrl:e.url,owner:o.owner,initiatedBySubjectId:o.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:o.authProfileId,upstreamDisplayName:o.upstreamDisplayName,operationId:o.operationId,subject:"MCP route",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(a,{status:428})}n(yd,"connectHandler");async function wd(e,t){let r=pr(t,"client_metadata");try{let o=Pc(e.url),a=Oc(o,r.upstreamServerId,r.authProfileId);return Response.json(a)}catch(o){if(!(o instanceof _))throw o;let a=o instanceof Error?o.message:String(o);return t.log.warn({event:"oauth_client_metadata_request_failed",upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:a},"Failed to serve OAuth client metadata document for upstream connection"),he.notFound(e,t,{code:"not_found",detail:SS(o)})}}n(wd,"oauthClientMetadataHandler");function $e(e){if(typeof e=="string"&&e.length!==0)return e}n($e,"readOptionalQueryString");function RS(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new re(`Validated path parameter ${t} is missing`);return r}n(RS,"requirePathString");function _S(e){let t=$e(e);return t?G.parse(t):void 0}n(_S,"readOptionalOperationId");function bS(e,t){let r=$e(e);return r?ce.parse(r):mt(t,"user-oauth")}n(bS,"readOptionalAuthProfileId");function CS(e){let t=_S(e);if(!t)throw new w({message:"operationId query parameter is required.",extensionMembers:{[y]:"invalid_request"}});return t}n(CS,"readRequiredOperationId");function xS(e){let t=Pr($e(e));return t===void 0?{}:{returnTo:t}}n(xS,"readOptionalReturnTo");function AS(e){let t=$e(e.query.error_description);return t===void 0?{}:{errorDescription:t}}n(AS,"readOptionalProviderErrorDescription");function vS(e){let t=Re(e.authMode);if(t.connectSupport!=="none")return e;throw new w({message:t.connectUnsupportedDetail??"This upstream does not support browser connection flows.",extensionMembers:{[y]:"invalid_request"}})}n(vS,"requireConnectableRouteAuth");function IS(e,t,r,o){return{kind:"connect",...Zr(e,t),...o===void 0?{}:{returnTo:o},redirect:r}}n(IS,"buildConnectContextForPrincipal");function kS(e,t,r){let o=zr(t),a=Re(e.authMode);if(o.mode!==a.ownerMode)throw new w({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[y]:"oauth_callback_mismatch"}});return{kind:"connect",...e,...t.returnTo===void 0?{}:{returnTo:t.returnTo},owner:o,initiatedBySubjectId:t.initiatedBySubjectId,redirect:r}}n(kS,"buildConnectContextForTicket");async function US(e,t){let r=vS(Vc(t,CS(e.query.operationId))),o=e.query.redirect==="true",a=$e(e.query.browserTicket);if(e.user){if(a)throw new w({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[y]:"invalid_request"}});let u=Fe(e.user,e.url);return IS(r,u,o,xS(e.query.returnTo).returnTo)}if(!a)throw new w({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[y]:"authentication_required"}});let s=await Ic(a);if(s.ownerMode!==r.ownerMode||s.upstreamServerId!==r.upstreamServerId||s.authProfileId!==r.authProfileId||s.operationId!==r.operationId)throw new w({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[y]:"oauth_callback_mismatch"}});return await kc(s),kS(r,s,o)}n(US,"resolveConnectContext");async function TS(e,t,r){let o=oe.parse(RS(e,"connection"));switch(r){case"connect":Pt(t,await US(e,o));return;case"callback":{let a=$e(e.query.error);if(a){Pt(t,{kind:"callback_provider_error",upstreamServerId:o,error:a,...AS(e)});return}let s=$e(e.query.code),u=$e(e.query.state);if(s&&u){Pt(t,{kind:"callback_authorization_code",upstreamServerId:o,code:s,state:u});return}Pt(t,{kind:"callback_invalid",upstreamServerId:o});return}case"client_metadata":Pt(t,{kind:"client_metadata",upstreamServerId:o,authProfileId:bS(e.query.authProfileId,o)});return}}n(TS,"resolveUpstreamRequestInbound");async function PS(e,t,r){try{await TS(e,t,r);return}catch(o){let a=o instanceof w?o.extensionMembers?.[y]:void 0,s=o instanceof Error?o.message:void 0;switch(a){case"invalid_request":case"oauth_callback_mismatch":return he.badRequest(e,t,{code:a,detail:s});case"authentication_required":return he.unauthorized(e,t,{code:a,detail:s});default:throw o}}}n(PS,"applyUpstreamRequestContext");function nn(e,t){return n(async(o,a)=>{let s=await PS(o,a,e);return s||t(o,a)},"wrapped")}n(nn,"withUpstreamRequestContext");var OS={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function zS(){return new Response(null,{status:204,headers:OS})}n(zS,"buildWellKnownPreflightResponse");function ES(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}n(ES,"withWellKnownCorsHeaders");function ti(e){return async(t,r)=>t.method==="OPTIONS"?zS():ES(await e(t,r))}n(ti,"wrapWellKnownHandler");var _d=[{routeName:"oauth_as_metadata",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:ti(nd),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",path:"/.well-known/oauth-authorization-server/mcp/:operationId",methods:["GET","OPTIONS"],handler:ti(od),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",path:"/.well-known/oauth-protected-resource/mcp/:operationId",methods:["GET","OPTIONS"],handler:ti(Ia),corsPolicy:"anything-goes"},{routeName:"oauth_register",path:"/oauth/register",methods:["POST"],handler:id},{routeName:"oauth_authorize",path:"/oauth/authorize",methods:["GET"],handler:ad},{routeName:"oauth_authorize_scoped",path:"/oauth/authorize/mcp/:operationId",methods:["GET"],handler:sd},{routeName:"oauth_callback",path:"/oauth/callback",methods:["GET"],handler:cd},{routeName:"oauth_dev_login",path:"/oauth/dev-login",methods:["GET"],handler:ud},{routeName:"oauth_setup",path:"/oauth/setup",methods:["GET","POST"],handler:dd},{routeName:"oauth_token",path:"/oauth/token",methods:["POST"],handler:pd},{routeName:"oauth_revoke",path:"/oauth/revoke",methods:["POST"],handler:ld},{routeName:"upstream_client_metadata",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:nn("client_metadata",wd)},{routeName:"upstream_connect",path:"/auth/connections/:connection/connect",methods:["GET"],handler:nn("connect",yd)},{routeName:"upstream_callback",path:"/auth/connections/:connection/callback",methods:["GET"],handler:nn("callback",ei)}],MS=_d.filter(e=>!e.routeName.startsWith("upstream_")),qS=_d.filter(e=>e.routeName.startsWith("upstream_"));function bd(e){return e?.some(fn)??!1}n(bd,"hasMcpOAuthRuntimeConfigPolicy");function Cd(e){return e?.some(t=>_r(t.policyType))??!1}n(Cd,"hasMcpTokenExchangePolicy");function xd(e){return bd(e)||Cd(e)}n(xd,"shouldRegisterMcpGatewayInternalRoutes");function HS(e){sa(Pn({routes:e.routes,policies:e.policies}))}n(HS,"initializeMcpGatewayConnectionRegistry");function DS(e){let t=vi(e.policies);if(!t){let r=[...hn].map(o=>`\`${o}\``).join(", ");throw new _(`MCP gateway: could not find an MCP authorization policy in policies.json. Add one of [${r}] and reference it on your MCP routes.`)}return t.config}n(DS,"initializeMcpGatewayOAuthRuntimeConfig");function Sd(e,t,r){return async(o,a)=>{r&&st(a,r());let s=o.method==="OPTIONS",u=Date.now();s||a.log.info({event:`${e}_received`,method:o.method},`MCP gateway: ${e} received`);let d=await t(o,a);return s||a.log.info({event:`${e}_responded`,status:d.status,durationMs:Date.now()-u},`MCP gateway: ${e} responded`),d}}n(Sd,"wrapInternalHandler");function Rd(e,t,r){e.addPluginRoute({path:t.path,methods:t.methods,handler:r,processors:[on],corsPolicy:t.corsPolicy??"none"})}n(Rd,"addInternalRoute");function Ad(e,t){HS(t);let r=bd(t.policies),o=Cd(t.policies),a,s=n(()=>(a===void 0&&(a=DS(t)),a),"readOAuthConfig");if(r)for(let u of MS)Rd(e,u,Sd(u.routeName,u.handler,s));if(o)for(let u of qS)Rd(e,u,Sd(u.routeName,u.handler))}n(Ad,"registerMcpGatewayInternalRoutes");function vd(e){aa(e)}n(vd,"configureLazyMcpGatewayState");var ri=class extends ai{static{n(this,"McpGatewayPlugin")}registerRoutes(t){let r=t.parsedRouteData;if(!r||!xd(r.policies))return;let o={routes:r.routes,policies:r.policies};vd(o),Ad(t.router,o)}};var jS={Allow:"POST"};async function LS(e,t){return e.method==="GET"?he.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},jS):gi(e,t)}n(LS,"McpProxyHandler");export{so as McpAuth0OAuthInboundPolicy,ri as McpGatewayPlugin,ln as McpOAuthInboundPolicy,LS as McpProxyHandler,Oo as McpTokenExchangeInboundPolicy};
27
+ </style></head><body><main class="card"><header class="card__head">${e.headerIcon}<h1 class="card__title">${e.heading}</h1>${e.subhead}</header><div class="card__body">${e.body}</div>${e.footer}</main></body></html>`}n(ve,"renderShell");var lr="zuplo.com";function ei(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(ei,"s2FaviconHref");function Mc(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(Mc,"strictFaviconHref");var bt=ei(lr);function Ct(e){let t=e.toLowerCase();return t===lr||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?ei(lr):Mc(e)}n(Ct,"resolveIconHref");function St(e){return b`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}n(St,"renderShellIcon");var zc="text/html; charset=utf-8";function xe(e){try{return new URL(e).host}catch{return""}}n(xe,"safeHostFromUrl");function $(e){let t=Ct(e.host),r=Dc(e.kind??"authorization_failed");return new Response(Ce(ve({title:e.title??r.title,iconHref:t,styles:Se,headerIcon:St({iconHref:t,fallbackIconHref:bt}),heading:e.title??r.title,subhead:"",body:Qo({code:e.code??"unknown",detail:e.detail,guidance:b`<p class="card__description">${r.guidance}</p>`,action:Hc(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":zc,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n($,"browserErrorPageResponse");function Dc(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(Dc,"readBrowserErrorPagePresentation");function Hc(e){return e===void 0?he:b`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(Hc,"renderAction");var ti="application/json",Bc="application/x-www-form-urlencoded";function vt(e,t){return new y({message:e,extensionMembers:{[w]:"invalid_request"}},t===void 0?void 0:{cause:t})}n(vt,"invalidRequestError");function Lc(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}n(Lc,"normalizeContentType");function jc(e,t){return e===t?!0:t===ti&&e.endsWith("+json")}n(jc,"contentTypeMatches");function Nc(e,t){if(!t||t.length===0)return;let r=Lc(e.headers.get("content-type"));if(!t.some(o=>jc(r,o)))throw vt(`Request body must be ${t.join(" or ")}.`)}n(Nc,"assertExpectedContentType");function Gc(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 vt(`${r} exceeded the maximum allowed size.`)}n(Gc,"assertContentLengthWithinLimit");async function ri(e,t){let r=t.label??"Request body";Nc(e,t.expectedContentTypes),Gc(e,t.maxBytes,r);let o=await $n(e.body,{maxBytes:t.maxBytes,createLimitError:n(()=>vt(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(o)}n(ri,"readBoundedTextBody");async function ni(e,t){let r=await ri(e,{...t,expectedContentTypes:[ti]});try{return JSON.parse(r)}catch(o){throw vt("Request body must be valid JSON.",o)}}n(ni,"readBoundedJsonBody");async function oi(e,t){let r=await ri(e,{...t,expectedContentTypes:[Bc]});return new URLSearchParams(r)}n(oi,"readBoundedFormUrlEncodedBody");z();z();import{errors as ui,jwtVerify as li,SignJWT as pi}from"jose";z();import{errors as $c,jwtVerify as Zc,SignJWT as Fc}from"jose";var mr="zuplo_mcp_session",Kc=d.object({purpose:d.literal("gateway_browser_session"),sub:st,browserLoginOrigin:d.string().min(1),roles:d.array(d.string().min(1)).optional(),exp:d.number().int().positive(),iat:d.number().int().positive().optional()});function Wc(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let o=r.indexOf("=");if(o<0)continue;let i=r.slice(0,o).trim(),a=r.slice(o+1).trim();if(i)try{t.set(i,decodeURIComponent(a))}catch{t.set(i,a)}}return t}n(Wc,"parseCookieHeader");async function ii(){return G({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>re(e,"browser-session"),"derive")})}n(ii,"getBrowserSessionKey");function pr(e){let t=new URL(I(e)),r=[`${mr}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(pr,"buildBrowserSessionEvictionCookie");function Jc(e){let t=new URL(I(e.requestUrl)),r=[`${mr}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(Jc,"serializeSessionCookie");function ai(){return new URL(lt("url")).origin}n(ai,"readBrowserLoginOrigin");function fr(){return D().browserLogin.stateTtlSeconds}n(fr,"readBrowserLoginStateTtlSeconds");function si(e){if(!e.user)throw g("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return ct(e.user,e.url)}n(si,"resolveCurrentRequestPrincipal");async function xt(e,t={}){let r=Wc(e.headers.get("cookie")).get(mr);if(!r)return{};try{let{payload:o}=await Zc(r,await ii(),{algorithms:[M],issuer:T,audience:q}),i=Kc.parse(o);if(i.browserLoginOrigin!==ai())return{evictCookie:pr(e.url)};let a={subjectId:i.sub};return i.roles&&i.roles.length>0&&(a.roles=i.roles),{principal:a}}catch(o){return o instanceof $c.JWTExpired?{evictCookie:pr(e.url)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:o instanceof Error?o.name:"unknown",errorMessage:o instanceof Error?o.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:pr(e.url)})}}n(xt,"readBrowserSession");async function It(e){let t=D().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:ai()};e.principal.roles&&(r.roles=e.principal.roles);let o=await new Fc(r).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await ii());return Jc({value:o,requestUrl:e.requestUrl,ttlSeconds:t})}n(It,"createBrowserSessionCookie");async function ci(e){let t={};e.context!==void 0&&(t.context=e.context);let r=await xt(e.request,t);if(r.principal)return r.principal;let o=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(!o)throw g("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.");let{exchangeFederatedAuthorizationCode:i}=await import("../browser-login-idp-HWMCSYMR.js");return i({code:o,nonce:e.stateId,requestUrl:e.request.url,...e.context===void 0?{}:{context:e.context}})}n(ci,"resolveBrowserLoginCallbackPrincipal");function di(e){let t=D().browserLogin,r=new URL(lt("url")),o=new URL("/oauth/callback",wn(e.requestUrl));return An(r)?(r.searchParams.set("redirect_uri",o.toString()),r.searchParams.set("state",e.state),r):(r.searchParams.set("response_type","code"),r.searchParams.set("client_id",lt("clientId")),r.searchParams.set("redirect_uri",o.toString()),r.searchParams.set("scope",t.scope),r.searchParams.set("state",e.state),r.searchParams.set("nonce",e.nonce),t.audience&&r.searchParams.set("audience",t.audience),r)}n(di,"buildBrowserLoginUrl");var Vc={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},p=class extends Error{static{n(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,o=Vc[t],i){super(r,i),this.name="OAuthProtocolError",this.errorCode=t,this.status=o}};var Yc=5*60,Xc=d.object({purpose:d.literal("gateway_browser_login"),transactionId:Mt,stateId:zt,exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),Qc=d.object({purpose:d.literal("gateway_authorization_setup"),transactionId:Mt,stateId:zt,exp:d.number().int().positive(),iat:d.number().int().positive().optional()});async function mi(){return G({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>re(e,"browser-login"),"derive")})}n(mi,"getBrowserLoginKey");async function fi(){return G({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>re(e,"authorization-csrf"),"derive")})}n(fi,"getCsrfKey");function hi(e){return{now:e.now??new Date,ttlSeconds:fr()}}n(hi,"readPendingTransactionDependencies");function ed(e,t){return e.subjectId===t.subjectId}n(ed,"principalsMatch");function gi(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}n(gi,"toPendingPrincipal");function yi(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,operationId:e.transaction.operationId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:_(e.now),expiresAt:_(F(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw g("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:gi(e.principal)}}n(yi,"createTransactionRecord");async function wi(e){let{id:t,...r}=e.record,o=await R().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(o.kind){case"started":return o.transaction;case"already_exists":throw g("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new p("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new p("invalid_request","redirect_uri is not registered for the client.")}}n(wi,"startPendingTransaction");async function td(e){return new pi({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await mi())}n(td,"signBrowserLoginState");async function _i(e){return new pi({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:Ht()}).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await fi())}n(_i,"signCsrfToken");async function hr(e){try{let{payload:t}=await li(e,await mi(),{algorithms:[M],issuer:T,audience:q}),r=Xc.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof ui.JWTExpired?g("oauth_state_expired","Browser login state has expired.",t):g("oauth_state_invalid","Browser login state could not be verified.",t)}}n(hr,"verifyBrowserLoginStateToken");async function At(e){try{let{payload:t}=await li(e,await fi(),{algorithms:[M],issuer:T,audience:q});return{transactionId:Qc.parse(t).transactionId}}catch(t){throw t instanceof ui.JWTExpired?g("oauth_state_expired","Authorization setup state has expired.",t):g("oauth_state_invalid","Authorization setup state could not be verified.",t)}}n(At,"verifyCsrfToken");function gr(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}n(gr,"pendingStateErrorCode");function rd(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}n(rd,"toPendingAuthorizationGetResult");function nd(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}n(nd,"toPendingAuthorizationAdvanceResult");function yr(e){return e==="principal_mismatch"?"oauth_callback_mismatch":gr(e==="consumed_already"?"consumed_already":e)}n(yr,"setupDecisionErrorCode");async function Ri(e){let t=e.now??new Date,r=await At(e.csrfToken),o=await R().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await C(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:_(t)});if(o.kind!=="marked")throw g(yr(o.kind),"Authorization setup state is invalid, expired, or already used.");return bi({kind:"available",record:o.transaction})}n(Ri,"markSetupApproved");function bi(e){if(e.kind!=="available")throw g(gr(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}n(bi,"requireAwaitingSetup");function od(e){if(!ed(e.currentBrowserPrincipal,e.transaction.principal))throw g("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}n(od,"requireCurrentPrincipalMatches");async function Ci(e){let t=e.now??new Date,r=fr(),o=Dt(),i=Ht(),a=await td({transactionId:o,stateId:i,ttlSeconds:r}),s=yi({id:o,transaction:e.transaction,currentStateHash:await C(a),phase:"awaiting_login",now:t,ttlSeconds:r});if(s.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");let c=await wi({record:s,client:e.transaction.client});if(c.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");return{transaction:c,browserLoginStateToken:a,browserLoginUrl:di({state:a,nonce:i,operationId:s.operationId,requestUrl:e.requestUrl})}}n(Ci,"startAwaitingLogin");async function Si(e){let{now:t,ttlSeconds:r}=hi(e),o=Dt(),i=await _i({transactionId:o,ttlSeconds:r}),a=yi({id:o,transaction:e.transaction,currentStateHash:await C(i),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(a.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");let s=await wi({record:a,client:e.transaction.client});if(s.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:s,csrfToken:i}}n(Si,"startAwaitingSetup");async function vi(e){let{now:t,ttlSeconds:r}=hi(e),o=await hr(e.browserLoginStateToken),i=await _i({transactionId:o.transactionId,ttlSeconds:r}),a=nd(await R().advancePendingAuthorization({transactionId:o.transactionId,expectedPhase:"awaiting_login",currentStateHash:await C(e.browserLoginStateToken),nextStateHash:await C(i),nextPhase:"awaiting_setup",principal:gi(e.principal),now:_(t)}));if(a.kind!=="advanced")throw g(gr(a.kind),"Browser login state is invalid, expired, or already used.");if(a.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:a.record,csrfToken:i}}n(vi,"completeLogin");async function xi(e){let t=await wr(e);return od({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}n(xi,"getSetup");async function wr(e){let t=e.now??new Date,r=await At(e.csrfToken);return bi(rd(await R().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await C(e.csrfToken),now:_(t)})))}n(wr,"getSetupTransaction");async function id(e){let t=await At(e.csrfToken),r=W(),o=_(F(e.now,Yc)),i=await R().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await C(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await C(r),authorizationCodeExpiresAt:o,grantId:xn(),now:_(e.now)});if(i.kind!=="approved")throw g(i.kind==="cancelled"?"oauth_state_invalid":yr(i.kind),"Authorization setup state is invalid, expired, or already used.");let a=new URL(i.transaction.redirectUri);return a.searchParams.set("code",r),i.transaction.clientState&&a.searchParams.set("state",i.transaction.clientState),a}n(id,"createAuthorizationCodeRedirectWithDecision");async function ad(e){let t=await At(e.csrfToken),r=await R().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await C(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:_(e.now)});if(r.kind!=="cancelled")throw g(r.kind==="approved"?"oauth_state_invalid":yr(r.kind),"Authorization setup state is invalid, expired, or already used.");return sd({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}n(ad,"createCancelRedirectWithDecision");function sd(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),t}n(sd,"buildClientCancelRedirect");async function Ii(e){let t=e.now??new Date;return id({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Ii,"approve");async function Ai(e){let t=e.now??new Date;return ad({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Ai,"cancel");z();var cd=1e4,dd=5*1024,ud=2,ld=90*24*60*60,_r=["authorization_code","refresh_token"],Rr=["code"],pd=d.object({client_name:d.string().min(1).optional(),redirect_uris:d.array(d.string().min(1)).min(1),grant_types:d.array(d.enum(_r)).min(1).max(2).optional(),response_types:d.array(d.enum(Rr)).min(1).max(1).optional(),scope:d.literal(P).optional(),token_endpoint_auth_method:Sn.default("none")});function md(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&se(t))&&t.pathname!=="/"}catch{return!1}}n(md,"isCimdClientIdCandidate");function Ie(e,t="invalid_request",r="authorize"){if(fd(e))throw new p(t,"redirect_uris must not include raw whitespace or control characters.");let o;try{o=new URL(e)}catch{throw new p(t,"redirect_uris must be absolute URIs.")}if(o.hash||o.username||o.password)throw new p(t,"redirect_uris must not include credentials or fragments.");let i={source:r},a=bn({url:o,context:i});if(a.kind!=="rejected"){a.mode!=="strict"&&void 0;return}throw new p(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}n(Ie,"assertValidRedirectUri");function fd(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}n(fd,"hasForbiddenRawRedirectUriCharacter");async function hd(e){let{response:t,json:r}=await Fn(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:ud,maxResponseBytes:dd,timeoutMs:cd});if(!t.ok)throw g("invalid_request","CIMD metadata could not be fetched.");let o=vn.parse(r);for(let i of o.redirect_uris)Ie(i,"invalid_request","cimd");if(o.client_id!==e.clientId)throw g("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return o}n(hd,"fetchCimdMetadata");async function gd(e){let t=Gn(e),r=await hd({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}n(gd,"resolveCimdClient");async function Ut(e,t){let r=ee.parse(e);if(md(r)){if(!D().gateway.cimdEnabled)throw new p("invalid_client","OAuth client is not registered.");try{return await gd(r)}catch{throw new p("invalid_client","OAuth client is not registered.")}}let o=await R().readClient({clientId:r});if(o.kind==="found"){let i=o.client,a={kind:"dcr",clientId:r,metadata:{client_id:i.clientId,client_name:i.clientName,redirect_uris:i.redirectUris,token_endpoint_auth_method:i.tokenEndpointAuthMethod}};return i.hashedClientSecret&&(a.hashedClientSecret=i.hashedClientSecret),a}throw new p("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}n(Ut,"resolveClient");function Ui(e,t){if(!e.metadata.redirect_uris.some(r=>In(r,t)))throw g("invalid_request","redirect_uri is not registered for the client.")}n(Ui,"assertRedirectRegistered");function yd(e){let t=ki(e.grant_types),r=e.response_types??[...Rr];if(!wd(t))throw new p("invalid_client_metadata","grant_types must be a subset of authorization_code and refresh_token.");if(!_d(r))throw new p("invalid_client_metadata","response_types must be code.");if(!Rd(e.scope))throw new p("invalid_client_metadata",`Only the ${P} scope is supported.`)}n(yd,"assertSupportedDcrRequest");function ki(e){return e===void 0?[..._r]:Array.from(new Set(e))}n(ki,"normalizeGrantTypes");function wd(e){return e.length===0?!1:e.every(t=>_r.includes(t))}n(wd,"isSupportedGrantTypes");function _d(e){return e.length===Rr.length&&e[0]==="code"}n(_d,"isSupportedResponseTypes");function Rd(e){return e===void 0||e===P}n(Rd,"isSupportedDcrScope");function Ke(e){if(e===void 0||e===P)return P;throw new p("invalid_request",`Only the ${P} scope is supported.`)}n(Ke,"assertSupportedOAuthScope");function Ae(e,t){let r;try{r=new URL(t)}catch{throw new p("invalid_target","resource must be an absolute URI.")}if(r.hash)throw new p("invalid_target","resource must not include a fragment.");if(r.protocol!=="https:"&&!se(r))throw new p("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let o=I(e),i=yn(),a=i?[...i.byOperationId.values()].find(s=>new URL(s.routePath,o).toString()===t):void 0;if(!a)throw new p("invalid_target","resource must match a published MCP route.");return a}n(Ae,"resolveResource");async function Pi(e){let t;try{t=pd.parse(e)}catch(m){if(m instanceof d.ZodError){let v=m.issues.some(L=>L.path[0]==="redirect_uris");throw new p(v?"invalid_redirect_uri":"invalid_client_metadata",m.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:m})}throw m}yd(t);for(let m of t.redirect_uris)Ie(m,"invalid_redirect_uri","dcr");let r=new Date,o=ee.parse(`dcr:${crypto.randomUUID()}`),i=F(r,ld),a=Math.floor(r.getTime()/1e3),s=Math.floor(i.getTime()/1e3),c={client_id:o,client_name:t.client_name??"Dynamically registered MCP client",redirect_uris:t.redirect_uris,grant_types:ki(t.grant_types),response_types:["code"],scope:P,token_endpoint_auth_method:t.token_endpoint_auth_method,client_id_issued_at:a},l={clientId:o,clientName:String(c.client_name),redirectUris:t.redirect_uris,tokenEndpointAuthMethod:t.token_endpoint_auth_method,createdAt:_(r),clientExpiresAt:_(i)};if(t.token_endpoint_auth_method!=="none"){let m=W();l.hashedClientSecret=await C(m),l.clientSecretExpiresAt=_(i),c.client_secret=m,c.client_secret_expires_at=s,c.client_secret_issued_at=a}if((await R().registerClient(l)).kind==="already_exists")throw g("invalid_request","OAuth client is already registered.");return c}n(Pi,"registerDownstreamClient");function Ti(e){return b`<form class="actions" method="post" action="/oauth/setup" ${e.submitOnceAttrs}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate >Cancel</button><button class="button button--primary" type="submit" name="decision" value="approve" ${e.authorizeAttrs} >Authorize</button></form>`}n(Ti,"renderActions");var _h=V('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="4.6" x2="8" y2="8.4"/><circle cx="8" cy="11" r=".7" fill="currentColor" stroke="none"/></svg>');var Rh=V('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),bh=V('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>');var Ch=V('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var bd="data:,",Oi=b`data-submit-once="true" onsubmit="if (this.dataset.submitted === 'true') return false; this.dataset.submitted = 'true'; setTimeout(() => this.querySelectorAll('button').forEach((button) => { button.disabled = true; }), 0);"`,Ei=b`data-activate-once="true" onclick="if (this.dataset.activated === 'true') return false; this.dataset.activated = 'true'; this.setAttribute('aria-disabled', 'true'); this.style.pointerEvents = 'none';"`;function Cd(e,t){if(e)try{let r=new URL(t).origin,o=new URL(e,r);return o.origin!==r||!o.pathname.startsWith("/auth/connections/")?void 0:o.toString()}catch{return}}n(Cd,"safeGatewayConnectHref");function Sd(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}n(Sd,"deriveMode");function vd(e){return Ti({state:e.state,submitOnceAttrs:Oi,authorizeAttrs:he})}n(vd,"renderActions");function br(e,t,r){for(let o of e){if(o.ownerMode!=="user"||o.status!==r)continue;let i=Cd(o.connectUrl,t);if(i)return i}}n(br,"firstUserConnectHref");function xd(e){let t=e.connectHref?b`<a class="button button--primary" href="${e.connectHref}" ${Ei}>Connect</a>`:b`<button class="button button--primary" type="button" disabled aria-disabled="true">Connect</button>`;return b`<form class="actions" method="post" action="/oauth/setup" ${Oi}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate>Cancel</button>${t}</form>`}n(xd,"renderSetupActions");function Id(e){return e?b`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${Ei}>Re-connect<span class="tooltip" tabindex="0" aria-label="Reset or change how the gateway connects to the upstream service, including changing scopes.">?</span></a></span>`:he}n(Id,"renderReconnectAction");function Cr(e){let t=Sd(e.upstreams),r=br(e.upstreams,e.gatewayOrigin,"not_connected"),o=br(e.upstreams,e.gatewayOrigin,"reconsent_required"),i=br(e.upstreams,e.gatewayOrigin,"active"),a=t==="setup"?r??o:void 0,s=b`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>`,c=t==="setup"?b`<footer class="card__footer">${xd({state:e.state,connectHref:a})}</footer>`:b`<footer class="card__footer">${Id(i)}${vd({state:e.state})}</footer>`;return Ce(ve({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:bd,styles:Se,headerIcon:he,heading:"MCP Gateway",subhead:he,body:s,footer:c}))}n(Cr,"renderConsentPage");var Ad=1e4,qi="mcp-session-id",Ud,Mi;function Li(){return{tools:[],prompts:[],resources:[]}}n(Li,"emptyCapabilities");function zi(e){let t=new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":Bt});switch(e.type){case"none":return t;case"bearer_token":return t.set("authorization",`Bearer ${e.token}`),t;case"headers":for(let[r,o]of Object.entries(e.headers))t.set(r,o);return t;case"mcp_oauth_provider":throw new Error("MCP OAuth provider credentials require async headers.")}}n(zi,"buildCredentialHeaders");async function Di(e){if(e.type!=="mcp_oauth_provider")return zi(e);let t=await e.provider.tokens();if(!t)return;let r=zi({type:"none"});return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}n(Di,"buildAsyncCredentialHeaders");function Hi(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(ot.parse({jsonrpc:nt,id:1,method:"initialize",params:{protocolVersion:Bt,capabilities:{},clientInfo:{name:"zuplo-mcp-gateway-readiness",version:"0.0.0"}}}))})}n(Hi,"buildInitializePreflight");async function Sr(e){Nn(e.url);let t=new AbortController,r=setTimeout(()=>t.abort(),Ad);try{let o=new Request(e,{redirect:"manual",signal:t.signal});return Mi?await Mi(o):await Xe.fetch(o)}finally{clearTimeout(r)}}n(Sr,"runPreflight");function vr(e){e.body?.cancel().catch(()=>{})}n(vr,"releasePreflightBody");async function kd(e){let t=e.response.headers.get(qi);if(!t)return;let r=new Headers(e.headers);r.set(qi,t),r.delete("content-type");try{let o=await Sr(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));vr(o)}catch{}}n(kd,"terminatePreflightSession");async function ji(e){let{response:t}=e;return vr(t),t.status>=200&&t.status<300?(await kd(e),{kind:"ready",upstreamStatus:t.status,capabilities:Li()}):t.status===401||t.status===403?{kind:"upstream_auth_rejected",status:t.status,message:"Upstream MCP server rejected the configured credential."}:{kind:"upstream_unavailable",status:t.status,message:"Upstream MCP server did not accept the readiness preflight."}}n(ji,"classifyResponse");function Bi(e){let t={status:e.state==="reconsent_required"?"reconsent_required":"not_connected",connected:!1};return e.nextAction==="admin_setup_required"?{kind:"admin_setup_required",payload:e,connectionStatus:t}:{kind:"connect_required",payload:e,connectionStatus:t}}n(Bi,"connectRequiredResult");async function Pd(e){try{return ji({response:await Sr(e.request),upstreamUrl:e.upstreamUrl,headers:e.headers})}catch(t){return{kind:"upstream_unavailable",message:t instanceof Error?t.message:"Upstream MCP server readiness preflight failed."}}}n(Pd,"classifyPreflight");async function Td(e){let t=e.route.connection;if(t===void 0)return{kind:"ready",upstreamStatus:204,capabilities:Li()};let r=Rt(t.upstreamServerId,e.route.operationId),o=be(r,e.principal),i=e.returnTo===void 0?o:{...o,returnTo:e.returnTo},a=await Re({request:new Request(e.requestUrl),routeAuth:i,preloadedConnection:e.preloadedConnection});if(a.kind==="connect_required")return Bi(a.payload);let s=await Di(a.credential);if(s===void 0)return{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens."};let c=Hi({upstreamUrl:t.mcpUrl,headers:s}),l;try{l=await Sr(c)}catch(v){return{kind:"upstream_unavailable",message:v instanceof Error?v.message:"Upstream MCP server readiness preflight failed."}}if(l.status!==401)return ji({response:l,upstreamUrl:t.mcpUrl,headers:s});vr(l);let h=await Re({request:new Request(e.requestUrl),routeAuth:i,forceRefresh:!0,preloadedConnection:e.preloadedConnection});if(h.kind==="connect_required")return Bi(h.payload);let m=await Di(h.credential);return m===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:Pd({request:Hi({upstreamUrl:t.mcpUrl,headers:m}),upstreamUrl:t.mcpUrl,headers:m})}n(Td,"checkUpstreamRouteReadinessImpl");function Ni(e){return(Ud??Td)(e)}n(Ni,"checkUpstreamRouteReadiness");function Od(e){try{return new URL(e).host}catch{return}}n(Od,"safeUrlHost");function Ed(e){if(e.mode==="user-oauth"||e.mode==="shared-oauth")return e.oauth.scopes}n(Ed,"readOAuthScopes");function Gi(e){return e!==void 0&&e.length>0}n(Gi,"hasItems");function qd(e){let t=e.serverInfo?.icons;return Gi(t)?t:void 0}n(qd,"readServerIcons");async function Md(e){if(!(e.returnTo===void 0||!e.isUserOwned))return nr({requestUrl:e.requestUrl,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:e.registeredConnection.upstreamServerId,authProfileId:e.registeredConnection.authProfileId,operationId:e.route.operationId,returnTo:e.returnTo})}n(Md,"readConnectUrl");function ge(e,t){return t===void 0?{}:{[e]:t}}n(ge,"optionalRequirementField");function zd(e){return e.readiness!==void 0?e.readiness:e.isUserOwned?Dn(e.connection):{connected:!0,status:"active"}}n(zd,"readSetupConnectionStatus");function Dd(e){let t=Ed(e);return Gi(t)?t:void 0}n(Dd,"readScopesRequested");function Hd(e){return e.isUserOwned&&"updatedAt"in e.connectionStatus&&e.connectionStatus.updatedAt!==void 0?e.connectionStatus.updatedAt:void 0}n(Hd,"readUpdatedAt");function Bd(){return{tools:[],prompts:[],resources:[]}}n(Bd,"readRouteCapabilities");async function Ld(e){let{authConfig:t,authMode:r,description:o,displayName:i,mcpUrl:a,upstreamServerId:s,authProfileId:c}=e.registeredConnection,l=ft(r),h=l==="user",m=zd({connection:e.connection,isUserOwned:h,readiness:e.readiness}),v=e.readiness?.connectUrl??await Md({...e,connected:m.connected,isUserOwned:h});return{upstreamServerId:s,authProfileId:c,authMode:r,ownerMode:l,upstreamDisplayName:i,status:m.status,connected:m.connected,capabilities:Bd(),...ge("description",o),...ge("transportHost",Od(a)),...ge("scopesRequested",Dd(t)),...ge("serverIcons",qd(e.registeredConnection)),...ge("connectUrl",v),...ge("updatedAt",Hd({connectionStatus:m,isUserOwned:h})),...ge("expiresAt",e.readiness?.expiresAt??e.connection?.expiresAt)}}n(Ld,"buildSetupRequirement");function $i(e){let t=j().byOperationId.get(e);if(!t)throw g("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}n($i,"requireRoute");async function xr(e){let t=$i(e.transaction.operationId),r=dt(e.transaction.principal.subjectId),o=[],i=new Map,a=t.connection;if(a===void 0)return[];ft(a.authMode)==="user"&&(i.set(a,o.length),o.push({owner:r,upstreamServerId:a.upstreamServerId,authProfileId:a.authProfileId}));let s=await R().batchGetUpstreamConnections(o),c=[],l=ft(a.authMode)==="user",h=i.get(a),m=await Ni({requestUrl:e.requestUrl,route:t,principal:e.transaction.principal,preloadedConnection:l&&h!==void 0?s[h]:void 0,...e.returnTo===void 0?{}:{returnTo:e.returnTo}}),v=(()=>{if("connectionStatus"in m&&m.connectionStatus)return m.connectionStatus})(),L=(m.kind==="connect_required"||m.kind==="admin_setup_required")&&m.payload.authUrl!==void 0?m.payload.authUrl:void 0;return c.push(await Ld({connection:l&&h!==void 0?s[h]:void 0,registeredConnection:a,route:t,requestUrl:e.requestUrl,returnTo:e.returnTo,transaction:e.transaction,userOwner:r,readiness:v===void 0?void 0:{...v,...L===void 0?{}:{connectUrl:L}}})),c}n(xr,"requirementsForSetup");function jd(e){return e.route.connection?.displayName??e.route.operationId}n(jd,"readRouteDisplayName");async function Ir(e){let t=$i(e.transaction.operationId),r=jd({route:t}),o=await R().readClient({clientId:e.transaction.clientId}),i=o.kind==="found"?o.client:void 0,a={gatewayOrigin:I(e.requestUrl),routeDisplayName:r,clientDisplayName:i?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},s=t.connection?.description;return s!==void 0&&(a.routeDescription=s),a}n(Ir,"consentContext");function Ar(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}n(Ar,"hasUnresolvedUserUpstream");var Nd=["mcp_user"],Gd="dev-browser-user",$d=["resource is required for /oauth/authorize.","MCP clients should start at the MCP server URL and follow its WWW-Authenticate resource_metadata link.","If your client reached this endpoint directly, use /oauth/authorize/{routePath} where {routePath} is the published MCP route path without a leading slash and each segment is URL-encoded as needed, for example /oauth/authorize/mcp/linear, or add resource={protected resource URI from protected-resource metadata}."].join(" "),Zd=d.object({response_type:d.literal("code"),client_id:d.string().min(1),redirect_uri:d.string().min(1),resource:d.url(),code_challenge:d.string().min(43),code_challenge_method:Cn,state:d.string().min(1).optional(),scope:d.literal(P).default(P)}),Fd=d.enum(["continue","approve","cancel"]).default("continue"),Kd=d.object({state:d.string().min(1),decision:Fd}),oe=class extends Error{static{n(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription}};function Zi(e){return typeof e=="string"&&e.length>0?e:void 0}n(Zi,"readQueryString");function Wd(e){let t=Array.from(j().byOperationId.values());if(t.length!==1)return;let r=t[0];if(r!==void 0)return Lt(r.operationId,e.url)}n(Wd,"inferSingleRouteResource");function Jd(e,t){let r=Zi(e.query.resource);if(t===void 0){if(r!==void 0)return r;let i=Wd(e);if(i!==void 0)return i;throw new p("invalid_target",$d)}let o=Lt(t,e.url);if(r===void 0||r===o)return o;throw new p("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}n(Jd,"requireAuthorizeResource");async function Vd(e,t){let r={};t!==void 0&&(r.context=t);let o=await xt(e,r);if(o.principal)return{principal:o.principal};if(!e.user)return o.evictCookie===void 0?{}:{setCookie:o.evictCookie};let i=si(e);return{principal:i,setCookie:await It({principal:i,requestUrl:e.url})}}n(Vd,"resolveBrowserPrincipal");async function Yd(e,t){let r={};t!==void 0&&(r.context=t);let o=await xt(e,r);if(!o.principal)throw g("authentication_required","Authorization setup requires a current browser session.");return o.principal}n(Yd,"requireSetupPrincipal");function Fi(e){return`/oauth/setup?state=${encodeURIComponent(e)}`}n(Fi,"buildSetupReturnTo");async function Ki(e){let t=await xr({transaction:e.transaction,requestUrl:e.requestUrl,returnTo:Fi(e.csrfToken)}),r=await Ir({transaction:e.transaction,requestUrl:e.requestUrl}),o={kind:"setup_page",html:Cr({state:e.csrfToken,operationId:e.transaction.operationId,upstreams:t,...r})};return e.setCookie!==void 0&&(o.setCookie=e.setCookie),o}n(Ki,"renderSetup");function Xd(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}n(Xd,"toAuthorizationTransactionClient");async function Ur(e,t={}){let r=Zd.parse({...e.query,resource:Jd(e,t.operationId),state:Zi(e.query.state)}),o=Ke(r.scope);Ie(r.redirect_uri,"invalid_request","authorize");let i=new Date,a=ee.parse(r.client_id),s=await Ut(r.client_id,i);Ui(s,r.redirect_uri);try{let c=Ae(e.url,r.resource),l=Xd(s);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:a,operationId:c.operationId,scope:o,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved"),t.context&&A(t.context,{eventType:x.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:c.operationId,attributes:{clientId:a,scope:o,responseType:r.response_type}});let h={clientId:s?.clientId??a,...l===void 0?{}:{client:l},redirectUri:r.redirect_uri,resource:r.resource,operationId:c.operationId,scope:o,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state}},{principal:m,setCookie:v}=await Vd(e,t.context);if(!m){let X=await Ci({transaction:h,requestUrl:e.url,now:i});t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:a,operationId:c.operationId},"Downstream OAuth authorize: redirecting to browser login (no session)");let Ye={kind:"redirect",location:X.browserLoginUrl};return v!==void 0&&(Ye.setCookie=v),Ye}let L=await Si({transaction:h,principal:m,now:i});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:a,operationId:c.operationId,subjectId:m.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),t.context&&A(t.context,{eventType:x.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:c.operationId,attributes:{clientId:a,scope:o,responseType:r.response_type,subjectId:m.subjectId}}),Ki({transaction:L.transaction,csrfToken:L.csrfToken,requestUrl:e.url,setCookie:v})}catch(c){throw Qd({redirectUri:r.redirect_uri,clientState:r.state,cause:c})}}n(Ur,"authorizeDownstreamClient");function Qd(e){if(e.cause instanceof oe)return e.cause;let t=eu(e.cause);return t?new oe({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}n(Qd,"toDownstreamAuthorizeRedirectError");function eu(e){if(e instanceof p)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof d.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}n(eu,"mapToOAuthRedirectError");async function Wi(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let h=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,m=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...h===void 0?{}:{idpErrorDescription:h},...m===void 0?{}:{idpErrorUri:m}},"Identity provider redirected browser-login callback with an error"),g("provider_access_denied",h??"The delegated browser login was not completed.")}let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),g("oauth_state_invalid","Browser login callback is missing state.");let i=await hr(o),a={request:e,stateId:i.stateId};t.context!==void 0&&(a.context=t.context);let s=await ci(a),c=await vi({browserLoginStateToken:o,principal:s}),l=await Ki({transaction:c.transaction,csrfToken:c.csrfToken,requestUrl:e.url});return l.setCookie=await It({principal:s,requestUrl:e.url}),l}n(Wi,"completeBrowserLoginCallback");async function Ji(e){let t=D(),r=new URL(e.url);if(!se(r))throw g("forbidden","Local browser login is only available on loopback HTTP origins.");let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw g("oauth_state_invalid","Local browser login is missing state.");let i=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:"/oauth/callback",I(e.url)),a=new URL(I(e.url)).origin;if(i.origin!==a||i.pathname!=="/oauth/callback")throw g("oauth_callback_mismatch","Local browser login redirect_uri must target this gateway's /oauth/callback route.");i.searchParams.set("state",o);let s={subjectId:st.parse(Gd),roles:Nd};return{kind:"redirect",location:i,setCookie:await It({principal:s,requestUrl:e.url})}}n(Ji,"completeLocalDevBrowserLogin");function tu(e){let t=e.method==="POST"?e.body:e.query;return Kd.parse(t)}n(tu,"readSetupContinueRequest");async function Vi(e){let{state:t,decision:r}=tu({method:e.request.method,query:e.request.query,body:e.body}),o=new Date,i=await wr({csrfToken:t,now:o}),a=await Yd(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await Ai({csrfToken:t,currentBrowserPrincipal:a,now:o})};let s=await xi({csrfToken:t,currentBrowserPrincipal:a,now:o}),c=await xr({transaction:s,requestUrl:e.request.url,returnTo:Fi(t)});if(r==="approve"&&Ar(c)&&await Ri({csrfToken:t,currentBrowserPrincipal:a,now:o}),Ar(c)){let l=await Ir({transaction:s,requestUrl:e.request.url});return{kind:"setup_page",html:Cr({state:t,operationId:s.operationId,upstreams:c,...l})}}return{kind:"redirect",location:await Ii({csrfToken:t,currentBrowserPrincipal:a,now:o})}}n(Vi,"continueDownstreamAuthorizeSetup");z();import{createLocalJWKSet as ru,decodeJwt as nu,errors as We,jwtVerify as ou}from"jose";var iu=new Set(["authorization_code","refresh_token"]),au="urn:ietf:params:oauth:client-assertion-type:jwt-bearer",su=1e4,cu=32*1024,du=2,Yi=d.object({client_id:d.string().min(1).optional(),client_secret:d.string().min(1).optional(),client_assertion_type:d.string().min(1).optional(),client_assertion:d.string().min(1).optional()}),uu=d.discriminatedUnion("grant_type",[Yi.extend({grant_type:d.literal("authorization_code"),code:d.string().min(1),redirect_uri:d.string().min(1),code_verifier:at,resource:d.url().optional(),scope:d.literal(P).optional()}),Yi.extend({grant_type:d.literal("refresh_token"),refresh_token:d.string().min(1),resource:d.url().optional(),scope:d.literal(P).optional()})]);function lu(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!iu.has(t)))throw new p("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}n(lu,"assertSupportedGrantType");var pu=d.object({token:d.string().min(1),client_id:d.string().min(1).optional(),token_type_hint:d.string().optional(),client_secret:d.string().min(1).optional(),client_assertion_type:d.string().min(1).optional(),client_assertion:d.string().min(1).optional()}),mu=d.object({keys:d.array(d.record(d.string(),d.unknown())).min(1)}).passthrough();function Xi(){return D().gateway.accessTokenTtlSeconds}n(Xi,"readAccessTokenTtlSeconds");function fu(){return D().gateway.refreshTokenTtlSeconds}n(fu,"readRefreshTokenTtlSeconds");function hu(e,t){let r=Xi(),o=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),i=Math.min(r,o);return{expiresAt:_(F(e,i)),expiresIn:i}}n(hu,"calculateAccessTokenExpiresAt");function Qi(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new p("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new p("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new p("invalid_client","Malformed HTTP Basic client authentication.")}}n(Qi,"readBasicClientSecret");function ea(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new p("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t!==void 0)return t;if(e.clientAssertion!==void 0){try{let r=nu(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new p("invalid_client","Malformed private_key_jwt client assertion.")}throw new p("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new p("invalid_client","Client authentication or client_id is required.")}n(ea,"resolveAuthenticatedClientId");function gu(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new p("invalid_request","Use only one client authentication method per request.");return e.basicClientSecret!==void 0?{clientSecret:e.basicClientSecret,clientSecretSource:"basic"}:e.bodyClientSecret!==void 0?{clientSecret:e.bodyClientSecret,clientSecretSource:"post"}:{}}n(gu,"resolveClientSecretInput");function yu(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}n(yu,"hasClientAssertion");function wu(e){if(e.requestUrl===void 0)throw new p("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(e.pathname,e.requestUrl);return t.search="",t.hash="",t.toString()}n(wu,"buildEndpointAudience");function _u(e){return e instanceof We.JWTExpired?"expired":e instanceof We.JWTClaimValidationFailed?"claim":e instanceof We.JWSSignatureVerificationFailed?"signature":e instanceof We.JWKSNoMatchingKey?"jwks_no_match":e instanceof We.JWTInvalid?"invalid":e instanceof d.ZodError?"schema":"other"}n(_u,"readJwtFailureKind");async function Ru(e){let{response:t,json:r}=await Kn(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:du,maxResponseBytes:cu,timeoutMs:su});if(!t.ok)throw new p("invalid_client","Client JWKS could not be fetched.");return mu.parse(r)}n(Ru,"fetchClientJwks");async function bu(e){if(e.clientAssertionType!==au||e.clientAssertion===void 0)throw new p("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=ee.parse(e.clientId),r=await Ut(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new p("invalid_client","Client is not registered for private_key_jwt authentication.");let o=r.metadata.jwks_uri;if(o===void 0)throw new p("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let i=wu({requestUrl:e.requestUrl,pathname:e.endpointPathname});try{let a=await Ru({jwksUri:o,context:e.context});await ou(e.clientAssertion,ru(a),{issuer:t,subject:t,audience:i,currentDate:e.now})}catch(a){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:_u(a)},"OAuth private_key_jwt client authentication failed"),new p("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}n(bu,"verifyPrivateKeyJwtClientAssertion");async function Cu(e){let t=ee.parse(e.clientId);return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await C(e.clientSecret)}}n(Cu,"buildRuntimeHttpClientAuth");async function ta(e){if(yu({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new p("invalid_request","Use only one client authentication method per request.");return bu(e)}let t=gu({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return Cu({clientId:e.clientId,...t})}n(ta,"resolveRuntimeHttpClientAuth");async function ra(e){lu(e.body);let t=uu.parse(e.body),r=Qi(e.authorizationHeader),o=ea({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),i=new Date,a=await ta({clientId:o,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,endpointPathname:"/oauth/token",now:i,context:e.context});return Su({parsed:t,clientId:o,clientAuth:a,now:i,requestUrl:e.requestUrl,context:e.context})}n(ra,"exchangeDownstreamToken");async function Su(e){if(e.parsed.grant_type==="authorization_code"){Ie(e.parsed.redirect_uri,"invalid_request","token"),Ke(e.parsed.scope),e.parsed.resource!==void 0&&Ae(e.requestUrl??e.parsed.resource,e.parsed.resource);let s=W(),c=W(),l=_(F(e.now,fu())),h=hu(e.now,l),m=await R().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await C(e.parsed.code),redirectUri:e.parsed.redirect_uri,...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},codeChallenge:await jn(e.parsed.code_verifier),currentRefreshTokenHash:await C(s),accessTokenHash:await C(c),grantExpiresAt:l,accessTokenExpiresAt:h.expiresAt,now:_(e.now)});if(m.kind==="invalid_client")throw new p("invalid_client","Client authentication failed.");if(m.kind==="resource_mismatch")throw new p("invalid_target","Token request resource must match the authorization code resource.");if(m.kind!=="exchanged")throw new p("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&A(e.context,{eventType:x.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:c,token_type:"Bearer",expires_in:h.expiresIn,refresh_token:s,scope:m.grant.scope,resource:m.grant.resource}}Ke(e.parsed.scope),e.parsed.resource!==void 0&&Ae(e.requestUrl??e.parsed.resource,e.parsed.resource);let t=W(),r=W(),o=_(F(e.now,Xi())),i=await R().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:await C(e.parsed.refresh_token),nextRefreshTokenHash:await C(t),accessTokenHash:await C(r),...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},accessTokenExpiresAt:o,now:_(e.now)});if(i.kind==="invalid_client")throw new p("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new p("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new p("invalid_grant","Refresh token is invalid, expired, or revoked.");Ae(e.requestUrl??i.grant.resource,i.grant.resource);let a=i.accessToken.expiresAt;return e.context&&(A(e.context,{eventType:x.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),A(e.context,{eventType:x.MCP_OAUTH_TOKEN_REFRESH_ROTATED,outcome:"success",attributes:{clientId:e.clientId}})),{access_token:r,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(a).getTime()-e.now.getTime())/1e3)),refresh_token:t,scope:i.grant.scope,resource:i.grant.resource}}n(Su,"exchangeDownstreamTokenWithRuntimeHttp");async function na(e){let t=pu.parse(e.body),r=Qi(e.authorizationHeader),o=ea({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),i=new Date;if((await R().revokeOAuthToken({clientAuth:await ta({clientId:o,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,endpointPathname:"/oauth/revoke",now:i,context:e.context}),tokenHash:await C(t.token),now:_(i)})).kind==="invalid_client")throw new p("invalid_client","Client authentication failed.");e.context?.log.info({event:"oauth_token_revoked",clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed"),e.context&&A(e.context,{eventType:x.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}n(na,"revokeDownstreamToken");var vu=64*1024,xu=16*1024,Iu="text/html; charset=utf-8";function Au(e){let t={};for(let[r,o]of e.entries())t[r]=o;return t}n(Au,"formDataToObject");async function Uu(e){return ni(e,{maxBytes:vu,label:"Request body"})}n(Uu,"readJsonBody");async function kr(e){return Au(await oi(e,{maxBytes:xu,label:"Request body"}))}n(kr,"readFormBody");async function oa(e,t,r){let o=ce(r),i=r instanceof d.ZodError?kt(r):void 0,a={code:o??(r instanceof d.ZodError?"invalid_request":"internal_server_error")};return i!==void 0&&(a.detail=i),Rn(e,t,a)}n(oa,"handleProblem");function Je(e){let t=new Headers(e.headers);t.set("cache-control","no-store"),t.set("pragma","no-cache");let r={error:e.error};return e.errorDescription!==void 0&&(r.error_description=e.errorDescription),Response.json(r,{status:e.status??400,headers:t})}n(Je,"oauthErrorResponse");function ku(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}n(ku,"readOAuthProtocolHeaders");function Pu(e,t){let r=H("internal_server_error");return Je({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:ku(e,t)})}n(Pu,"oauthProtocolErrorResponse");function ia(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}n(ia,"readZodOAuthErrorCode");function Tu(e){let t={error:ia(e)},r=kt(e);return r!==void 0&&(t.errorDescription=r),Je(t)}n(Tu,"oauthZodErrorResponse");function Ou(e){let t=ce(e);if(t===void 0)return;let r=H(t);if(r.oauthError===void 0)return;let o={error:r.oauthError,status:qu(r.oauthError)};return r.oauthError==="server_error"?o.errorDescription=r.publicDetail:e instanceof Error?o.errorDescription=e.message:o.errorDescription=r.publicDetail,Je(o)}n(Ou,"oauthGatewayProblemResponse");function Eu(){let t={error:"server_error",status:500,errorDescription:H("internal_server_error").publicDetail};return Je(t)}n(Eu,"oauthFallbackErrorResponse");function qu(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}n(qu,"readOAuthStatus");function Pr(e,t={}){return e instanceof oe?ca(e):e instanceof p?Pu(e,t):e instanceof d.ZodError?Tu(e):Ou(e)??Eu()}n(Pr,"oauthProblemResponse");function Tr(e,t){let r=xe(e.url);if(t instanceof oe)return ca(t);if(t instanceof p){let a=H("internal_server_error");return $({host:r,kind:Mu(t.errorCode),title:"Authorization failed",detail:t.errorCode==="server_error"?a.publicDetail:t.message,code:t.errorCode,status:t.status})}if(t instanceof d.ZodError)return $({host:r,kind:"invalid_request",detail:kt(t)??"The authorization request was invalid.",code:ia(t)});let o=ce(t);if(o!==void 0){let a=H(o);return $({host:r,kind:sa(o),detail:a.status<500&&t instanceof Error?t.message:a.publicDetail,code:a.oauthError??o,status:a.status})}let i=H("internal_server_error");return $({host:r,kind:"internal_error",detail:i.publicDetail,code:"server_error",status:i.status})}n(Tr,"browserOAuthProblemResponse");function aa(e,t){let r=xe(e.url),o=ce(t);if(o!==void 0){let a=H(o);return $({host:r,kind:sa(o),detail:a.status<500&&t instanceof Error?t.message:a.publicDetail,code:o,status:a.status})}if(t instanceof d.ZodError)return $({host:r,kind:"invalid_request",detail:kt(t)??"The authorization request was invalid.",code:"invalid_request"});let i=H("internal_server_error");return $({host:r,kind:"internal_error",detail:i.publicDetail,code:"internal_server_error",status:i.status})}n(aa,"browserGatewayProblemResponse");function Mu(e){return e==="server_error"?"internal_error":"invalid_request"}n(Mu,"readOAuthBrowserErrorKind");function sa(e){if(H(e).status>=500)return"internal_error";switch(e){case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"configuration_error";case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"upstream_client_registration_required":return"admin_required";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"invalid_request":case"authentication_required":case"forbidden":case"not_found":case"too_many_requests":case"identity_context_missing":return"invalid_request";case"upstream_capability_invocation_failed":case"upstream_capability_unavailable":case"upstream_import_failed":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}n(sa,"readGatewayBrowserErrorKind");function Y(e,t,r){let o={event:t},i=!1;if(r instanceof p)o.oauthError=r.errorCode,o.status=r.status,K(o,"error",r);else if(r instanceof oe)o.oauthError=r.errorCode,K(o,"error",r);else if(r instanceof d.ZodError){o.code="invalid_request",K(o,"error",r);let a=r.issues[0];a&&(o.zodPath=a.path.join("."))}else{let a=ce(r);if(a!==void 0){let s=H(a);o.code=a,o.status=s.status,s.oauthError!==void 0&&(o.oauthError=s.oauthError),i=s.status>=500||s.oauthError==="server_error",K(o,"error",r)}else i=!0,K(o,"error",r)}if(i){let a=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(o,a.message)}else e.log.warn(o,"OAuth handler rejected the request")}n(Y,"logUnexpectedOAuthHandlerError");function ca(e){let t;try{t=new URL(e.redirectUri)}catch{return Je({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}n(ca,"downstreamAuthorizeRedirectErrorResponse");function kt(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}n(kt,"formatZodErrorDetail");function zu(e,t){let r={event:"browser_login_callback_failed",code:ce(t)??"invalid_request"};K(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}n(zu,"logBrowserLoginCallbackFailure");function da(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(null,{status:302,headers:t})}n(da,"redirectResultResponse");function Pt(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":Iu,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(e.html,{status:200,headers:t})}return da(e)}n(Pt,"authorizeResultResponse");async function ua(e,t){try{return Response.json(Un(e.url))}catch(r){return Y(t,"oauth_authorization_server_metadata_failed",r),oa(e,t,r)}}n(ua,"authorizationServerMetadataHandler");async function la(e,t){try{let r=jt(e.params.routePath);return Response.json(kn({operationId:r.operationId,requestUrl:e.url}))}catch(r){return Y(t,"oauth_authorization_server_metadata_failed",r),oa(e,t,r)}}n(la,"scopedAuthorizationServerMetadataHandler");async function pa(e,t){try{let r=await Pi(await Uu(e)),o=r,i=typeof o.client_id=="string"?o.client_id:void 0,a=typeof o.client_name=="string"?o.client_name:void 0,s=Array.isArray(o.redirect_uris)?o.redirect_uris.length:void 0,c=typeof o.token_endpoint_auth_method=="string"?o.token_endpoint_auth_method:void 0;return t.log.info({event:"oauth_dcr_client_registered",clientId:i,clientName:a,redirectUriCount:s,tokenEndpointAuthMethod:c},"OAuth Dynamic Client Registration completed"),A(t,{eventType:x.MCP_OAUTH_CLIENT_REGISTERED,outcome:"success",clientName:a,attributes:{clientId:i,redirectUriCount:s,tokenEndpointAuthMethod:c}}),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return Y(t,"oauth_register_failed",r),Pr(r)}}n(pa,"registerHandler");async function ma(e,t){try{return Pt(await Ur(e,{context:t}))}catch(r){return Y(t,"oauth_authorize_failed",r),Tr(e,r)}}n(ma,"authorizeHandler");async function fa(e,t){try{let r=jt(e.params.routePath);return Pt(await Ur(e,{operationId:r.operationId,context:t}))}catch(r){return Y(t,"oauth_authorize_scoped_failed",r),Tr(e,r)}}n(fa,"scopedAuthorizeHandler");async function ha(e,t){try{let r=await Wi(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),Pt(r)}catch(r){return zu(t,r),aa(e,r)}}n(ha,"callbackHandler");async function ga(e,t){try{return da(await Ji(e))}catch(r){return Y(t,"oauth_dev_login_failed",r),Tr(e,r)}}n(ga,"devLoginHandler");async function ya(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await Vi({request:e,body:e.method==="POST"?await kr(e):void 0,context:t});return Pt(r)}catch(r){return Y(t,"oauth_setup_failed",r),aa(e,r)}}n(ya,"setupHandler");async function wa(e,t){try{return Response.json(await ra({body:await kr(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return Y(t,"oauth_token_failed",r),Pr(r)}}n(wa,"tokenHandler");async function _a(e,t){try{return await na({body:await kr(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return Y(t,"oauth_revoke_failed",r),Pr(r)}}n(_a,"revokeHandler");var Du={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},Ra=new Nr("upstream-request");function Hu(e){let t=Ra.get(e);if(!t)throw new E("Upstream request context has not been set");return t}n(Hu,"readUpstreamRequestContext");function Bu(e,t){return t.some(r=>r===e)}n(Bu,"requestContextMatchesKind");function Lu(e){return typeof e=="string"?[e]:e}n(Lu,"toExpectedKinds");function Ue(e,t){Ra.set(e,t)}n(Ue,"setUpstreamRequestContext");function Ve(e,t){let r=Hu(e),o=Lu(t);if(!Bu(r.kind,o)){let i=Du[o[0]];throw new E(`${i} request context has not been set`)}return r}n(Ve,"requireUpstreamRequestContext");function ba(e){return b`<p data-gateway-error-code="${e.code}">${e.body}</p>`}n(ba,"renderBrowserResult");var ju="text/html; charset=utf-8",Nu="none";function Gu(e){let t=Ct(e.host);return ve({title:e.title,iconHref:t,styles:Se,headerIcon:St({iconHref:t,fallbackIconHref:bt}),heading:e.title,subhead:"",body:ba({body:e.body,code:e.code??Nu}),footer:""})}n(Gu,"browserResultHtml");function $u(e,t=200){return new Response(Ce(e),{status:t,headers:{"content-type":ju,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n($u,"browserResultResponse");function Ca(e){return $u(Gu(e))}n(Ca,"browserConnectionSuccessResponse");function Tt(e,t){let r=_n(t);return $({host:e,kind:Zu(t),detail:r.body,code:t})}n(Tt,"browserConnectionFailureResponse");function Zu(e){switch(e){case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed"}}n(Zu,"readCallbackFailureBrowserErrorKind");var Fu=["callback_authorization_code","callback_provider_error","callback_invalid"];function Ku(e){return"cause"in e?e.cause:void 0}n(Ku,"readErrorCause");function Wu(e){return e.stack?.split(`
28
+ `).slice(1,4).map(t=>t.trim()).join(" | ")}n(Wu,"readFirstStackFrame");function Sa(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=Wu(r))}n(Sa,"addErrorAttributes");function Or(e){if(!(e instanceof y))return;let t=e.extensionMembers?.[w];return rn(t)?t:void 0}n(Or,"readRuntimeGatewayCode");function Ju(e,t,r){switch(t.kind){case"callback_provider_error":return e.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:t.upstreamServerId,providerError:t.error,...t.errorDescription===void 0?{}:{providerErrorDescription:t.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),A(e,{eventType:x.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:t.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:t.error,errorDescription:t.errorDescription}}),Tt(r,"provider_access_denied");case"callback_invalid":return e.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:t.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),Tt(r,"oauth_state_invalid");case"callback_authorization_code":return t}}n(Ju,"requireAuthorizationCallbackRequest");function Vu(e,t){A(e,{eventType:x.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}n(Vu,"emitCallbackReceivedAnalyticsEvent");function Yu(e,t){A(e,{eventType:x.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}n(Yu,"emitTokenExchangeSucceededAnalyticsEvent");function Xu(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return Ca({host:xe(e.url),title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}n(Xu,"buildSuccessfulCallbackResponse");function Qu(e){let t={detail:e instanceof Error?e.message:void 0};return Sa(t,"error",e),e instanceof Error&&Sa(t,"cause",Ku(e)),t}n(Qu,"buildTokenExchangeFailureAttributes");function el(e){A(e.context,{eventType:x.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:Or(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:Qu(e.error)})}n(el,"emitTokenExchangeFailedAnalyticsEvent");function tl(e,t){let r=Or(t);return Tt(e,nn(r)?r:"upstream_token_exchange_failed")}n(tl,"tokenExchangeFailureResponse");async function Er(e,t){let r=Ve(t,Fu),o=xe(e.url),i=Ju(t,r,o);if(i instanceof Response)return i;Vu(t,i);try{let a=await Ko({request:e,callbackRequest:i});return Yu(t,a),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:a.upstreamServerId,operationId:a.operationId,authProfileId:a.authProfileId,ownerMode:a.ownerMode},"Upstream OAuth token exchange completed; user connection established"),Xu(e,a)}catch(a){let s={event:"upstream_oauth_token_exchange_failed",code:Or(a)??"upstream_token_exchange_failed",upstreamServerId:i.upstreamServerId};return K(s,"error",a),t.log.warn(s,"Upstream OAuth token exchange failed; user shown connection-failure page"),el({context:t,callbackRequest:i,error:a}),tl(o,a)}}n(Er,"callbackHandler");function rl(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}n(rl,"clientMetadataProblemDetail");async function va(e,t){let r=Ve(t,"connect"),o=await Fo({request:e,connectRequest:r});if(A(t,{eventType:x.MCP_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:o.operationId,upstreamServerTitle:o.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:o.authProfileId,operationId:o.operationId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),r.redirect)return Response.redirect(o.authUrl,302);let i=await wt({requestUrl:e.url,owner:o.owner,initiatedBySubjectId:o.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:o.authProfileId,upstreamDisplayName:o.upstreamDisplayName,operationId:o.operationId,subject:"MCP route",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(i,{status:428})}n(va,"connectHandler");async function xa(e,t){let r=Ve(t,"client_metadata");try{let o=To(e.url),i=Oo(o,r.upstreamServerId,r.authProfileId);return Response.json(i)}catch(o){if(!(o instanceof k))throw o;let i=o instanceof Error?o.message:String(o);return t.log.warn({event:"oauth_client_metadata_request_failed",upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:i},"Failed to serve OAuth client metadata document for upstream connection"),ae.notFound(e,t,{code:"not_found",detail:rl(o)})}}n(xa,"oauthClientMetadataHandler");function ie(e){if(typeof e=="string"&&e.length!==0)return e}n(ie,"readOptionalQueryString");function nl(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new E(`Validated path parameter ${t} is missing`);return r}n(nl,"requirePathString");function ol(e){let t=ie(e);return t?rt.parse(t):void 0}n(ol,"readOptionalOperationId");function il(e,t){let r=ie(e);return r?sn.parse(r):it(t,"user-oauth")}n(il,"readOptionalAuthProfileId");function al(e){let t=ol(e);if(!t)throw new y({message:"operationId query parameter is required.",extensionMembers:{[w]:"invalid_request"}});return t}n(al,"readRequiredOperationId");function sl(e){let t=On(ie(e));return t===void 0?{}:{returnTo:t}}n(sl,"readOptionalReturnTo");function cl(e){let t=ie(e.query.error_description);return t===void 0?{}:{errorDescription:t}}n(cl,"readOptionalProviderErrorDescription");function dl(e){let t=N(e.authMode);if(t.connectSupport!=="none")return e;throw new y({message:t.connectUnsupportedDetail??"This upstream does not support browser connection flows.",extensionMembers:{[w]:"invalid_request"}})}n(dl,"requireConnectableRouteAuth");function ul(e,t,r,o){return{kind:"connect",...be(e,t),...o===void 0?{}:{returnTo:o},redirect:r}}n(ul,"buildConnectContextForPrincipal");function ll(e,t,r){let o=ut(t),i=N(e.authMode);if(o.mode!==i.ownerMode)throw new y({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[w]:"oauth_callback_mismatch"}});return{kind:"connect",...e,...t.returnTo===void 0?{}:{returnTo:t.returnTo},owner:o,initiatedBySubjectId:t.initiatedBySubjectId,redirect:r}}n(ll,"buildConnectContextForTicket");async function pl(e,t){let r=dl(Rt(t,al(e.query.operationId))),o=e.query.redirect==="true",i=ie(e.query.browserTicket);if(e.user){if(i)throw new y({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[w]:"invalid_request"}});let s=ct(e.user,e.url);return ul(r,s,o,sl(e.query.returnTo).returnTo)}if(!i)throw new y({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[w]:"authentication_required"}});let a=await Ao(i);if(a.ownerMode!==r.ownerMode||a.upstreamServerId!==r.upstreamServerId||a.authProfileId!==r.authProfileId||a.operationId!==r.operationId)throw new y({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[w]:"oauth_callback_mismatch"}});return await Uo(a),ll(r,a,o)}n(pl,"resolveConnectContext");async function ml(e,t,r){let o=an.parse(nl(e,"connection"));switch(r){case"connect":Ue(t,await pl(e,o));return;case"callback":{let i=ie(e.query.error);if(i){Ue(t,{kind:"callback_provider_error",upstreamServerId:o,error:i,...cl(e)});return}let a=ie(e.query.code),s=ie(e.query.state);if(a&&s){Ue(t,{kind:"callback_authorization_code",upstreamServerId:o,code:a,state:s});return}Ue(t,{kind:"callback_invalid",upstreamServerId:o});return}case"client_metadata":Ue(t,{kind:"client_metadata",upstreamServerId:o,authProfileId:il(e.query.authProfileId,o)});return}}n(ml,"resolveUpstreamRequestInbound");async function fl(e,t,r){try{await ml(e,t,r);return}catch(o){let i=o instanceof y?o.extensionMembers?.[w]:void 0,a=o instanceof Error?o.message:void 0;switch(i){case"invalid_request":case"oauth_callback_mismatch":return ae.badRequest(e,t,{code:i,detail:a});case"authentication_required":return ae.unauthorized(e,t,{code:i,detail:a});default:throw o}}}n(fl,"applyUpstreamRequestContext");function Ot(e,t){return n(async(o,i)=>{let a=await fl(o,i,e);return a||t(o,i)},"wrapped")}n(Ot,"withUpstreamRequestContext");var hl={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function gl(){return new Response(null,{status:204,headers:hl})}n(gl,"buildWellKnownPreflightResponse");function yl(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}n(yl,"withWellKnownCorsHeaders");function qr(e){return async(t,r)=>t.method==="OPTIONS"?gl():yl(await e(t,r))}n(qr,"wrapWellKnownHandler");var Ua=[{routeName:"oauth_as_metadata",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:qr(ua),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:qr(la),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:qr(Pn),corsPolicy:"anything-goes"},{routeName:"oauth_register",path:"/oauth/register",methods:["POST"],handler:pa},{routeName:"oauth_authorize",path:"/oauth/authorize",methods:["GET"],handler:ma},{routeName:"oauth_authorize_scoped",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:fa},{routeName:"oauth_callback",path:"/oauth/callback",methods:["GET"],handler:ha},{routeName:"oauth_dev_login",path:"/oauth/dev-login",methods:["GET"],handler:ga},{routeName:"oauth_setup",path:"/oauth/setup",methods:["GET","POST"],handler:ya},{routeName:"oauth_token",path:"/oauth/token",methods:["POST"],handler:wa},{routeName:"oauth_revoke",path:"/oauth/revoke",methods:["POST"],handler:_a},{routeName:"upstream_client_metadata",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:Ot("client_metadata",xa)},{routeName:"upstream_connect",path:"/auth/connections/:connection/connect",methods:["GET"],handler:Ot("connect",va)},{routeName:"upstream_callback",path:"/auth/connections/:connection/callback",methods:["GET"],handler:Ot("callback",Er)}],wl=Ua.filter(e=>!e.routeName.startsWith("upstream_")),_l=Ua.filter(e=>e.routeName.startsWith("upstream_"));function ka(e){return e?.some(en)??!1}n(ka,"hasMcpOAuthRuntimeConfigPolicy");function Pa(e){return e?.some(t=>mn(t.policyType))??!1}n(Pa,"hasMcpTokenExchangePolicy");function Ta(e){return ka(e)||Pa(e)}n(Ta,"shouldRegisterMcpGatewayInternalRoutes");function Rl(e){gn(fn({routes:e.routes,policies:e.policies}))}n(Rl,"initializeMcpGatewayConnectionRegistry");function bl(e){let t=tn(e.policies);if(!t){let r=[...Qr].map(o=>`\`${o}\``).join(", ");throw new k(`MCP gateway: could not find an MCP authorization policy in policies.json. Add one of [${r}] and reference it on your MCP routes.`)}return t.config}n(bl,"initializeMcpGatewayOAuthRuntimeConfig");function Ia(e,t,r){return async(o,i)=>{r&&Yr(i,r());let a=o.method==="OPTIONS",s=Date.now();a||i.log.info({event:`${e}_received`,method:o.method},`MCP gateway: ${e} received`);let c=await t(o,i);return a||i.log.info({event:`${e}_responded`,status:c.status,durationMs:Date.now()-s},`MCP gateway: ${e} responded`),c}}n(Ia,"wrapInternalHandler");function Aa(e,t,r){e.addPluginRoute({path:t.path,methods:t.methods,handler:r,processors:[jr],corsPolicy:t.corsPolicy??"none"})}n(Aa,"addInternalRoute");function Oa(e,t){Rl(t);let r=ka(t.policies),o=Pa(t.policies),i,a=n(()=>(i===void 0&&(i=bl(t)),i),"readOAuthConfig");if(r)for(let s of wl)Aa(e,s,Ia(s.routeName,s.handler,a));if(o)for(let s of _l)Aa(e,s,Ia(s.routeName,s.handler))}n(Oa,"registerMcpGatewayInternalRoutes");function Ea(e){hn(e)}n(Ea,"configureLazyMcpGatewayState");var Mr=class extends Br{static{n(this,"McpGatewayPlugin")}registerRoutes(t){let r=t.parsedRouteData;if(!r||!Ta(r.policies))return;let o={routes:r.routes,policies:r.policies};Ea(o),Oa(t.router,o)}};var Cl={Allow:"POST"};async function Sl(e,t){return e.method==="GET"?ae.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},Cl):Jr(e,t)}n(Sl,"McpProxyHandler");export{Ha as McpAuth0OAuthInboundPolicy,Gt as McpCapabilityFilterInboundPolicy,Mr as McpGatewayPlugin,Da as McpOAuthInboundPolicy,Sl as McpProxyHandler,ur as McpTokenExchangeInboundPolicy};
33
29
  //# sourceMappingURL=index.js.map