@zuplo/runtime 6.70.36 → 6.70.37

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,12 @@
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 j,A as dn,B as Me,J as ui,K as di,L as c,M as pi,N as C,O as P,P as li,Q as mi,R as B,S as l,T as m,U as G,V as O,W as pn,X as ln,Y as U,Z as se,_ as f,a as ot,aa as hi,b as si,ba as mn,ca as fi,da as gi,ea as i,fa as z,ga as yi,j as he,k as ci,m as mr,ma as wi,q as cn,s as it,x as un}from"../chunk-YTQ3TTI6.js";import{d as at}from"../chunk-TOF2KNST.js";import{a as v}from"../chunk-A2CSR4RF.js";import{$ as te,a as n,aa as w,ba as _,ca as nt,da as ai}from"../chunk-2VLXJLVI.js";z();z();var kd=new Set(["localhost","::1"]);function ve(e){return e.replace(/^\[(.*)\]$/,"$1").replace(/\.+$/,"").toLowerCase()}n(ve,"normalizeHostname");function $(e){let t=ve(e.hostname);return e.protocol==="http:"&&(kd.has(t)||/^127(?:\.\d{1,3}){3}$/.test(t))}n($,"isLoopbackHttpUrl");var Si=new Me("gateway-route");function Ri(e,t){Si.set(e,t)}n(Ri,"setGatewayRouteContext");function hr(e){return Si.get(e)}n(hr,"readGatewayRouteContext");var _i=new Me("mcp-oauth-runtime-config");function st(e,t){_i.set(e,t)}n(st,"setMcpOAuthRuntimeConfig");function bi(e){let t=_i.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(bi,"requireMcpOAuthRuntimeConfig");var zt=i.string().trim().min(1),Ud=60,Td=24*60*60,Od=15*Ud,zd=10*365*Td,Et={accessTokenTtlSeconds:Od,refreshTokenTtlSeconds:zd,cimdEnabled:!0},Ed=i.object({issuer:i.url(),jwksUrl:i.url(),audience:zt.optional()}),Md=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(!xi(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]})}),qd=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),hn=i.object({oidc:Ed,browserLogin:Md,gateway:qd.optional().default(Et)}).strict();function Ci(e){return xi(e.browserLogin.url)?"local_dev":"federated_oidc"}n(Ci,"readBrowserLoginKind");function xi(e){let t;try{t=new URL(e)}catch{return!1}return $(t)&&t.pathname==="/oauth/dev-login"}n(xi,"isLoopbackDevLoginUrl");function Ai(e){return hn.parse(e)}n(Ai,"parseMcpOAuthRuntimeConfig");function F(){let e;try{e=un()}catch(t){throw new te("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 bi(e)}n(F,"getGatewayOAuthConfig");function fr(e,t,r){let o=e.safeParse(t);if(o.success)return o.data;throw new _(`${r} is misconfigured. Validation failed:
26
+ ${Hd(o.error)}`,{cause:o.error})}n(fr,"parseConfigOrThrow");function Hd(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
27
+ `)}n(Hd,"formatZodIssues");var fn=class extends it{static{n(this,"McpOAuthInboundPolicy")}constructor(t,r){let o=gn(t,r);super(o,r)}async handler(t,r){return ot("policy.inbound.mcp-oauth"),st(r,this.options),Mt(t,r)}};function gn(e,t="mcp-oauth-inbound"){return fr(hn,e,`MCP OAuth policy "${t}"`)}n(gn,"mcpOAuthOptionsToRuntimeConfig");var yn=["mcp-oauth-inbound","mcp-auth0-oauth-inbound"],vi={"mcp-oauth-inbound":"McpOAuthInboundPolicy","mcp-auth0-oauth-inbound":"McpAuth0OAuthInboundPolicy"};function Dd(e,t,r){switch(e){case"mcp-oauth-inbound":return gn(r,t);case"mcp-auth0-oauth-inbound":return Pi(r,t);default:return}}n(Dd,"parseMcpOAuthPolicyConfig");function Ii(e){return e!==void 0&&yn.some(t=>t===e)}n(Ii,"isMcpOAuthInboundPolicyType");function wn(e){switch(e.policyType){case"mcp-oauth-inbound":return e.handler.export===vi["mcp-oauth-inbound"];case"mcp-auth0-oauth-inbound":return e.handler.export===vi["mcp-auth0-oauth-inbound"];default:return!1}}n(wn,"isMcpOAuthRuntimeConfigPolicy");function ki(e){if(!e)return;let t=e.filter(wn);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=Dd(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(ki,"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."}}},gr={...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(gr,e)}n(Ie,"isGatewayProblemCode");function Ui(e){return Ie(e)&&K(e).callbackFailure===!0}n(Ui,"isGatewayCallbackFailureCode");function K(e){return gr[e]}n(K,"readGatewayProblemDefinition");function Ti(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(Ti,"readDefaultGatewayProblemCodeForStatus");var jd=/^\$\{env\.([A-Za-z_][A-Za-z0-9_]*)\}$/;function Oi(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(Oi,"assertHttpUrl");function zi(e){return e.options??{}}n(zi,"readHandlerOptions");function Ld(e){let t=jd.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 Oi(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 Oi(e,"MCP route handler rewritePattern")}n(Ld,"readRewritePatternUrl");function Sn(e){let t=zi(e);if(typeof t.rewritePattern=="string"&&t.rewritePattern!=="")return Ld(t.rewritePattern);throw new _("MCP route must configure handler.options.rewritePattern.")}n(Sn,"readMcpRouteUpstreamUrl");function Ei(e){let t=zi(e.handler),r=new URL(Sn(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(Ei,"buildMcpRouteUpstreamFetch");z();var Bd=["shared-oauth","user-oauth"],Nd=["none","client_secret_basic","client_secret_post"],oe=i.string().min(1).brand(),re=i.string().min(1),ce=i.string().min(1).brand(),MR=i.string().min(1).brand(),Rn=i.enum(Bd),_n=i.enum(Nd);z();var Ht="2025-11-25";var $d="io.modelcontextprotocol/related-task",dt="2.0",Z=hi(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Mi=O([c(),C().int()]),qi=c(),HR=G({ttl:C().optional(),pollInterval:C().optional()}),Zd=m({ttl:C().optional()}),Fd=m({taskId:c()}),Cn=G({progressToken:Mi.optional(),[$d]:Fd.optional()}),ue=m({_meta:Cn.optional()}),wr=ue.extend({task:Zd.optional()});var Y=m({method:c(),params:ue.loose().optional()}),fe=m({_meta:Cn.optional()}),ge=m({method:c(),params:fe.loose().optional()}),X=G({_meta:Cn.optional()}),Sr=O([c(),C().int()]),xn=m({jsonrpc:f(dt),id:Sr,...Y.shape}).strict();var Kd=m({jsonrpc:f(dt),...ge.shape}).strict();var Hi=m({jsonrpc:f(dt),id:Sr,result:X}).strict();var Ge;(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"})(Ge||(Ge={}));var Rr=m({jsonrpc:f(dt),id:Sr.optional(),error:m({code:C().int(),message:c(),data:B().optional()})}).strict();var DR=O([xn,Kd,Hi,Rr]),jR=O([Hi,Rr]),Di=X.strict(),Wd=fe.extend({requestId:Sr.optional(),reason:c().optional()}),ji=ge.extend({method:f("notifications/cancelled"),params:Wd}),Jd=m({src:c(),mimeType:c().optional(),sizes:l(c()).optional(),theme:se(["light","dark"]).optional()}),Dt=m({icons:l(Jd).optional()}),ut=m({name:c(),title:c().optional()}),pt=ut.extend({...ut.shape,...Dt.shape,version:c(),websiteUrl:c().optional(),description:c().optional()}),Vd=ln(m({applyDefaults:P().optional()}),U(c(),B())),Yd=mn(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ln(m({form:Vd.optional(),url:Z.optional()}),U(c(),B()).optional())),Xd=G({list:Z.optional(),cancel:Z.optional(),requests:G({sampling:G({createMessage:Z.optional()}).optional(),elicitation:G({create:Z.optional()}).optional()}).optional()}),Qd=G({list:Z.optional(),cancel:Z.optional(),requests:G({tools:G({call:Z.optional()}).optional()}).optional()}),ep=m({experimental:U(c(),Z).optional(),sampling:m({context:Z.optional(),tools:Z.optional()}).optional(),elicitation:Yd.optional(),roots:m({listChanged:P().optional()}).optional(),tasks:Xd.optional(),extensions:U(c(),Z).optional()}),tp=ue.extend({protocolVersion:c(),capabilities:ep,clientInfo:pt}),rp=Y.extend({method:f("initialize"),params:tp});var np=m({experimental:U(c(),Z).optional(),logging:Z.optional(),completions:Z.optional(),prompts:m({listChanged:P().optional()}).optional(),resources:m({subscribe:P().optional(),listChanged:P().optional()}).optional(),tools:m({listChanged:P().optional()}).optional(),tasks:Qd.optional(),extensions:U(c(),Z).optional()}),op=X.extend({protocolVersion:c(),capabilities:np,serverInfo:pt,instructions:c().optional()}),ip=ge.extend({method:f("notifications/initialized"),params:fe.optional()});var Li=Y.extend({method:f("ping"),params:ue.optional()}),ap=m({progress:C(),total:j(C()),message:j(c())}),sp=m({...fe.shape,...ap.shape,progressToken:Mi}),Bi=ge.extend({method:f("notifications/progress"),params:sp}),cp=ue.extend({cursor:qi.optional()}),jt=Y.extend({params:cp.optional()}),Lt=X.extend({nextCursor:qi.optional()}),up=se(["working","input_required","completed","failed","cancelled"]),Bt=m({taskId:c(),status:up,ttl:O([C(),li()]),createdAt:c(),lastUpdatedAt:c(),pollInterval:j(C()),statusMessage:j(c())}),Ni=X.extend({task:Bt}),dp=fe.merge(Bt),Gi=ge.extend({method:f("notifications/tasks/status"),params:dp}),$i=Y.extend({method:f("tasks/get"),params:ue.extend({taskId:c()})}),Zi=X.merge(Bt),Fi=Y.extend({method:f("tasks/result"),params:ue.extend({taskId:c()})}),LR=X.loose(),Ki=jt.extend({method:f("tasks/list")}),Wi=Lt.extend({tasks:l(Bt)}),Ji=Y.extend({method:f("tasks/cancel"),params:ue.extend({taskId:c()})}),BR=X.merge(Bt),Vi=m({uri:c(),mimeType:j(c()),_meta:U(c(),B()).optional()}),Yi=Vi.extend({text:c()}),An=c().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Xi=Vi.extend({blob:An}),Nt=se(["user","assistant"]),lt=m({audience:l(Nt).optional(),priority:C().min(0).max(1).optional(),lastModified:di.datetime({offset:!0}).optional()}),Qi=m({...ut.shape,...Dt.shape,uri:c(),description:j(c()),mimeType:j(c()),size:j(C()),annotations:lt.optional(),_meta:j(G({}))}),pp=m({...ut.shape,...Dt.shape,uriTemplate:c(),description:j(c()),mimeType:j(c()),annotations:lt.optional(),_meta:j(G({}))}),lp=jt.extend({method:f("resources/list")}),mp=Lt.extend({resources:l(Qi)}),hp=jt.extend({method:f("resources/templates/list")}),fp=Lt.extend({resourceTemplates:l(pp)}),vn=ue.extend({uri:c()}),gp=vn,yp=Y.extend({method:f("resources/read"),params:gp}),wp=X.extend({contents:l(O([Yi,Xi]))}),Sp=ge.extend({method:f("notifications/resources/list_changed"),params:fe.optional()}),Rp=vn,_p=Y.extend({method:f("resources/subscribe"),params:Rp}),bp=vn,Cp=Y.extend({method:f("resources/unsubscribe"),params:bp}),xp=fe.extend({uri:c()}),Ap=ge.extend({method:f("notifications/resources/updated"),params:xp}),vp=m({name:c(),description:j(c()),required:j(P())}),Ip=m({...ut.shape,...Dt.shape,description:j(c()),arguments:j(l(vp)),_meta:j(G({}))}),kp=jt.extend({method:f("prompts/list")}),Pp=Lt.extend({prompts:l(Ip)}),Up=ue.extend({name:c(),arguments:U(c(),c()).optional()}),Tp=Y.extend({method:f("prompts/get"),params:Up}),In=m({type:f("text"),text:c(),annotations:lt.optional(),_meta:U(c(),B()).optional()}),kn=m({type:f("image"),data:An,mimeType:c(),annotations:lt.optional(),_meta:U(c(),B()).optional()}),Pn=m({type:f("audio"),data:An,mimeType:c(),annotations:lt.optional(),_meta:U(c(),B()).optional()}),Op=m({type:f("tool_use"),name:c(),id:c(),input:U(c(),B()),_meta:U(c(),B()).optional()}),zp=m({type:f("resource"),resource:O([Yi,Xi]),annotations:lt.optional(),_meta:U(c(),B()).optional()}),Ep=Qi.extend({type:f("resource_link")}),Un=O([In,kn,Pn,Ep,zp]),Mp=m({role:Nt,content:Un}),qp=X.extend({description:c().optional(),messages:l(Mp)}),Hp=ge.extend({method:f("notifications/prompts/list_changed"),params:fe.optional()}),Dp=m({title:c().optional(),readOnlyHint:P().optional(),destructiveHint:P().optional(),idempotentHint:P().optional(),openWorldHint:P().optional()}),jp=m({taskSupport:se(["required","optional","forbidden"]).optional()}),ea=m({...ut.shape,...Dt.shape,description:c().optional(),inputSchema:m({type:f("object"),properties:U(c(),Z).optional(),required:l(c()).optional()}).catchall(B()),outputSchema:m({type:f("object"),properties:U(c(),Z).optional(),required:l(c()).optional()}).catchall(B()).optional(),annotations:Dp.optional(),execution:jp.optional(),_meta:U(c(),B()).optional()}),Lp=jt.extend({method:f("tools/list")}),Bp=Lt.extend({tools:l(ea)}),ta=X.extend({content:l(Un).default([]),structuredContent:U(c(),B()).optional(),isError:P().optional()}),NR=ta.or(X.extend({toolResult:B()})),Np=wr.extend({name:c(),arguments:U(c(),B()).optional()}),Gp=Y.extend({method:f("tools/call"),params:Np}),$p=ge.extend({method:f("notifications/tools/list_changed"),params:fe.optional()}),GR=m({autoRefresh:P().default(!0),debounceMs:C().int().nonnegative().default(300)}),ra=se(["debug","info","notice","warning","error","critical","alert","emergency"]),Zp=ue.extend({level:ra}),Fp=Y.extend({method:f("logging/setLevel"),params:Zp}),Kp=fe.extend({level:ra,logger:c().optional(),data:B()}),Wp=ge.extend({method:f("notifications/message"),params:Kp}),Jp=m({name:c().optional()}),Vp=m({hints:l(Jp).optional(),costPriority:C().min(0).max(1).optional(),speedPriority:C().min(0).max(1).optional(),intelligencePriority:C().min(0).max(1).optional()}),Yp=m({mode:se(["auto","required","none"]).optional()}),Xp=m({type:f("tool_result"),toolUseId:c().describe("The unique identifier for the corresponding tool call."),content:l(Un).default([]),structuredContent:m({}).loose().optional(),isError:P().optional(),_meta:U(c(),B()).optional()}),Qp=pn("type",[In,kn,Pn]),yr=pn("type",[In,kn,Pn,Op,Xp]),el=m({role:Nt,content:O([yr,l(yr)]),_meta:U(c(),B()).optional()}),tl=wr.extend({messages:l(el),modelPreferences:Vp.optional(),systemPrompt:c().optional(),includeContext:se(["none","thisServer","allServers"]).optional(),temperature:C().optional(),maxTokens:C().int(),stopSequences:l(c()).optional(),metadata:Z.optional(),tools:l(ea).optional(),toolChoice:Yp.optional()}),rl=Y.extend({method:f("sampling/createMessage"),params:tl}),nl=X.extend({model:c(),stopReason:j(se(["endTurn","stopSequence","maxTokens"]).or(c())),role:Nt,content:Qp}),ol=X.extend({model:c(),stopReason:j(se(["endTurn","stopSequence","maxTokens","toolUse"]).or(c())),role:Nt,content:O([yr,l(yr)])}),il=m({type:f("boolean"),title:c().optional(),description:c().optional(),default:P().optional()}),al=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()}),sl=m({type:se(["number","integer"]),title:c().optional(),description:c().optional(),minimum:C().optional(),maximum:C().optional(),default:C().optional()}),cl=m({type:f("string"),title:c().optional(),description:c().optional(),enum:l(c()),default:c().optional()}),ul=m({type:f("string"),title:c().optional(),description:c().optional(),oneOf:l(m({const:c(),title:c()})),default:c().optional()}),dl=m({type:f("string"),title:c().optional(),description:c().optional(),enum:l(c()),enumNames:l(c()).optional(),default:c().optional()}),pl=O([cl,ul]),ll=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()}),ml=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()}),hl=O([ll,ml]),fl=O([dl,pl,hl]),gl=O([fl,il,al,sl]),yl=wr.extend({mode:f("form").optional(),message:c(),requestedSchema:m({type:f("object"),properties:U(c(),gl),required:l(c()).optional()})}),Tn=wr.extend({mode:f("url"),message:c(),elicitationId:c(),url:c().url()}),wl=O([yl,Tn]),Sl=Y.extend({method:f("elicitation/create"),params:wl}),Rl=fe.extend({elicitationId:c()}),_l=ge.extend({method:f("notifications/elicitation/complete"),params:Rl}),bl=X.extend({action:se(["accept","decline","cancel"]),content:mn(e=>e===null?void 0:e,U(c(),O([c(),C(),P(),l(c())])).optional())}),Cl=m({type:f("ref/resource"),uri:c()});var xl=m({type:f("ref/prompt"),name:c()}),Al=ue.extend({ref:O([xl,Cl]),argument:m({name:c(),value:c()}),context:m({arguments:U(c(),c()).optional()}).optional()}),vl=Y.extend({method:f("completion/complete"),params:Al});var Il=X.extend({completion:G({values:l(c()).max(100),total:j(C().int()),hasMore:j(P())})}),kl=m({uri:c().startsWith("file://"),name:c().optional(),_meta:U(c(),B()).optional()}),Pl=Y.extend({method:f("roots/list"),params:ue.optional()}),Ul=X.extend({roots:l(kl)}),Tl=ge.extend({method:f("notifications/roots/list_changed"),params:fe.optional()}),$R=O([Li,rp,vl,Fp,Tp,kp,lp,hp,yp,_p,Cp,Gp,Lp,$i,Fi,Ki,Ji]),ZR=O([ji,Bi,ip,Tl,Gi]),FR=O([Di,nl,ol,bl,Ul,Zi,Wi,Ni]),KR=O([Li,rl,Sl,Pl,$i,Fi,Ki,Ji]),WR=O([ji,Bi,Wp,Ap,Sp,$p,Hp,Gi,_l]),JR=O([Di,op,Il,qp,Pp,mp,fp,wp,ta,Bp,Zi,Wi,Ni]),bn=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===Ge.UrlElicitationRequired&&o){let a=o;if(a.elicitations)return new qt(a.elicitations,r)}return new e(t,r,o)}},qt=class extends bn{static{n(this,"UrlElicitationRequiredError")}constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(Ge.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};z();var oa=oe,Ol=i.object({mode:i.literal("auto")}).strict(),zl=i.object({mode:i.literal("manual"),clientId:i.string().trim().min(1),clientSecret:i.string().min(1).optional(),tokenEndpointAuthMethod:_n.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"]})}),ia=i.discriminatedUnion("mode",[Ol,zl]),El=ia.default({mode:"auto"}),Ml=i.object({scopes:i.array(i.string().min(1)).default([]),scopeDelimiter:i.string().min(1).default(" "),clientRegistration:El}).strict(),na=Ml.extend({redirectPath:i.string().startsWith("/auth/connections/")}).strict(),ql=i.discriminatedUnion("mode",[i.object({mode:i.literal("shared-oauth"),oauth:na}).strict(),i.object({mode:i.literal("user-oauth"),oauth:na}).strict()]),Hl=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:Hl}).strict(),Dl=i.object({id:oa,displayName:i.string().min(1),description:i.string().min(1).optional(),serverInfo:pt.optional(),protectedResourceMetadataUrl:i.url().optional(),authMode:Rn,authConfig:ql}).strict().refine(e=>e.authMode===e.authConfig.mode,{message:"authMode must match authConfig.mode",path:["authConfig","mode"]}),jl={id:oa.optional(),displayName:i.string().min(1),summary:i.string().min(1).optional(),serverInfo:pt.optional(),protectedResourceMetadataUrl:i.url().optional()},Ll=i.object({...jl,authMode:Rn,scopes:i.array(i.string().min(1)).default([]),scopeDelimiter:i.string().min(1).default(" "),clientRegistration:ia.optional(),clientId:i.string().trim().min(1).optional(),clientSecret:i.string().min(1).optional(),tokenEndpointAuthMethod:_n.optional()}).strict();function Bl(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
28
+ `)}n(Bl,"formatZodIssues");function Nl(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(Nl,"inferUpstreamConnectionIdFromPolicyName");function aa(e){let t=new URL(e),r=t.pathname==="/"?"":t.pathname;return`${t.origin}/.well-known/oauth-protected-resource${r}`}n(aa,"buildDefaultProtectedResourceMetadataUrl");function mt(e,t){return ce.parse(`${e}:${t}`)}n(mt,"buildUpstreamAuthProfileId");function Gl(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(Gl,"resolveAuthConfig");function _r(e,t){try{let r=Ll.parse(e),o=r.id??(t===void 0?void 0:Nl(t));if(o===void 0)throw new _("MCP token exchange policy options must include id when policy name is unavailable.");return Dl.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:Gl(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
+ ${Bl(r)}`,{cause:r})}throw r}}n(_r,"parseUpstreamTokenExchangePolicyOptions");function sa(e){return e.mode==="shared-oauth"||e.mode==="user-oauth"}n(sa,"isUpstreamOAuthAuthConfig");var $l="mcp-token-exchange-inbound";function ca(e,t,r){let o=new _(t,r===void 0?void 0:{cause:r});return o.extensionMembers={[y]:e},o}n(ca,"configurationProblem");function br(e){return e===$l}n(br,"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??aa(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 re.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&&br(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],Sn(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=_r(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=>Ii(k.policyType)||br(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 zn(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(zn,"buildGatewayConnectionRegistry");var $e,On;function ua(e){On=e,$e=void 0}n(ua,"configureGatewayConnectionRegistrySource");function da(e){$e=e}n(da,"setGatewayConnectionRegistry");function ye(){if(!$e&&On&&($e=zn(On)),!$e)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 $e}n(ye,"getGatewayConnectionRegistry");function Ze(e){let r=ye().byOperationId.get(e);if(!r)throw ca("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(Ze,"getRegisteredMcpRoute");function Cr(e){let r=ye().byRoutePath.get(e);if(!r)throw ca("unknown_mcp_route",`Unknown MCP route: ${e}`,new Error(`Unknown MCP route path "${e}". Ensure routes.oas.json declares this path with operationId and policies.json registers the matching MCP OAuth or MCP token exchange policy.`));return r}n(Cr,"getRegisteredMcpRouteByRoutePath");function pa(){return $e}n(pa,"tryGetGatewayConnectionRegistry");z();var b=i.string().datetime({offset:!0}).brand();function x(e){return b.parse(e.toISOString())}n(x,"toIsoTimestamp");function ke(e,t){return new Date(e.getTime()+t*1e3)}n(ke,"addSeconds");z();function T(e){return new URL(e).origin}n(T,"readGatewayRequestOrigin");function Pe(e){return T(e)}n(Pe,"readGatewayOAuthIssuer");function En(e){return e.length>512?`${e.slice(0,512)}\u2026`:e}n(En,"truncate");function la(e){return"cause"in e?e.cause:void 0}n(la,"readCause");function ie(e,t,r){if(!(r instanceof Error)){r!=null&&(e[`${t}Message`]=En(String(r)));return}e[`${t}Name`]=r.name,e[`${t}Message`]=En(r.message);let o=la(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`]=En(o.message),o=la(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 ma(e,t){let r=Object.entries(t).filter(o=>o[1]!==void 0);r.length!==0&&e.log.setLogProperties?.(Object.fromEntries(r))}n(ma,"setLogProperties");function xr(e,t){ma(e,{subjectId:t.subjectId})}n(xr,"applyGatewayPrincipalLogProperties");function ha(e,t){ma(e,{upstreamServerId:t.upstreamServerId,operationId:t.operationId})}n(ha,"applyGatewayRouteLogProperties");function fa(e){let t=K(e);return{title:t.title,body:t.publicDetail}}n(fa,"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=K(o.code),s=o.privateDetail??(Ar(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 qe(e,t,r){let o=K(r.code),a=Yl(r.code,r.detail),s=Ar(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(qe,"gatewayProblemResponse");function Ar(e){return K(e).status<500}n(Ar,"canExposeGatewayProblemDetail");function Vl(e){return!e.privateDetail||Ar(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=K(e);return Ar(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 ya=[{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=>$(e),"accepts"),matches:n((e,t)=>$(e)&&$(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 wa(e){let t=ya.find(r=>r.accepts(e.url,e.context));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}n(wa,"evaluateBuiltInRedirectUriCompatibility");function ga(e){try{return new URL(e)}catch{return}}n(ga,"parseUrl");function Sa(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=ga(e.registeredRedirectUri),r=ga(e.requestedRedirectUri);if(t===void 0||r===void 0)return!1;let o=e.context??{source:"registration_match"};return ya.some(a=>a.matches?.(t,r,o))}n(Sa,"redirectUriMatchesBuiltInCompatibility");z();var rm=43,nm=128,om=/^[A-Za-z0-9._~-]+$/,Mn="S256",vr=i.literal(Mn),Ir=i.string().min(rm).max(nm).regex(om);function kr(e){return e.replace(/^\/+/,"").split("/").map(t=>encodeURIComponent(t)).join("/")}n(kr,"encodeMcpRoutePathForScopedOAuthRoute");function Ra(e){let t=typeof e=="string"?e:"";return t===""?"":`/${t.replace(/^\/+/,"")}`}n(Ra,"decodeMcpRoutePathFromScopedOAuthParam");z();var _a=["none","client_secret_post","client_secret_basic"],qn=[..._a,"private_key_jwt"],im=["awaiting_login","awaiting_setup"],am=i.string().min(1).brand(),W=i.string().min(1).brand(),Gt=i.uuid().brand(),pe=i.uuid().brand(),Pr=i.uuid().brand(),ba=i.enum(_a),Ca=i.enum(qn),N_=i.enum(im),xa=i.object({client_id:W,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:Ca.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."})}),Hn=i.object({clientId:W,clientName:i.string().min(1),redirectUris:i.array(i.string().min(1)),tokenEndpointAuthMethod:Ca,hashedClientSecret:i.string().optional(),clientSecretExpiresAt:b.optional(),clientExpiresAt:b,revokedAt:b.optional(),createdAt:b}),Dn=i.object({clientId:W,resource:i.string(),operationId:re,subjectId:am,scope:i.string(),roles:i.array(i.string()),createdAt:b,expiresAt:b}),G_=Dn.extend({id:pe,redirectUri:i.string(),clientState:i.string().optional(),codeChallenge:i.string(),codeChallengeMethod:vr}),jn=Dn.extend({id:Gt,currentRefreshTokenHash:i.string().optional(),previousRefreshTokenHash:i.string().optional(),previousRefreshTokenRotatedAt:b.optional(),revokedAt:b.optional(),revokedReason:i.string().optional()}),Ur=Dn.extend({tokenHash:i.string(),grantId:Gt,revokedAt:b.optional()});function Ln(){return pe.parse(crypto.randomUUID())}n(Ln,"createDownstreamAuthorizationTransactionId");function Bn(){return Pr.parse(crypto.randomUUID())}n(Bn,"createDownstreamBrowserLoginStateId");function Aa(){return Gt.parse(crypto.randomUUID())}n(Aa,"createDownstreamGrantId");var E="mcp:tools";function va(e,t){return Sa({registeredRedirectUri:e,requestedRedirectUri:t,context:{source:"registration_match"}})}n(va,"redirectUriMatchesRegistration");function Ia(e){return $(e)&&e.pathname==="/oauth/dev-login"}n(Ia,"isLoopbackDevLoginUrl");function Tr(e,t){return new URL(e,Pe(t)).toString()}n(Tr,"buildGatewayOAuthUrl");function Nn(e){let t=Ze(re.parse(e.operationId));return new URL(t.routePath,T(e.requestUrl)).toString()}n(Nn,"buildScopedAuthorizationServerIssuer");function sm(e){let t=Ze(re.parse(e.operationId));return new URL(`/oauth/authorize/${kr(t.routePath)}`,T(e.requestUrl)).toString()}n(sm,"buildScopedAuthorizationEndpoint");function Gn(e){let t=F();return{issuer:Pe(e),authorization_endpoint:Tr("/oauth/authorize",e),token_endpoint:Tr("/oauth/token",e),registration_endpoint:Tr("/oauth/register",e),revocation_endpoint:Tr("/oauth/revoke",e),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],scopes_supported:[E],code_challenge_methods_supported:[Mn],token_endpoint_auth_methods_supported:qn,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":Ci(t)}}n(Gn,"buildAuthorizationServerMetadata");function ka(e){let t=Nn(e);return{...Gn(e.requestUrl),issuer:t,authorization_endpoint:sm(e)}}n(ka,"buildScopedAuthorizationServerMetadata");var Pa=Ht;async function Ua(e,t){try{let r=Or(e.params.routePath);return Response.json(cm(r.operationId,e.url))}catch(r){let o=de(r);return qe(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(Ua,"protectedResourceMetadataHandler");function cm(e,t){let r=Ze(e);return{resource:ht(r.operationId,t),resource_name:r.routePath,authorization_servers:[Nn({operationId:r.operationId,requestUrl:t})],bearer_methods_supported:["header"],scopes_supported:[E],mcp_protocol_version:Pa}}n(cm,"buildProtectedResourceMetadataResponseBody");function ht(e,t){let r=Ze(e);return new URL(r.routePath,T(t)).toString()}n(ht,"buildCanonicalMcpResourceForRoute");function Ta(e,t){let r=Ze(e);return new URL(`/.well-known/oauth-protected-resource/${kr(r.routePath)}`,T(t)).toString()}n(Ta,"buildProtectedResourceMetadataUrlForRoute");function Or(e){return Cr(Ra(e))}n(Or,"getRegisteredMcpRouteByExternalPathParam");var um=i.record(i.string(),i.unknown()),Oa=i.string().min(1),dm=i.union([Oa.transform(e=>[e]),i.array(Oa)]),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"],za=new Me("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===Pe(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 Zn(e,t){za.set(e,t)}n(Zn,"setGatewayPrincipal");function Fn(e){return za.get(e)}n(Fn,"readGatewayPrincipal");function Ea(e,t){let r=Fn(t);if(r)return r;let o=Fe(e.user,e.url);return Zn(t,o),xr(t,o),o}n(Ea,"readOrHydrateGatewayPrincipal");function zr(e){let r=['realm="OAuth"',`resource_metadata="${$n(Ta(e.operationId,e.requestUrl))}"`];return e.error!==void 0&&r.push(`error="${e.error}"`),e.errorDescription!==void 0&&r.push(`error_description="${$n(e.errorDescription)}"`),e.scope!==void 0&&r.push(`scope="${$n(e.scope)}"`),`Bearer ${r.join(", ")}`}n(zr,"buildGatewayBearerChallenge");function $n(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($n,"sanitizeQuotedHeaderParameter");z();z();function Ma(e){return new w({message:e,extensionMembers:{[y]:"invalid_request"}})}n(Ma,"invalidReturnTo");function Er(e){if(e===void 0||e.length===0)return;if(!e.startsWith("/")||e.startsWith("//"))throw Ma("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 Ma("returnTo must be a same-origin relative path without credentials or fragments.");return`${t.pathname}${t.search}`}n(Er,"parseSafeRelativeReturnTo");z();var ym=["user","shared"],ft=i.enum(ym);function gt(e){return{mode:"user",subjectId:e}}n(gt,"buildUserUpstreamConnectionOwner");function Mr(){return{mode:"shared"}}n(Mr,"buildSharedUpstreamConnectionOwner");var qa=i.object({ownerMode:ft,initiatedBySubjectId:q,ownerSubjectId:q.optional(),upstreamServerId:oe,authProfileId:ce,operationId:re,returnTo:i.string().min(1).transform(e=>Er(e)).optional()});function Ha(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(Ha,"validateUpstreamOwnerState");var yt=qa.superRefine(Ha),Da=qa.omit({returnTo:!0}).superRefine(Ha);function $t(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($t,"buildUpstreamOwnerState");function qr(e){if(e.ownerMode==="shared")return Mr();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(qr,"resolveUpstreamConnectionOwnerFromState");var wm=["active","not_connected","reconsent_required"],Sm=["basic_auth_app_password","bearer_token"],ja=i.string().trim().min(1).brand(),wt=i.uuid().brand(),Zt=i.uuid().brand(),Kn=i.enum(wm),Rm=i.enum(Sm),La=i.object({encryptedClientInformation:i.string().optional(),encryptedDiscoveryState:i.string().optional(),connectedBySubjectId:q.optional()}),_m=La.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:ja,subjectId:q.optional(),ownerMode:ft,upstreamServerId:oe,authProfileId:ce,status:Kn,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 Wn(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(Wn,"validateUpstreamConnectionOwnerShape");var St=bm.superRefine(Wn);function Ba(e){return JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId])}n(Ba,"readUpstreamConnectionLookupKey");var Jn=yt.extend({id:wt,callbackPath:i.string().min(1),expiresAt:b,codeVerifier:i.string().optional(),redirectUri:i.url(),returnOrigin:i.url().optional()}).extend(La.shape);function Na(e){let t=e?.status??"not_connected",r={connected:t==="active",status:t};return e?.updatedAt!==void 0&&(r.updatedAt=e.updatedAt),r}n(Na,"readUpstreamConnectionStatus");function Ga(){return ja.parse(`mcpgw2uc_${crypto.randomUUID()}`)}n(Ga,"createUpstreamConnectionId");function $a(){return wt.parse(crypto.randomUUID())}n($a,"createOAuthStateId");function Za(){return Zt.parse(crypto.randomUUID())}n(Za,"createBrowserConnectTicketId");z();var Yn=i.discriminatedUnion("mode",[i.object({mode:i.literal("user"),subjectId:q}).strict(),i.object({mode:i.literal("shared")}).strict()]),Ka=i.object({owner:Yn,upstreamServerId:oe,authProfileId:ce}).strict(),Wa=i.object({items:i.array(Ka).min(1).max(100)}).strict(),Xn=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(),Ja=St.omit({createdAt:!0,updatedAt:!0}).strict().superRefine(Wn),Va=St.strict(),Ya=i.object({owner:Yn,upstreamServerId:oe,authProfileId:ce}).strict(),Xa=i.object({owner:Yn,upstreamServerId:oe,authProfileId:ce,connection:St.strict().optional(),connectionStatus:i.object({connected:i.boolean(),status:Kn,updatedAt:St.shape.updatedAt.optional()}).strict()}).strict(),Cm=i.enum(["none","client_secret_basic","client_secret_post","private_key_jwt"]),Ke=i.object({clientId:W,clientName:i.string().min(1),tokenEndpointAuthMethod:Cm}).strict(),Qn=i.discriminatedUnion("method",[i.object({method:i.literal("none"),clientId:W}).strict(),i.object({method:i.enum(["client_secret_basic","client_secret_post"]),clientId:W,clientSecretHashInput:i.string().min(1)}).strict(),i.object({method:i.literal("private_key_jwt"),clientId:W}).strict()]),eo=i.object({id:pe,currentStateHash:i.string().min(1),clientId:W,redirectUri:i.string().min(1),resource:i.string().min(1),operationId:re,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(),Fa=eo.omit({id:!0,consumedAt:!0}).extend({transactionId:pe,client:Ke.optional()}).strict(),to=i.object({subjectId:q,roles:i.array(i.string()).optional()}).strict(),xm=eo.extend({phase:i.literal("awaiting_login")}).strict(),Vn=eo.extend({phase:i.literal("awaiting_setup"),principal:to}).strict(),Am=i.discriminatedUnion("phase",[xm,Vn]),Hr=i.object({transaction:Am,client:Ke}).strict(),Qa=Hn.omit({revokedAt:!0}).strict(),es=i.discriminatedUnion("kind",[i.object({kind:i.literal("registered"),client:Ke}).strict(),i.object({kind:i.literal("already_exists")}).strict()]),ts=i.object({clientId:W}).strict(),rs=i.discriminatedUnion("kind",[i.object({kind:i.literal("found"),client:Hn.strict()}).strict(),i.object({kind:i.literal("missing")}).strict()]),ns=i.discriminatedUnion("phase",[Fa.extend({phase:i.literal("awaiting_login")}).strict(),Fa.extend({phase:i.literal("awaiting_setup"),principal:to}).strict()]),os=i.discriminatedUnion("kind",[Hr.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()]),is=i.object({transactionId:pe,currentStateHash:i.string().min(1),now:b}).strict(),as=i.discriminatedUnion("kind",[Hr.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()]),ss=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:to,now:b}).strict(),cs=i.discriminatedUnion("kind",[Hr.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()]),us=i.object({transactionId:pe,currentStateHash:i.string().min(1),currentPrincipal:i.object({subjectId:q}).strict(),now:b}).strict(),ds=i.discriminatedUnion("kind",[Hr.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()]),ps=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:Gt,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()]),ls=i.discriminatedUnion("kind",[i.object({kind:i.literal("approved"),transaction:Vn,client:Ke}).strict(),i.object({kind:i.literal("cancelled"),transaction:Vn,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()]),ms=i.object({clientAuth:Qn,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(),hs=i.discriminatedUnion("kind",[i.object({kind:i.literal("exchanged"),client:Ke,grant:jn.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()]),fs=i.object({clientAuth:Qn,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(),gs=i.discriminatedUnion("kind",[i.object({kind:i.literal("rotated"),client:Ke,grant:jn.strict(),accessToken:Ur.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()]),ys=i.object({clientAuth:Qn,tokenHash:i.string().min(1),now:b}).strict(),ws=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()]),Ss=i.object({tokenHash:i.string().min(1),now:b}).strict(),Rs=i.discriminatedUnion("kind",[i.object({kind:i.literal("valid"),record:Ur.strict()}).strict(),i.object({kind:i.literal("missing")}).strict(),i.object({kind:i.literal("expired")}).strict(),i.object({kind:i.literal("revoked")}).strict()]),_s=i.object({accessTokenHash:i.string().min(1),resource:i.string().min(1),operationId:re,upstreamConnectionKeys:i.array(Ka).max(100),now:b}).strict(),bs=i.discriminatedUnion("kind",[i.object({kind:i.literal("authorized"),principal:i.object({subjectId:q,roles:i.array(i.string())}).strict(),accessToken:Ur.strict(),upstreamConnections:Xn.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()]),Cs=i.object({record:Jn}).strict(),xs=i.object({kind:i.literal("saved")}).strict(),As=i.object({id:wt,now:b}).strict(),vs=i.discriminatedUnion("kind",[i.object({kind:i.literal("available"),record:Jn}).strict(),i.object({kind:i.literal("consumed")}).strict(),i.object({kind:i.literal("missing")}).strict()]),Is=i.object({id:Zt,expiresAt:b,now:b}).strict(),ks=i.discriminatedUnion("kind",[i.object({kind:i.literal("available")}).strict(),i.object({kind:i.literal("consumed")}).strict()]);var Ps=100,vm=new Set(["undefined","null","nan"]);function Us(e){return e!==null&&typeof e=="object"}n(Us,"isProblemDetailsShape");var Ts="bckt_";function J(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(Ts))throw We("internal_server_error",`MCP Gateway runtime storage bucket ID must start with "${Ts}".`);return`/zups/v2/buckets/${encodeURIComponent(t)}/mcp/storage/${e}`}n(J,"buildStoragePath");function Im(){return J("upstream-connections/batch-get")}n(Im,"buildBatchGetUpstreamConnectionsPath");function km(){return J("upstream-connections/upsert")}n(km,"buildUpsertUpstreamConnectionPath");function Pm(){return J("authorization/read-setup")}n(Pm,"buildReadAuthorizationSetupPath");function Um(){return J("oauth/register-client")}n(Um,"buildRegisterClientPath");function Tm(){return J("oauth/read-client")}n(Tm,"buildReadClientPath");function Om(){return J("authorization/start")}n(Om,"buildStartAuthorizationPath");function zm(){return J("authorization/read-pending")}n(zm,"buildReadPendingAuthorizationPath");function Em(){return J("authorization/advance-pending")}n(Em,"buildAdvancePendingAuthorizationPath");function Mm(){return J("authorization/mark-setup-approved")}n(Mm,"buildMarkAuthorizationSetupApprovedPath");function qm(){return J("authorization/decide-setup")}n(qm,"buildDecideAuthorizationSetupPath");function Hm(){return J("token/exchange-authorization-code")}n(Hm,"buildExchangeAuthorizationCodePath");function Dm(){return J("token/refresh")}n(Dm,"buildRefreshTokenPath");function jm(){return J("token/revoke")}n(jm,"buildRevokeOAuthTokenPath");function Lm(){return J("token/validate-access-token")}n(Lm,"buildValidateAccessTokenPath");function Bm(){return J("mcp/authorize-and-load-connections")}n(Bm,"buildAuthorizeAndLoadConnectionsPath");function Nm(){return J("upstream-oauth-state/save")}n(Nm,"buildSaveUpstreamOAuthStatePath");function Gm(){return J("upstream-oauth-state/consume")}n(Gm,"buildConsumeUpstreamOAuthStatePath");function $m(){return J("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 Es(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(Es,"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??"")&&oo(e.scopes,t.scopes)&&no(e.expiresAt,t.expiresAt)&&Wm(e.metadata,t.metadata)}n(Km,"connectionMatchesUpsertRecord");function no(e,t){return e===void 0||t===void 0?e===t:Date.parse(e)===Date.parse(t)}n(no,"optionalTimestampInstantsMatch");function Os(e,t){return Date.parse(e)<=Date.parse(t)}n(Os,"timestampInstantIsAtOrBefore");function oo(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}n(oo,"stringArraysMatch");function Wm(e,t){let r=zs(e),o=zs(t),a=Object.fromEntries(o);return r.length===o.length&&r.every(([s,u])=>a[s]===u)}n(Wm,"metadataMatches");function zs(e){return Object.entries(e??{}).filter(t=>t[1]!==void 0)}n(zs,"definedMetadataEntries");function H(e,t){throw We("internal_server_error",e,t)}n(H,"throwInvalidStorageResponse");function We(e,t,r){let o=gr[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 Ms(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&&!Es(o.connection,a)&&H("Gateway Service storage response connection did not match the response key.")}}n(Ms,"validateUpstreamConnectionItemsMatchLookups");function Vm(e,t){Fm(e,t)||H("Gateway Service storage response authorization setup did not match the request."),e.connection!==void 0&&!Es(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||!no(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 ro(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(ro,"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||!no(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||!Os(e.accessToken.expiresAt,t.accessTokenExpiresAt)||!Os(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||!oo(e.principal.roles,e.accessToken.roles))&&H("Gateway Service storage response MCP authorization did not match the request."),Ms(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&&oo(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=Us(t)&&typeof t.status=="number"?t.status:e.status,o=Us(t)&&Ie(t.code)?t.code:Ti(r);throw We(o,`Gateway Service storage request failed with HTTP ${r}.`)}n(sh,"throwRuntimeHttpStorageError");var Dr=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"});si(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=Ba(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+=Ps){let d=r.slice(u,u+Ps);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:Ja,responseSchema:Va});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:Pm(),requestSchema:Ya,responseSchema:Xa});return Vm(o,r),o}async registerClient(t){let{request:r,response:o}=await this.#e({input:t,path:Um(),requestSchema:Qa,responseSchema:es});return Ym(o,r),o}async readClient(t){let{request:r,response:o}=await this.#e({input:t,path:Tm(),requestSchema:ts,responseSchema:rs});return Xm(o,r),o}async startAuthorization(t){let{request:r,response:o}=await this.#e({input:t,path:Om(),requestSchema:ns,responseSchema:os});return Qm(o,r),o}async readPendingAuthorization(t){let{request:r,response:o}=await this.#e({input:t,path:zm(),requestSchema:is,responseSchema:as});return ro(o,r),o}async advancePendingAuthorization(t){let{request:r,response:o}=await this.#e({input:t,path:Em(),requestSchema:ss,responseSchema:cs});return ro(o,r),o}async markAuthorizationSetupApproved(t){let{request:r,response:o}=await this.#e({input:t,path:Mm(),requestSchema:us,responseSchema:ds});return ro(o,r),o}async decideAuthorizationSetup(t){let{request:r,response:o}=await this.#e({input:t,path:qm(),requestSchema:ps,responseSchema:ls});return eh(o,r),o}async saveUpstreamOAuthState(t){let{response:r}=await this.#e({input:t,path:Nm(),requestSchema:Cs,responseSchema:xs});return r}async consumeUpstreamOAuthState(t){let{request:r,response:o}=await this.#e({input:t,path:Gm(),requestSchema:As,responseSchema:vs});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:Is,responseSchema:ks});return r}async exchangeAuthorizationCode(t){let{request:r,response:o}=await this.#e({input:t,path:Hm(),requestSchema:ms,responseSchema:hs});return th(o,r),o}async refreshToken(t){let{request:r,response:o}=await this.#e({input:t,path:Dm(),requestSchema:fs,responseSchema:gs});return rh(o,r),o}async revokeOAuthToken(t){let{response:r}=await this.#e({input:t,path:jm(),requestSchema:ys,responseSchema:ws});return r}async validateAccessToken(t){let{request:r,response:o}=await this.#e({input:t,path:Lm(),requestSchema:Ss,responseSchema:Rs});return nh(o,r),o}async authorizeAndLoadConnections(t){let{request:r,response:o}=await this.#e({input:t,path:Bm(),requestSchema:_s,responseSchema:bs});return oh(o,r),o}async#o(t){let r={items:[...t]},{response:o}=await this.#e({input:r,path:Im(),requestSchema:Wa,responseSchema:Xn});return Ms(o.items,t),o.items.map(a=>a.connection)}};var ch="__zuploMcpGatewayStorageBackend",io;function uh(){return new Dr({})}n(uh,"buildProductionStorageBackend");function A(){let e=globalThis[ch];return e||(io||(io=uh()),io)}n(A,"getStorage");function dh(e,t){let r=Fn(e),o=hr(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 yi(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 ao}from"jose";var ph="sha256:",lh=32;function qs(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(qs,"copyToArrayBuffer");function Ue(){let e=crypto.getRandomValues(new Uint8Array(lh));return ao.encode(e)}n(Ue,"createOpaqueToken");async function M(e){let t=await crypto.subtle.digest("SHA-256",qs(new TextEncoder().encode(e)));return`${ph}${ao.encode(new Uint8Array(t))}`}n(M,"hashOpaqueValue");async function Hs(e){let t=await crypto.subtle.digest("SHA-256",qs(new TextEncoder().encode(e)));return ao.encode(new Uint8Array(t))}n(Hs,"calculatePkceS256Challenge");function mh(e){let t=e.headers.get("authorization"),[r,o]=t?.split(/\s+/,2)??[];if(!(r?.toLowerCase()!=="bearer"||!o))return o}n(mh,"readBearerToken");function hh(e,t,r){return qe(e,t,{code:"authentication_required",detail:"Gateway access token is required.",headers:{"WWW-Authenticate":r}})}n(hh,"gatewayAuthenticationRequiredResponse");function fh(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(fh,"tokenValidationReasonCode");async function gh(e,t,r){let o=await A().validateAccessToken({tokenHash:await M(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=fh(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(gh,"validateGatewayAccessToken");function yh(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(yh,"assertAccessTokenResource");function wh(e,t,r){return qe(e,t,{code:"forbidden",detail:"Gateway access token is missing the required MCP scope.",headers:{"WWW-Authenticate":zr({operationId:r,requestUrl:e.url,error:"insufficient_scope",errorDescription:`The access token is missing the ${E} scope required by this MCP resource.`,scope:E})}})}n(wh,"insufficientScopeResponse");function Sh(e){return{subjectId:e.subjectId,roles:e.roles}}n(Sh,"principalFromAccessToken");async function Rh(e){switch((await A().authorizeAndLoadConnections({accessTokenHash:await M(e.token),resource:e.resource,operationId:e.operationId,upstreamConnectionKeys:[],now:x(new Date)})).kind){case"authorized":return;case"resource_mismatch":throw R("authentication_required","Gateway access token was not issued for this MCP resource.");case"principal_mismatch":throw R("authentication_required","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(Rh,"assertCompositeMcpAuthorization");function _h(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"),qe(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":zr({operationId:e.operationId,requestUrl:e.request.url,error:"invalid_token",errorDescription:"The access token is expired, malformed, or invalid."})}})}n(_h,"gatewayTokenRejectedResponse");async function so(e,t,r){let o=ht(r.operationId,e.url),a=mh(e),s=zr({operationId:r.operationId,requestUrl:e.url,scope:E});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"}),hh(e,t,s);try{let u=await gh(a,t,r.operationId);if(yh({accessToken:u,resource:o,operationId:r.operationId},t),u.scope!==E)return t.log.warn({event:"gateway_access_token_insufficient_scope",code:"forbidden",tokenScope:u.scope,requiredScope:E,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:E,clientId:u.clientId}}),I(t,{eventType:v.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:r.operationId,httpStatusCode:403,reasonClass:"auth",reasonCode:"insufficient_scope"}),wh(e,t,r.operationId);await Rh({token:a,resource:o,operationId:r.operationId});let d=Sh(u);Zn(t,d),xr(t,d),I(t,{eventType:v.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED,outcome:"success",virtualServerName:r.operationId,attributes:{clientId:u.clientId}});let p=new Headers(e.headers);return p.delete("authorization"),new mr(e,{headers:p})}catch(u){return _h({request:e,context:t,error:u,operationId:r.operationId})}}n(so,"gatewayTokenInbound");var Rt={OAUTH_PROTECTED_RESOURCE_METADATA:"oauth_metadata",VIRTUAL_MCP_SERVER:"gateway",OTHER:"other"},bh="oauth-protected-resource-metadata",Ch="/.well-known/oauth-protected-resource/";function xh(e){let r=(typeof e.route.raw=="function"?e.route.raw():void 0)?.operationId;return typeof r=="string"?r:void 0}n(xh,"readRouteOperationId");function Ah(e){return e.hasGatewayRouteContext?Rt.VIRTUAL_MCP_SERVER:e.routeOperationId===bh||e.routeOperationId===void 0&&e.routePath.startsWith(Ch)?Rt.OAUTH_PROTECTED_RESOURCE_METADATA:Rt.OTHER}n(Ah,"classifyAnalyticsRouteSurface");function vh(e){let t=e.route.path;return{routePath:t,routeSurface:Ah({routePath:t,routeOperationId:xh(e),hasGatewayRouteContext:hr(e)!==void 0})}}n(vh,"readAnalyticsRequestContext");function Ih(e){return e.response.status===405&&e.response.headers.has("allow")&&e.routeSurface===Rt.VIRTUAL_MCP_SERVER}n(Ih,"isIntentionalMethodRejection");function kh(e){return Ih(e)||e.response.status===401&&e.routeSurface===Rt.OAUTH_PROTECTED_RESOURCE_METADATA?"success":e.response.status>=400?"failure":"success"}n(kh,"classifyRequestCompletedOutcome");async function co(e,t){let r=Date.now(),o=vh(t);return I(t,{eventType:v.MCP_REQUEST_RECEIVED,outcome:"success",routeSurface:o.routeSurface,httpMethod:e.method}),dn.getContextExtensions(t).addHandlerResponseHook(a=>{let s=kh({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(co,"analyticsContextInbound");function Ph(e){return e instanceof Response}n(Ph,"isResponse");async function Mt(e,t){let r=Cr(t.route.path),o={operationId:r.operationId};Ri(t,o),ha(t,o);let a=await co(e,t);return Ph(a)?a:so(a,t,{operationId:r.operationId})}n(Mt,"mcpOAuthInboundPolicy");var Uh=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.'}),Th=i.object({auth0Domain:Uh,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(),uo=class extends it{static{n(this,"McpAuth0OAuthInboundPolicy")}#t;constructor(t,r){let o=Ds(t,r);super(o,r),this.#t=js(o,r)}async handler(t,r){return ot("policy.inbound.mcp-auth0-oauth"),st(r,this.#t),Mt(t,r)}};function Ds(e,t){return fr(Th,e,`MCP Auth0 OAuth policy "${t}"`)}n(Ds,"parseAuth0OAuthOptions");function Pi(e,t="mcp-auth0-oauth-inbound"){let r=Ds(e,t);return js(r,t)}n(Pi,"auth0OptionsToMcpOAuthRuntimeConfig");function js(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 Ai({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(js,"buildAuth0McpOAuthRuntimeConfig");function Oh(e){let t=xn.safeParse(e);return t.success?t.data.id:void 0}n(Oh,"parseJsonRpcRequestId");function Ls(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Oh(t)}catch{return}}n(Ls,"readJsonRpcRequestIdFromBody");function Bs(e){return Rr.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(Bs,"jsonRpcErrorResponse");function Ns(e){return new qt([Tn.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Ns,"urlElicitationRequiredError");function He(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(He,"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 po(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(po,"getUpstreamAuthConfig");function Je(e,t){let r=po({upstreamServerId:e,authProfileId:t});if(!sa(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 jr(e){return Re(e).ownerMode}n(jr,"resolveOwnerModeForUpstreamAuthMode");var lo;lo=globalThis.crypto;async function Mh(e){return(await lo).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 lo).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 mo(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(mo,"pkceChallenge");z();var Q=pi().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:fi.custom,message:"URL must be parseable",fatal:!0}),ui}).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"}),Lr=G({resource:c().url(),authorization_servers:l(Q).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:P().optional(),authorization_details_types_supported:l(c()).optional(),dpop_signing_alg_values_supported:l(c()).optional(),dpop_bound_access_tokens_required:P().optional()}),Ft=G({issuer:c(),authorization_endpoint:Q,token_endpoint:Q,registration_endpoint:Q.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:Q.optional(),revocation_endpoint:Q.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:P().optional()}),jh=G({issuer:c(),authorization_endpoint:Q,token_endpoint:Q,userinfo_endpoint:Q.optional(),jwks_uri:Q,registration_endpoint:Q.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:P().optional(),request_parameter_supported:P().optional(),request_uri_parameter_supported:P().optional(),require_request_uri_registration:P().optional(),op_policy_uri:Q.optional(),op_tos_uri:Q.optional(),client_id_metadata_document_supported:P().optional()}),Br=m({...jh.shape,...Ft.pick({code_challenge_methods_supported:!0}).shape}),_t=m({access_token:c(),id_token:c().optional(),token_type:c(),expires_in:gi.number().optional(),scope:c().optional(),refresh_token:c().optional()}).strip(),$s=m({error:c(),error_description:c().optional(),error_uri:c().optional()}),Gs=Q.optional().or(f("").transform(()=>{})),Lh=m({redirect_uris:l(Q),token_endpoint_auth_method:c().optional(),grant_types:l(c()).optional(),response_types:l(c()).optional(),client_name:c().optional(),client_uri:Q.optional(),logo_uri:Gs,scope:c().optional(),contacts:l(c()).optional(),tos_uri:Gs,policy_uri:c().optional(),jwks_uri:Q.optional(),jwks:mi().optional(),software_id:c().optional(),software_version:c().optional(),software_statement:c().optional()}).strip(),ho=m({client_id:c(),client_secret:c().optional(),client_id_issued_at:C().optional(),client_secret_expires_at:C().optional()}).strip(),Kt=Lh.merge(ho),Ax=m({error:c(),error_description:c().optional()}).strip(),vx=m({token:c(),token_type_hint:c().optional()}).strip();function Zs(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(Zs,"resourceUrlFromServerUrl");function Fs({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(Fs,"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}},Wt=class extends N{static{n(this,"InvalidRequestError")}};Wt.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 Jt=class extends N{static{n(this,"UnsupportedGrantTypeError")}};Jt.errorCode="unsupported_grant_type";var Vt=class extends N{static{n(this,"InvalidScopeError")}};Vt.errorCode="invalid_scope";var Yt=class extends N{static{n(this,"AccessDeniedError")}};Yt.errorCode="access_denied";var Te=class extends N{static{n(this,"ServerError")}};Te.errorCode="server_error";var Xt=class extends N{static{n(this,"TemporarilyUnavailableError")}};Xt.errorCode="temporarily_unavailable";var Qt=class extends N{static{n(this,"UnsupportedResponseTypeError")}};Qt.errorCode="unsupported_response_type";var er=class extends N{static{n(this,"UnsupportedTokenTypeError")}};er.errorCode="unsupported_token_type";var tr=class extends N{static{n(this,"InvalidTokenError")}};tr.errorCode="invalid_token";var rr=class extends N{static{n(this,"MethodNotAllowedError")}};rr.errorCode="method_not_allowed";var nr=class extends N{static{n(this,"TooManyRequestsError")}};nr.errorCode="too_many_requests";var Qe=class extends N{static{n(this,"InvalidClientMetadataError")}};Qe.errorCode="invalid_client_metadata";var or=class extends N{static{n(this,"InsufficientScopeError")}};or.errorCode="insufficient_scope";var ir=class extends N{static{n(this,"InvalidTargetError")}};ir.errorCode="invalid_target";var Ks={[Wt.errorCode]:Wt,[Ve.errorCode]:Ve,[Ye.errorCode]:Ye,[Xe.errorCode]:Xe,[Jt.errorCode]:Jt,[Vt.errorCode]:Vt,[Yt.errorCode]:Yt,[Te.errorCode]:Te,[Xt.errorCode]:Xt,[Qt.errorCode]:Qt,[er.errorCode]:er,[tr.errorCode]:tr,[rr.errorCode]:rr,[nr.errorCode]:nr,[Qe.errorCode]:Qe,[or.errorCode]:or,[ir.errorCode]:ir};function Bh(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(Bh,"isClientAuthMethod");var fo="code",go="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 Js(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=$s.parse(JSON.parse(r)),{error:a,error_description:s,error_uri:u}=o,d=Ks[a]||Te;return new d(s||"",u)}catch(o){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new Te(a)}}n(Js,"parseErrorResponse");async function wo(e,t){try{return await yo(e,t)}catch(r){if(r instanceof Ve||r instanceof Xe)return await e.invalidateCredentials?.("all"),await yo(e,t);if(r instanceof Ye)return await e.invalidateCredentials?.("tokens"),await yo(e,t);throw r}}n(wo,"auth");async function yo(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 Ys(p,{fetchFn:s}),!d)try{d=await Vs(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 V=await Xh(t,{resourceMetadataUrl:g,fetchFn:s});p=V.authorizationServerUrl,h=V.authorizationServerMetadata,d=V.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 V=h?.client_id_metadata_document_supported===!0,ee=e.clientMetadataUrl;if(ee&&!So(ee))throw new Qe(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ee}`);if(V&&ee)ne={client_id:ee},await e.saveClientInformation?.(ne);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let ii=await nf(p,{metadata:h,clientMetadata:e.clientMetadata,scope:k,fetchFn:s});await e.saveClientInformation(ii),ne=ii}}let Se=!e.redirectUrl;if(r!==void 0||Se){let V=await rf(e,p,{metadata:h,resource:D,authorizationCode:r,fetchFn:s});return await e.saveTokens(V),"AUTHORIZED"}let Ee=await e.tokens();if(Ee?.refresh_token)try{let V=await tf(p,{metadata:h,clientInformation:ne,refreshToken:Ee.refresh_token,resource:D,addClientAuthentication:e.addClientAuthentication,fetchFn:s});return await e.saveTokens(V),"AUTHORIZED"}catch(V){if(!(!(V instanceof N)||V instanceof Te))throw V}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(yo,"authInternal");function So(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(So,"isHttpsUrl");async function Kh(e,t,r){let o=Zs(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!Fs({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 Vs(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 Lr.parse(await o.json())}n(Vs,"discoverOAuthProtectedResourceMetadata");async function Ro(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Ro(e,void 0,r):void 0;throw o}}n(Ro,"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 Ws(e,t,r=fetch){return await Ro(e,{"MCP-Protocol-Version":t},r)}n(Ws,"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??Ht,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 Ws(u,s,r);if(!o?.metadataUrl&&Jh(d,a.pathname)){let p=new URL(`/.well-known/${t}`,a);d=await Ws(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 Ys(e,{fetchFn:t=fetch,protocolVersion:r=Ht}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},a=Yh(e);for(let{url:s,type:u}of a){let d=await Ro(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"?Ft.parse(await d.json()):Br.parse(await d.json())}}}n(Ys,"discoverAuthorizationServerMetadata");async function Xh(e,t){let r,o;try{r=await Vs(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 Ys(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(fo))throw new Error(`Incompatible auth server: does not support response type ${fo}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(go))throw new Error(`Incompatible auth server: does not support code challenge method ${go}`)}else d=new URL("/authorize",e);let p=await mo(),h=p.code_verifier,g=p.code_challenge;return d.searchParams.set("response_type",fo),d.searchParams.set("client_id",r.client_id),d.searchParams.set("code_challenge",g),d.searchParams.set("code_challenge_method",go),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 Xs(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 Js(h);return _t.parse(await h.json())}n(Xs,"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 Xs(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 Xs(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 Js(u);return Kt.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 bo(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(bo,"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 Qs(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(Qs,"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 ec(e){let t=Qs(e);return t!==void 0&&uf.some(r=>df(t,r))}n(ec,"isPrivateIpv4");function _o(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(_o,"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=Qs(t);if(r!==void 0)return r.join(".");let[o,a,s]=t.split(":"),u=_o(o),d=_o(a);return s===void 0&&u!==void 0&&d!==void 0?pf(u,d):void 0}n(lf,"parseIpv6MappedIpv4");function mf(e){return _o(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||ec(o)}let r=mf(t);return r===void 0?!1:(r&65024)===64512||(r&65472)===65152}n(hf,"isPrivateIpv6");function Co(e){let t=ve(e);return cf.has(t)||t.endsWith(".internal")||ec(t)||hf(t)}n(Co,"isBlockedOutboundHostname");function tc(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw _e(`Unsupported outbound protocol: ${t.protocol}`);bo(t,e);let r=$(t);if(t.protocol==="http:"&&!r)throw _e("Configured outbound HTTP URLs must target loopback hosts.");let o=ve(t.hostname);if(!r&&Co(o))throw _e(`Blocked outbound host: ${o}`);return t}n(tc,"validateConfiguredOutboundUrl");function rc(e){let t=new URL(e),r=$(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.");bo(t,e);let a=ve(t.hostname);if(!r&&Co(a))throw _e(`Blocked identity provider host: ${a}`);return t}n(rc,"validateIdentityProviderUrl");function nc(e,t){let r=new URL(e),o=r.protocol==="http:"&&$(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(bo(r,e),!o&&Co(r.hostname))throw _e(`CIMD ${t} points at a blocked host.`);return r}n(nc,"validateCimdUrl");function Nr(e){return nc(e,"client_id")}n(Nr,"validateCimdClientMetadataUrl");function oc(e){return nc(e,"jwks_uri")}n(oc,"validateCimdClientJwksUrl");function ic(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(ic,"mergeAbortSignals");async function ff(e){try{await e.cancel()}catch{}}n(ff,"cancelReader");async function Gr(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(Gr,"readBoundedByteStream");var gf=2,yf=1024*1024,wf=1e4,Sf=new Set([301,302,303,307,308]),Rf=["authorization","proxy-authorization","cookie","cookie2"];function xo(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(xo,"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),Gr(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 ac(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(ac,"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 ar(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(ar,"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";ar(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 Pf(e,t,r,o,a){let s={...e,method:t,redirect:"manual",signal:r};return o&&(s.headers=kf(e.headers,a)),s}n(Pf,"buildRedirectInit");function Uf(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(Uf,"buildInitialRequestInit");function Tf(e){let t=bt(e.currentInput,e.currentInit);If({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=ac(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:Pf(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(Tf,"followRedirect");async function Ao(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=ic(g,t.signal),k=!1,ne=setTimeout(()=>{k=!0,g.abort()},u),Se=e,Ee=Uf(e,t,g.signal),xe;try{xe=ac(xo(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(Ae){throw ar(h,{event:"outbound_url_blocked",problemCode:o,method:bt(e,t),host:we(xo(e)),error:Ae}),clearTimeout(ne),D?.(),Ae}let Ot=0;try{for(;;){let Ae=await vf(h,d,Se,Ee,o,xe,()=>k?`timeout_after_${u}ms`:void 0),V=xf(Ae,xe);if(V!==void 0)try{let ee=Tf({currentInput:Se,currentInit:Ee,currentUrl:xe,redirectUrl:V,redirects:Ot,maxRedirects:a,problemCode:o,validateUrl:r.validateUrl,signal:g.signal,additionalCrossOriginStrippedHeaders:p});Se=ee.currentInput,Ee=ee.currentInit,xe=ee.currentUrl,Ot=ee.redirects;continue}catch(ee){throw ar(h,{event:"outbound_redirect_blocked",problemCode:o,method:bt(Se,Ee),host:we(xe),error:ee,extra:{redirects:Ot,maxRedirects:a,redirectTargetHost:we(V)}}),ee}try{return Cf(Ae,await bf(Ae,s,o))}catch(ee){throw ar(h,{event:"outbound_response_size_exceeded",problemCode:o,method:bt(Se,Ee),host:we(xe),error:ee,extra:{maxResponseBytes:s,status:Ae.status}}),ee}}}finally{clearTimeout(ne),D?.()}}n(Ao,"runSafeOutboundExchange");async function $r(e,t,r){let o=await Ao(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(a){throw ar(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:bt(e,t),host:we(xo(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($r,"runSafeOutboundJsonExchange");function sc(e,t={},r={}){return Ao(e,t,{...r,validateUrl:tc})}n(sc,"fetchConfiguredOutbound");function cc(e,t={},r={}){return $r(e,t,{...r,validateUrl:rc})}n(cc,"fetchIdentityProviderJson");function uc(e,t={},r={}){return $r(e,t,{...r,validateUrl:Nr})}n(uc,"fetchCimdClientMetadataJson");function dc(e,t={},r={}){return $r(e,t,{...r,validateUrl:oc})}n(dc,"fetchCimdClientJwksJson");z();import{errors as wc,jwtVerify as Sc,SignJWT as Rc}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,pc=new Map,lc=new Map,qf;function Hf(){return qf??nt.instance.authPrivateKey}n(Hf,"readAuthPrivateKey");function mc(e){return new te(Ef,e===void 0?void 0:{cause:e})}n(mc,"createGeneratedKeyMaterialError");function hc(e,t){let r=Of.decode(t);if(r.byteLength!==Mf)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(hc,"decodeJwkKeyField");function Df(e){let t=Hf();if(!t)throw mc();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=hc("d",r.d);hc("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 mc(r)}}n(Df,"decodeGeneratedKeyMaterial");function jf(e){let t=pc.get(e);return t||(t=Df(e),pc.set(e,t)),t}n(jf,"getMasterKeyMaterial");async function be(e){let t=lc.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(jf(e.keyMaterialPurpose));return lc.set(e.purpose,r),r}n(be,"readCachedDerivedKey");var Lf="SHA-256";var Bf="zuplo-mcp-gateway:",Nf=new TextEncoder,fc=new WeakMap;async function De(e,t){let r=fc.get(e);r||(r=new Map,fc.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(De,"deriveGatewaySigningKey");async function Gf(e,t){let r=gc(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:gc(a)},o,32*8);return new Uint8Array(s)}n(Gf,"hkdfExpand");function gc(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(gc,"copyToArrayBuffer");var _c=15*60,$f=15*60,Zf=Da.extend({id:wt}),Ff=Zf.extend({exp:i.number().int().positive(),iat:i.number().int().positive().optional()}),bc=yt.extend({id:Zt,purpose:i.literal("browser_connect")}),Kf=yt.extend({purpose:i.literal("browser_connect")}),Wf=bc.extend({exp:i.number().int().positive(),iat:i.number().int().positive().optional()}),Cc=_c*1e3;async function xc(){return be({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>De(e,"oauth-state"),"derive")})}n(xc,"getOAuthStateKey");async function Ac(){return be({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>De(e,"browser-connect"),"derive")})}n(Ac,"getBrowserConnectKey");async function vc(e){let t=Math.floor(Date.now()/1e3)+_c;return new Rc(e).setProtectedHeader({alg:me,typ:"JWT"}).setIssuer(ae).setAudience(le).setIssuedAt().setExpirationTime(t).sign(await xc())}n(vc,"signOAuthState");async function Zr(e){try{let{payload:t}=await Sc(e,await xc(),{algorithms:[me],issuer:ae,audience:le});return Ff.parse(t)}catch(t){throw t instanceof wc.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(Zr,"verifyOAuthState");async function Ic(e){let t=Math.floor(Date.now()/1e3)+$f,r=Kf.parse(e),o=bc.parse({...r,id:Za()});return new Rc(o).setProtectedHeader({alg:me,typ:"JWT"}).setIssuer(ae).setAudience(le).setIssuedAt().setExpirationTime(t).sign(await Ac())}n(Ic,"signBrowserConnectTicket");async function kc(e){try{let{payload:t}=await Sc(e,await Ac(),{algorithms:[me],issuer:ae,audience:le});return Wf.parse(t)}catch(t){throw t instanceof wc.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(kc,"verifyBrowserConnectTicket");async function Pc(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(Pc,"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=T(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 Ic({...$t(e),purpose:"browser_connect"})),r.toString()}n(Vf,"buildGatewayBrowserTicketUrl");function Yf(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}n(Yf,"buildGatewayConnectPath");async function vo(e){return Vf({...e,path:Yf(e.upstreamServerId),redirect:!0})}n(vo,"buildGatewayConnectUrl");async function Fr(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 vo(t),message:Jf(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(Fr,"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 Io(e){return`Zuplo MCP Gateway - ${e}`}n(Io,"buildGatewayOAuthClientName");function Tc(e,t){let r=new URL(e,T(t));return $(r)&&ve(r.hostname)!=="localhost"&&(r.hostname="localhost"),r.toString()}n(Tc,"buildGatewayOAuthRedirectUri");function ko(e){let t=new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin);return t.searchParams.set("authProfileId",e.authProfileId),t.toString()}n(ko,"buildOAuthClientMetadataDocumentUrl");function Oc(e){return T(e)}n(Oc,"requireOAuthClientMetadataOrigin");function zc(e,t,r){let o=He(t),a=Je(t,r);return{client_id:ko({origin:e,upstreamServerId:t,authProfileId:r}),client_name:Io(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(zc,"buildOAuthClientMetadataDocument");z();import{base64url as je}from"jose";var Qf="SHA-256",xt="AES-GCM",eg=12,Uo="zuplo-secret",To=1,Ec="generated:auth_private_key:token-encryption",tg=i.object({version:i.literal(To),keyId:i.literal(Ec),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 Po(){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(Po,"getEncryptionKey");function Mc(e){return Ct(new TextEncoder().encode(`${Uo}:v${e.version}:${e.keyId}`))}n(Mc,"getAssociatedData");function rg(e){return`${Uo}:v${e.version}:${je.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(rg,"encodeEnvelope");function ng(e){let t=`${Uo}:v${To}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(je.decode(r));return tg.parse(JSON.parse(o))}n(ng,"decodeEnvelope");async function Kr(e){let t=await Po(),r=crypto.getRandomValues(new Uint8Array(eg)),o={version:To,keyId:Ec},a=await crypto.subtle.encrypt({name:xt,iv:r,additionalData:Mc(o)},t,new TextEncoder().encode(e));return rg({...o,algorithm:xt,iv:je.encode(r),ciphertext:je.encode(new Uint8Array(a))})}n(Kr,"encryptSecret");async function sr(e){let t=ng(e);if(t){let u=await Po(),d=await crypto.subtle.decrypt({name:xt,iv:Ct(je.decode(t.iv)),additionalData:Mc(t)},u,Ct(je.decode(t.ciphertext)));return new TextDecoder().decode(d)}let[r,o]=e.split(".");if(!r||!o)throw new te("Encrypted payload is malformed");let a=await Po(),s=await crypto.subtle.decrypt({name:xt,iv:Ct(je.decode(r))},a,Ct(je.decode(o)));return new TextDecoder().decode(s)}n(sr,"decryptSecret");var og=i.union([Kt,ho]),ig=i.object({authorizationServerUrl:i.url(),resourceMetadataUrl:i.url().optional(),resourceMetadata:Lr.optional(),authorizationServerMetadata:i.union([Ft,Br]).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 Ir.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 qc(e){if(e!==void 0)return Kr(JSON.stringify(e))}n(qc,"encryptJson");async function Hc(e,t){if(!e)return;let r=await sr(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(Hc,"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=He(e),a=Je(e,t),s;return a.scopes.length>0&&(s=a.scopes.join(a.scopeDelimiter)),{client_name:Io(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 Kt.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=ko({origin:new URL(r).origin,upstreamServerId:e,authProfileId:t});return So(o)?o:void 0}n(fg,"buildClientMetadataUrl");function Dc(e){for(let t of e)if(t!==void 0)return t}n(Dc,"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 Dc([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(yg,"readEncryptedClientInformation");function wg(e){return Dc([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 vc({id:t.id,...$t({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 qc(t),await this.syncPendingState(!1))}async discoveryState(){return this.loadPersistedDiscoveryState()}async saveDiscoveryState(t){this.cachedDiscoveryState=t,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await qc(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 Kr(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:_t.parse({...r,refresh_token:await sr(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let s={id:this.connection?.id??Ga(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await Kr(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:$a(),...$t({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()+Cc)),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 Hc(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 Hc(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 sr(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await sr(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 jc(e){return async(t,r)=>{let o=Ag(t),a=await sc(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(jc,"createUpstreamOAuthFetch");async function Lc(e,t){try{return await wo(e,{serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:jc(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(Lc,"runUpstreamOAuth");async function Ig(e,t){return wo(e,{serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:jc(t.upstreamServerId)})}n(Ig,"exchangeUpstreamAuthorizationCode");async function Bc(e,t){let r=await Lc(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(Bc,"requireUpstreamAuthorizationRedirect");async function Nc(e){if(!e.forceRefresh&&bg(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await Lc(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(Nc,"authorizeUpstreamOAuthSession");async function kg(e){let t=await Zr(e.stateToken),r=await A().consumeUpstreamOAuthState({id:t.id,now:x(new Date)}),o=Pg(r);return Ug({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),Tg(o),o}n(kg,"consumeStoredCallbackState");function Pg(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(Pg,"readConsumedCallbackState");function Ug(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(Ug,"assertStoredCallbackStateMatches");function Tg(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new w({message:"OAuth state has expired",extensionMembers:{[y]:"oauth_state_expired"}})}n(Tg,"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),Fr(t)}n(Og,"buildOAuthConnectRequiredResponse");async function Gc(e){let t=await kg({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=qr(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(Gc,"finishUpstreamOAuthCallback");async function $c(e){let t=He(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:T(e.request.url)}}}n($c,"prepareUpstreamOAuthRequest");async function Zc(e){let t=await $c(e),r=new et({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Bc(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Zc,"startUpstreamConnect");async function Fc(e){let t=await $c(e),r=new et({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return Nc({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(Fc,"authorizeUpstreamRequest");async function Oo(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return Fc({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 te(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(Oo,"resolveUpstreamCredentialForRoute");async function Kc(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 Zc(r);break;case"none":throw new te(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(Kc,"startUpstreamConnectForRequest");async function Wc(e){let r=(await Zr(e.callbackRequest.state)).authProfileId,o=po({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r});if(Re(o.mode).callbackSupport!=="authorization_code")throw new te(`Upstream server ${e.callbackRequest.upstreamServerId} does not support OAuth callbacks.`);return Gc({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:He(e.callbackRequest.upstreamServerId)})}n(Wc,"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 Vc(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(Vc,"buildRouteAuthBaseFromPolicyOptions");function Yc(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(Yc,"resolveRouteAuthBase");function Jc(e,t){switch(e){case"user":return gt(t.subjectId);case"shared":return Mr()}}n(Jc,"buildOwnerForPrincipal");function Wr(e,t){switch(e.ownerMode){case"shared":return{...e,owner:Jc(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"user":return{...e,owner:Jc(e.ownerMode,t),initiatedBySubjectId:t.subjectId}}}n(Wr,"resolveRouteAuthForPrincipal");var Eg=Ge.InvalidRequest,Mg=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function qg(e){let t=e.route.raw();return re.parse(t?.operationId)}n(qg,"readOperationId");async function Hg(e,t,r,o){let a=await Oo({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 mr(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 Xc(e,t){let r=t.authUrl===void 0?void 0:Ns({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(Bs({id:Ls(e),error:{code:r?.code??Eg,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(Xc,"connectRequiredJsonRpcResponse");async function Ng(e){let t=await Oo({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 Xc(e.requestBody,o.payload);if(o.kind==="response")return o.response;let a=Ei({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return ai.fetch(a.url,a.init)})}n(Gg,"installUpstreamAuthRetryHook");async function zo(e,t,r){let o=qg(t),a=await Bg(e),s=Vc({connection:r,operationId:o}),u=Wr(s,Ea(e,t)),d=await Hg(e,u,r,t);if(!(d instanceof Response)&&d.kind==="connect_required")return Xc(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(zo,"mcpTokenExchangePolicy");var Eo=class extends it{static{n(this,"McpTokenExchangeInboundPolicy")}constructor(t,r){let o=_r(t,r);super(o,r)}async handler(t,r){return ot("policy.inbound.mcp-token-exchange"),zo(t,r,this.options)}};z();var Qc=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[Qc]===!0}n(Zg,"isHtml");function eu(e){return e==null||e===!1?"":Array.isArray(e)?e.map(eu).join(""):Zg(e)?e.value:$g(String(e))}n(eu,"renderValue");function Oe(e){return{[Qc]:!0,value:e}}n(Oe,"trustedHtml");var tt=Oe("");function L(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=eu(t[o]),r+=e[o+1]??"";return Oe(r)}n(L,"html");function At(e){return e.value}n(At,"renderHtml");function tu(e){return L`<p data-gateway-error-code="${e.code}">${e.detail}</p>${e.guidance} ${e.action}`}n(tu,"renderBrowserErrorPage");var vt=Oe('*,: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>
30
30
  ${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};
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 Mo="zuplo.com";function ru(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(ru,"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 Jr=ru(Mo);function Vr(e){let t=e.toLowerCase();return t===Mo||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?ru(Mo):Fg(e)}n(Vr,"resolveIconHref");function Yr(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(Yr,"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=Vr(e.host),r=Wg(e.kind??"authorization_failed");return new Response(At(It({title:e.title??r.title,iconHref:t,styles:vt,headerIcon:Yr({iconHref:t,fallbackIconHref:Jr}),heading:e.title??r.title,subhead:"",body:tu({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 nu="application/json",Vg="application/x-www-form-urlencoded";function Xr(e,t){return new w({message:e,extensionMembers:{[y]:"invalid_request"}},t===void 0?void 0:{cause:t})}n(Xr,"invalidRequestError");function Yg(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}n(Yg,"normalizeContentType");function Xg(e,t){return e===t?!0:t===nu&&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 Xr(`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 Xr(`${r} exceeded the maximum allowed size.`)}n(ey,"assertContentLengthWithinLimit");async function ou(e,t){let r=t.label??"Request body";Qg(e,t.expectedContentTypes),ey(e,t.maxBytes,r);let o=await Gr(e.body,{maxBytes:t.maxBytes,createLimitError:n(()=>Xr(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(o)}n(ou,"readBoundedTextBody");async function iu(e,t){let r=await ou(e,{...t,expectedContentTypes:[nu]});try{return JSON.parse(r)}catch(o){throw Xr("Request body must be valid JSON.",o)}}n(iu,"readBoundedJsonBody");async function au(e,t){let r=await ou(e,{...t,expectedContentTypes:[Vg]});return new URLSearchParams(r)}n(au,"readBoundedFormUrlEncodedBody");z();z();import{errors as mu,jwtVerify as hu,SignJWT as fu}from"jose";z();import{errors as ly,jwtVerify as my,SignJWT as hy}from"jose";function Le(e){let t=F().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(Le,"requireBrowserLoginField");z();import{createRemoteJWKSet as ry,errors as cr,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 cr.JWTExpired?"expired":e instanceof cr.JWTClaimValidationFailed?"claim":e instanceof cr.JWSSignatureVerificationFailed?"signature":e instanceof cr.JWKSNoMatchingKey?"jwks_no_match":e instanceof cr.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()),qo;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(!qo){let e=F();qo=ry(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return qo}n(py,"readFederatedJwks");async function su(e){let t=F(),r=Le("tokenUrl"),o=Le("clientId"),a=Le("clientSecret"),s=new URL("/oauth/callback",Pe(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 cc(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(su,"exchangeFederatedAuthorizationCode");var Do="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 cu(){return be({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>De(e,"browser-session"),"derive")})}n(cu,"getBrowserSessionKey");function Ho(e){let t=new URL(T(e)),r=[`${Do}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(Ho,"buildBrowserSessionEvictionCookie");function yy(e){let t=new URL(T(e.requestUrl)),r=[`${Do}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(yy,"serializeSessionCookie");function uu(){return new URL(Le("url")).origin}n(uu,"readBrowserLoginOrigin");function jo(){return F().browserLogin.stateTtlSeconds}n(jo,"readBrowserLoginStateTtlSeconds");function du(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(du,"resolveCurrentRequestPrincipal");async function Qr(e,t={}){let r=gy(e.headers.get("cookie")).get(Do);if(!r)return{};try{let{payload:o}=await my(r,await cu(),{algorithms:[me],issuer:ae,audience:le}),a=fy.parse(o);if(a.browserLoginOrigin!==uu())return{evictCookie:Ho(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:Ho(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:Ho(e.url)})}}n(Qr,"readBrowserSession");async function en(e){let t=F().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:uu()};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 cu());return yy({value:o,requestUrl:e.requestUrl,ttlSeconds:t})}n(en,"createBrowserSessionCookie");async function pu(e){let t={};e.context!==void 0&&(t.context=e.context);let r=await Qr(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 su({code:o,nonce:e.stateId,requestUrl:e.request.url,...e.context===void 0?{}:{context:e.context}})}n(pu,"resolveBrowserLoginCallbackPrincipal");function lu(e){let t=F().browserLogin,r=new URL(Le("url")),o=new URL("/oauth/callback",Pe(e.requestUrl));return Ia(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",Le("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(lu,"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:Pr,exp:i.number().int().positive(),iat:i.number().int().positive().optional()}),_y=i.object({purpose:i.literal("gateway_authorization_setup"),transactionId:pe,stateId:Pr,exp:i.number().int().positive(),iat:i.number().int().positive().optional()});async function gu(){return be({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>De(e,"browser-login"),"derive")})}n(gu,"getBrowserLoginKey");async function yu(){return be({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>De(e,"authorization-csrf"),"derive")})}n(yu,"getCsrfKey");function wu(e){return{now:e.now??new Date,ttlSeconds:jo()}}n(wu,"readPendingTransactionDependencies");function by(e,t){return e.subjectId===t.subjectId}n(by,"principalsMatch");function Su(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}n(Su,"toPendingPrincipal");function Ru(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(ke(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:Su(e.principal)}}n(Ru,"createTransactionRecord");async function _u(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(_u,"startPendingTransaction");async function Cy(e){return new fu({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 gu())}n(Cy,"signBrowserLoginState");async function bu(e){return new fu({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:Bn()}).setProtectedHeader({alg:me,typ:"JWT"}).setIssuer(ae).setAudience(le).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await yu())}n(bu,"signCsrfToken");async function Lo(e){try{let{payload:t}=await hu(e,await gu(),{algorithms:[me],issuer:ae,audience:le}),r=Ry.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof mu.JWTExpired?R("oauth_state_expired","Browser login state has expired.",t):R("oauth_state_invalid","Browser login state could not be verified.",t)}}n(Lo,"verifyBrowserLoginStateToken");async function tn(e){try{let{payload:t}=await hu(e,await yu(),{algorithms:[me],issuer:ae,audience:le});return{transactionId:_y.parse(t).transactionId}}catch(t){throw t instanceof mu.JWTExpired?R("oauth_state_expired","Authorization setup state has expired.",t):R("oauth_state_invalid","Authorization setup state could not be verified.",t)}}n(tn,"verifyCsrfToken");function Bo(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}n(Bo,"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 No(e){return e==="principal_mismatch"?"oauth_callback_mismatch":Bo(e==="consumed_already"?"consumed_already":e)}n(No,"setupDecisionErrorCode");async function Cu(e){let t=e.now??new Date,r=await tn(e.csrfToken),o=await A().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await M(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:x(t)});if(o.kind!=="marked")throw R(No(o.kind),"Authorization setup state is invalid, expired, or already used.");return xu({kind:"available",record:o.transaction})}n(Cu,"markSetupApproved");function xu(e){if(e.kind!=="available")throw R(Bo(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(xu,"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 Au(e){let t=e.now??new Date,r=jo(),o=Ln(),a=Bn(),s=await Cy({transactionId:o,stateId:a,ttlSeconds:r}),u=Ru({id:o,transaction:e.transaction,currentStateHash:await M(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 _u({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:lu({state:s,nonce:a,operationId:u.operationId,requestUrl:e.requestUrl})}}n(Au,"startAwaitingLogin");async function vu(e){let{now:t,ttlSeconds:r}=wu(e),o=Ln(),a=await bu({transactionId:o,ttlSeconds:r}),s=Ru({id:o,transaction:e.transaction,currentStateHash:await M(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 _u({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(vu,"startAwaitingSetup");async function Iu(e){let{now:t,ttlSeconds:r}=wu(e),o=await Lo(e.browserLoginStateToken),a=await bu({transactionId:o.transactionId,ttlSeconds:r}),s=Ay(await A().advancePendingAuthorization({transactionId:o.transactionId,expectedPhase:"awaiting_login",currentStateHash:await M(e.browserLoginStateToken),nextStateHash:await M(a),nextPhase:"awaiting_setup",principal:Su(e.principal),now:x(t)}));if(s.kind!=="advanced")throw R(Bo(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(Iu,"completeLogin");async function ku(e){let t=await Go(e);return vy({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}n(ku,"getSetup");async function Go(e){let t=e.now??new Date,r=await tn(e.csrfToken);return xu(xy(await A().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await M(e.csrfToken),now:x(t)})))}n(Go,"getSetupTransaction");async function Iy(e){let t=await tn(e.csrfToken),r=Ue(),o=x(ke(e.now,Sy)),a=await A().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await M(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await M(r),authorizationCodeExpiresAt:o,grantId:Aa(),now:x(e.now)});if(a.kind!=="approved")throw R(a.kind==="cancelled"?"oauth_state_invalid":No(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 tn(e.csrfToken),r=await A().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await M(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:x(e.now)});if(r.kind!=="cancelled")throw R(r.kind==="approved"?"oauth_state_invalid":No(r.kind),"Authorization setup state is invalid, expired, or already used.");return Py({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}n(ky,"createCancelRedirectWithDecision");function Py(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(Py,"buildClientCancelRedirect");async function Pu(e){let t=e.now??new Date;return Iy({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Pu,"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 Uy=1e4,Ty=5*1024,Oy=2,zy=90*24*60*60,$o=["authorization_code","refresh_token"],Zo=["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($o)).min(1).max(2).optional(),response_types:i.array(i.enum(Zo)).min(1).max(1).optional(),scope:i.literal(E).optional(),token_endpoint_auth_method:ba.default("none")});function My(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&$(t))&&t.pathname!=="/"}catch{return!1}}n(My,"isCimdClientIdCandidate");function Pt(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=wa({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(Pt,"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 uc(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:Oy,maxResponseBytes:Ty,timeoutMs:Uy});if(!t.ok)throw R("invalid_request","CIMD metadata could not be fetched.");let o=xa.parse(r);for(let a of o.redirect_uris)Pt(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=Nr(e),r=await Hy({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}n(Dy,"resolveCimdClient");async function rn(e,t){let r=W.parse(e);if(My(r)){if(!F().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(rn,"resolveClient");function Tu(e,t){if(!e.metadata.redirect_uris.some(r=>va(r,t)))throw R("invalid_request","redirect_uri is not registered for the client.")}n(Tu,"assertRedirectRegistered");function jy(e){let t=Ou(e.grant_types),r=e.response_types??[...Zo];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 ${E} scope is supported.`)}n(jy,"assertSupportedDcrRequest");function Ou(e){return e===void 0?[...$o]:Array.from(new Set(e))}n(Ou,"normalizeGrantTypes");function Ly(e){return e.length===0?!1:e.every(t=>$o.includes(t))}n(Ly,"isSupportedGrantTypes");function By(e){return e.length===Zo.length&&e[0]==="code"}n(By,"isSupportedResponseTypes");function Ny(e){return e===void 0||e===E}n(Ny,"isSupportedDcrScope");function ur(e){if(e===void 0||e===E)return E;throw new S("invalid_request",`Only the ${E} scope is supported.`)}n(ur,"assertSupportedOAuthScope");function Ut(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:"&&!$(r))throw new S("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let o=T(e),a=pa(),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(Ut,"resolveResource");async function zu(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)Pt(g,"invalid_redirect_uri","dcr");let r=new Date,o=W.parse(`dcr:${crypto.randomUUID()}`),a=ke(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:Ou(t.grant_types),response_types:["code"],scope:E,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=Ue();p.hashedClientSecret=await M(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(zu,"registerDownstreamClient");function Eu(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(Eu,"renderActions");var zk=Oe('<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 Ek=Oe('<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>'),Mk=Oe('<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 qk=Oe('<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:,",Mu=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);"`,qu=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 Eu({state:e.state,submitOnceAttrs:Mu,authorizeAttrs:tt})}n(Fy,"renderActions");function Fo(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(Fo,"firstUserConnectHref");function Ky(e){let t=e.connectHref?L`<a class="button button--primary" href="${e.connectHref}" ${qu}>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" ${Mu}><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}" ${qu}>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 Ko(e){let t=Zy(e.upstreams),r=Fo(e.upstreams,e.gatewayOrigin,"not_connected"),o=Fo(e.upstreams,e.gatewayOrigin,"reconsent_required"),a=Fo(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(Ko,"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 Hu(e){return e!==void 0&&e.length>0}n(Hu,"hasItems");function Yy(e){let t=e.serverInfo?.icons;return Hu(t)?t:void 0}n(Yy,"readServerIcons");async function Xy(e){if(!(e.returnTo===void 0||!e.isUserOwned))return vo({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?Na(e.connection):{connected:!0,status:"active"}}n(Qy,"readSetupConnectionStatus");function ew(e){let t=Vy(e);return Hu(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=jr(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 Du(e){let t=ye().byOperationId.get(e);if(!t)throw R("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}n(Du,"requireRoute");async function Wo(e){let t=Du(e.transaction.operationId),r=gt(e.transaction.principal.subjectId),o=[],a=new Map,s=t.connection;if(s===void 0)return[];jr(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=jr(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(Wo,"requirementsForSetup");function ow(e){return e.route.connection?.displayName??e.route.operationId}n(ow,"readRouteDisplayName");async function Jo(e){let t=Du(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:T(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(Jo,"consentContext");function Vo(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}n(Vo,"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/{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(" "),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:vr,state:i.string().min(1).optional(),scope:i.literal(E).default(E)}),uw=i.enum(["continue","approve","cancel"]).default("continue"),dw=i.object({state:i.string().min(1),decision:uw}),Be=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 ju(e){return typeof e=="string"&&e.length>0?e:void 0}n(ju,"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=ju(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 Qr(e,r);if(o.principal)return{principal:o.principal};if(!e.user)return o.evictCookie===void 0?{}:{setCookie:o.evictCookie};let a=du(e);return{principal:a,setCookie:await en({principal:a,requestUrl:e.url})}}n(mw,"resolveBrowserPrincipal");async function hw(e,t){let r={};t!==void 0&&(r.context=t);let o=await Qr(e,r);if(!o.principal)throw R("authentication_required","Authorization setup requires a current browser session.");return o.principal}n(hw,"requireSetupPrincipal");function Lu(e){return`/oauth/setup?state=${encodeURIComponent(e)}`}n(Lu,"buildSetupReturnTo");async function Bu(e){let t=await Wo({transaction:e.transaction,requestUrl:e.requestUrl,returnTo:Lu(e.csrfToken)}),r=await Jo({transaction:e.transaction,requestUrl:e.requestUrl}),o={kind:"setup_page",html:Ko({state:e.csrfToken,operationId:e.transaction.operationId,upstreams:t,...r})};return e.setCookie!==void 0&&(o.setCookie=e.setCookie),o}n(Bu,"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 Yo(e,t={}){let r=cw.parse({...e.query,resource:lw(e,t.operationId),state:ju(e.query.state)}),o=ur(r.scope);Pt(r.redirect_uri,"invalid_request","authorize");let a=new Date,s=W.parse(r.client_id),u=await rn(r.client_id,a);Tu(u,r.redirect_uri);try{let d=Ut(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 Au({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 vu({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}}),Bu({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(Yo,"authorizeDownstreamClient");function gw(e){if(e.cause instanceof Be)return e.cause;let t=yw(e.cause);return t?new Be({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 Nu(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 Lo(o),s={request:e,stateId:a.stateId};t.context!==void 0&&(s.context=t.context);let u=await pu(s),d=await Iu({browserLoginStateToken:o,principal:u}),p=await Bu({transaction:d.transaction,csrfToken:d.csrfToken,requestUrl:e.url});return p.setCookie=await en({principal:u,requestUrl:e.url}),p}n(Nu,"completeBrowserLoginCallback");async function Gu(e){let t=F(),r=new URL(e.url);if(!$(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",T(e.url)),s=new URL(T(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 en({principal:u,requestUrl:e.url})}}n(Gu,"completeLocalDevBrowserLogin");function ww(e){let t=e.method==="POST"?e.body:e.query;return dw.parse(t)}n(ww,"readSetupContinueRequest");async function $u(e){let{state:t,decision:r}=ww({method:e.request.method,query:e.request.query,body:e.body}),o=new Date,a=await Go({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 ku({csrfToken:t,currentBrowserPrincipal:s,now:o}),d=await Wo({transaction:u,requestUrl:e.request.url,returnTo:Lu(t)});if(r==="approve"&&Vo(d)&&await Cu({csrfToken:t,currentBrowserPrincipal:s,now:o}),Vo(d)){let p=await Jo({transaction:u,requestUrl:e.request.url});return{kind:"setup_page",html:Ko({state:t,operationId:u.operationId,upstreams:d,...p})}}return{kind:"redirect",location:await Pu({csrfToken:t,currentBrowserPrincipal:s,now:o})}}n($u,"continueDownstreamAuthorizeSetup");z();import{createLocalJWKSet as Sw,decodeJwt as Rw,errors as dr,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,Zu=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",[Zu.extend({grant_type:i.literal("authorization_code"),code:i.string().min(1),redirect_uri:i.string().min(1),code_verifier:Ir,resource:i.url().optional(),scope:i.literal(E).optional()}),Zu.extend({grant_type:i.literal("refresh_token"),refresh_token:i.string().min(1),resource:i.url().optional(),scope:i.literal(E).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 Pw=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()}),Uw=i.object({keys:i.array(i.record(i.string(),i.unknown())).min(1)}).passthrough();function Fu(){return F().gateway.accessTokenTtlSeconds}n(Fu,"readAccessTokenTtlSeconds");function Tw(){return F().gateway.refreshTokenTtlSeconds}n(Tw,"readRefreshTokenTtlSeconds");function Ow(e,t){let r=Fu(),o=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),a=Math.min(r,o);return{expiresAt:x(ke(e,a)),expiresIn:a}}n(Ow,"calculateAccessTokenExpiresAt");function Ku(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(Ku,"readBasicClientSecret");function Wu(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(Wu,"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 dr.JWTExpired?"expired":e instanceof dr.JWTClaimValidationFailed?"claim":e instanceof dr.JWSSignatureVerificationFailed?"signature":e instanceof dr.JWKSNoMatchingKey?"jwks_no_match":e instanceof dr.JWTInvalid?"invalid":e instanceof i.ZodError?"schema":"other"}n(qw,"readJwtFailureKind");async function Hw(e){let{response:t,json:r}=await dc(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 Uw.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=W.parse(e.clientId),r=await rn(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=W.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 M(e.clientSecret)}}n(jw,"buildRuntimeHttpClientAuth");async function Ju(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(Ju,"resolveRuntimeHttpClientAuth");async function Vu(e){kw(e.body);let t=Iw.parse(e.body),r=Ku(e.authorizationHeader),o=Wu({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date,s=await Ju({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(Vu,"exchangeDownstreamToken");async function Lw(e){if(e.parsed.grant_type==="authorization_code"){Pt(e.parsed.redirect_uri,"invalid_request","token"),ur(e.parsed.scope),e.parsed.resource!==void 0&&Ut(e.requestUrl??e.parsed.resource,e.parsed.resource);let u=Ue(),d=Ue(),p=x(ke(e.now,Tw())),h=Ow(e.now,p),g=await A().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await M(e.parsed.code),redirectUri:e.parsed.redirect_uri,...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},codeChallenge:await Hs(e.parsed.code_verifier),currentRefreshTokenHash:await M(u),accessTokenHash:await M(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}}ur(e.parsed.scope),e.parsed.resource!==void 0&&Ut(e.requestUrl??e.parsed.resource,e.parsed.resource);let t=Ue(),r=Ue(),o=x(ke(e.now,Fu())),a=await A().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:await M(e.parsed.refresh_token),nextRefreshTokenHash:await M(t),accessTokenHash:await M(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.");Ut(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 Yu(e){let t=Pw.parse(e.body),r=Ku(e.authorizationHeader),o=Wu({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date;if((await A().revokeOAuthToken({clientAuth:await Ju({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 M(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(Yu,"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 iu(e,{maxBytes:Bw,label:"Request body"})}n(Zw,"readJsonBody");async function Xo(e){return $w(await au(e,{maxBytes:Nw,label:"Request body"}))}n(Xo,"readFormBody");async function Xu(e,t,r){let o=de(r),a=r instanceof i.ZodError?nn(r):void 0,s={code:o??(r instanceof i.ZodError?"invalid_request":"internal_server_error")};return a!==void 0&&(s.detail=a),qe(e,t,s)}n(Xu,"handleProblem");function pr(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(pr,"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=K("internal_server_error");return pr({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:Fw(e,t)})}n(Kw,"oauthProtocolErrorResponse");function Qu(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}n(Qu,"readZodOAuthErrorCode");function Ww(e){let t={error:Qu(e)},r=nn(e);return r!==void 0&&(t.errorDescription=r),pr(t)}n(Ww,"oauthZodErrorResponse");function Jw(e){let t=de(e);if(t===void 0)return;let r=K(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,pr(o)}n(Jw,"oauthGatewayProblemResponse");function Vw(){let t={error:"server_error",status:500,errorDescription:K("internal_server_error").publicDetail};return pr(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 Qo(e,t={}){return e instanceof Be?rd(e):e instanceof S?Kw(e,t):e instanceof i.ZodError?Ww(e):Jw(e)??Vw()}n(Qo,"oauthProblemResponse");function ei(e,t){let r=kt(e.url);if(t instanceof Be)return rd(t);if(t instanceof S){let s=K("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:nn(t)??"The authorization request was invalid.",code:Qu(t)});let o=de(t);if(o!==void 0){let s=K(o);return Ce({host:r,kind:td(o),detail:s.status<500&&t instanceof Error?t.message:s.publicDetail,code:s.oauthError??o,status:s.status})}let a=K("internal_server_error");return Ce({host:r,kind:"internal_error",detail:a.publicDetail,code:"server_error",status:a.status})}n(ei,"browserOAuthProblemResponse");function ed(e,t){let r=kt(e.url),o=de(t);if(o!==void 0){let s=K(o);return Ce({host:r,kind:td(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:nn(t)??"The authorization request was invalid.",code:"invalid_request"});let a=K("internal_server_error");return Ce({host:r,kind:"internal_error",detail:a.publicDetail,code:"internal_server_error",status:a.status})}n(ed,"browserGatewayProblemResponse");function Xw(e){return e==="server_error"?"internal_error":"invalid_request"}n(Xw,"readOAuthBrowserErrorKind");function td(e){if(K(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(td,"readGatewayBrowserErrorKind");function ze(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 Be)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=K(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(ze,"logUnexpectedOAuthHandlerError");function rd(e){let t;try{t=new URL(e.redirectUri)}catch{return pr({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(rd,"downstreamAuthorizeRedirectErrorResponse");function nn(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}n(nn,"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 nd(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(nd,"redirectResultResponse");function on(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 nd(e)}n(on,"authorizeResultResponse");async function od(e,t){try{return Response.json(Gn(e.url))}catch(r){return ze(t,"oauth_authorization_server_metadata_failed",r),Xu(e,t,r)}}n(od,"authorizationServerMetadataHandler");async function id(e,t){try{let r=Or(e.params.routePath);return Response.json(ka({operationId:r.operationId,requestUrl:e.url}))}catch(r){return ze(t,"oauth_authorization_server_metadata_failed",r),Xu(e,t,r)}}n(id,"scopedAuthorizationServerMetadataHandler");async function ad(e,t){try{let r=await zu(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 ze(t,"oauth_register_failed",r),Qo(r)}}n(ad,"registerHandler");async function sd(e,t){try{return on(await Yo(e,{context:t}))}catch(r){return ze(t,"oauth_authorize_failed",r),ei(e,r)}}n(sd,"authorizeHandler");async function cd(e,t){try{let r=Or(e.params.routePath);return on(await Yo(e,{operationId:r.operationId,context:t}))}catch(r){return ze(t,"oauth_authorize_scoped_failed",r),ei(e,r)}}n(cd,"scopedAuthorizeHandler");async function ud(e,t){try{let r=await Nu(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),on(r)}catch(r){return Qw(t,r),ed(e,r)}}n(ud,"callbackHandler");async function dd(e,t){try{return nd(await Gu(e))}catch(r){return ze(t,"oauth_dev_login_failed",r),ei(e,r)}}n(dd,"devLoginHandler");async function pd(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await $u({request:e,body:e.method==="POST"?await Xo(e):void 0,context:t});return on(r)}catch(r){return ze(t,"oauth_setup_failed",r),ed(e,r)}}n(pd,"setupHandler");async function ld(e,t){try{return Response.json(await Vu({body:await Xo(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return ze(t,"oauth_token_failed",r),Qo(r)}}n(ld,"tokenHandler");async function md(e,t){try{return await Yu({body:await Xo(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return ze(t,"oauth_revoke_failed",r),Qo(r)}}n(md,"revokeHandler");var eS={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},hd=new Me("upstream-request");function tS(e){let t=hd.get(e);if(!t)throw new te("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 Tt(e,t){hd.set(e,t)}n(Tt,"setUpstreamRequestContext");function lr(e,t){let r=tS(e),o=nS(t);if(!rS(r.kind,o)){let a=eS[o[0]];throw new te(`${a} request context has not been set`)}return r}n(lr,"requireUpstreamRequestContext");function fd(e){return L`<p data-gateway-error-code="${e.code}">${e.body}</p>`}n(fd,"renderBrowserResult");var oS="text/html; charset=utf-8",iS="none";function aS(e){let t=Vr(e.host);return It({title:e.title,iconHref:t,styles:vt,headerIcon:Yr({iconHref:t,fallbackIconHref:Jr}),heading:e.title,subhead:"",body:fd({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 gd(e){return sS(aS(e))}n(gd,"browserConnectionSuccessResponse");function an(e,t){let r=fa(t);return Ce({host:e,kind:cS(t),detail:r.body,code:t})}n(an,"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 yd(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=pS(r))}n(yd,"addErrorAttributes");function ti(e){if(!(e instanceof w))return;let t=e.extensionMembers?.[y];return Ie(t)?t:void 0}n(ti,"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}}),an(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"),an(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 gd({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 yd(t,"error",e),e instanceof Error&&yd(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:ti(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=ti(t);return an(e,Ui(r)?r:"upstream_token_exchange_failed")}n(wS,"tokenExchangeFailureResponse");async function ri(e,t){let r=lr(t,uS),o=kt(e.url),a=lS(t,r,o);if(a instanceof Response)return a;mS(t,a);try{let s=await Wc({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:ti(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(ri,"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 wd(e,t){let r=lr(t,"connect"),o=await Kc({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 Fr({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(wd,"connectHandler");async function Sd(e,t){let r=lr(t,"client_metadata");try{let o=Oc(e.url),a=zc(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(Sd,"oauthClientMetadataHandler");function Ne(e){if(typeof e=="string"&&e.length!==0)return e}n(Ne,"readOptionalQueryString");function RS(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new te(`Validated path parameter ${t} is missing`);return r}n(RS,"requirePathString");function _S(e){let t=Ne(e);return t?re.parse(t):void 0}n(_S,"readOptionalOperationId");function bS(e,t){let r=Ne(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=Er(Ne(e));return t===void 0?{}:{returnTo:t}}n(xS,"readOptionalReturnTo");function AS(e){let t=Ne(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",...Wr(e,t),...o===void 0?{}:{returnTo:o},redirect:r}}n(IS,"buildConnectContextForPrincipal");function kS(e,t,r){let o=qr(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 PS(e,t){let r=vS(Yc(t,CS(e.query.operationId))),o=e.query.redirect==="true",a=Ne(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 kc(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 Pc(s),kS(r,s,o)}n(PS,"resolveConnectContext");async function US(e,t,r){let o=oe.parse(RS(e,"connection"));switch(r){case"connect":Tt(t,await PS(e,o));return;case"callback":{let a=Ne(e.query.error);if(a){Tt(t,{kind:"callback_provider_error",upstreamServerId:o,error:a,...AS(e)});return}let s=Ne(e.query.code),u=Ne(e.query.state);if(s&&u){Tt(t,{kind:"callback_authorization_code",upstreamServerId:o,code:s,state:u});return}Tt(t,{kind:"callback_invalid",upstreamServerId:o});return}case"client_metadata":Tt(t,{kind:"client_metadata",upstreamServerId:o,authProfileId:bS(e.query.authProfileId,o)});return}}n(US,"resolveUpstreamRequestInbound");async function TS(e,t,r){try{await US(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(TS,"applyUpstreamRequestContext");function sn(e,t){return n(async(o,a)=>{let s=await TS(o,a,e);return s||t(o,a)},"wrapped")}n(sn,"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 ni(e){return async(t,r)=>t.method==="OPTIONS"?zS():ES(await e(t,r))}n(ni,"wrapWellKnownHandler");var bd=[{routeName:"oauth_as_metadata",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:ni(od),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:ni(id),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:ni(Ua),corsPolicy:"anything-goes"},{routeName:"oauth_register",path:"/oauth/register",methods:["POST"],handler:ad},{routeName:"oauth_authorize",path:"/oauth/authorize",methods:["GET"],handler:sd},{routeName:"oauth_authorize_scoped",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:cd},{routeName:"oauth_callback",path:"/oauth/callback",methods:["GET"],handler:ud},{routeName:"oauth_dev_login",path:"/oauth/dev-login",methods:["GET"],handler:dd},{routeName:"oauth_setup",path:"/oauth/setup",methods:["GET","POST"],handler:pd},{routeName:"oauth_token",path:"/oauth/token",methods:["POST"],handler:ld},{routeName:"oauth_revoke",path:"/oauth/revoke",methods:["POST"],handler:md},{routeName:"upstream_client_metadata",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:sn("client_metadata",Sd)},{routeName:"upstream_connect",path:"/auth/connections/:connection/connect",methods:["GET"],handler:sn("connect",wd)},{routeName:"upstream_callback",path:"/auth/connections/:connection/callback",methods:["GET"],handler:sn("callback",ri)}],MS=bd.filter(e=>!e.routeName.startsWith("upstream_")),qS=bd.filter(e=>e.routeName.startsWith("upstream_"));function Cd(e){return e?.some(wn)??!1}n(Cd,"hasMcpOAuthRuntimeConfigPolicy");function xd(e){return e?.some(t=>br(t.policyType))??!1}n(xd,"hasMcpTokenExchangePolicy");function Ad(e){return Cd(e)||xd(e)}n(Ad,"shouldRegisterMcpGatewayInternalRoutes");function HS(e){da(zn({routes:e.routes,policies:e.policies}))}n(HS,"initializeMcpGatewayConnectionRegistry");function DS(e){let t=ki(e.policies);if(!t){let r=[...yn].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 Rd(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(Rd,"wrapInternalHandler");function _d(e,t,r){e.addPluginRoute({path:t.path,methods:t.methods,handler:r,processors:[cn],corsPolicy:t.corsPolicy??"none"})}n(_d,"addInternalRoute");function vd(e,t){HS(t);let r=Cd(t.policies),o=xd(t.policies),a,s=n(()=>(a===void 0&&(a=DS(t)),a),"readOAuthConfig");if(r)for(let u of MS)_d(e,u,Rd(u.routeName,u.handler,s));if(o)for(let u of qS)_d(e,u,Rd(u.routeName,u.handler))}n(vd,"registerMcpGatewayInternalRoutes");function Id(e){ua(e)}n(Id,"configureLazyMcpGatewayState");var oi=class extends ci{static{n(this,"McpGatewayPlugin")}registerRoutes(t){let r=t.parsedRouteData;if(!r||!Ad(r.policies))return;let o={routes:r.routes,policies:r.policies};Id(o),vd(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):wi(e,t)}n(LS,"McpProxyHandler");export{uo as McpAuth0OAuthInboundPolicy,oi as McpGatewayPlugin,fn as McpOAuthInboundPolicy,LS as McpProxyHandler,Eo as McpTokenExchangeInboundPolicy};
33
33
  //# sourceMappingURL=index.js.map