@zuplo/runtime 6.70.37 → 6.70.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/esm/browser-login-idp-HWMCSYMR.js +26 -0
- package/out/esm/browser-login-idp-HWMCSYMR.js.map +1 -0
- package/out/esm/{chunk-YTQ3TTI6.js → chunk-2GVPMQ7M.js} +4 -4
- package/out/esm/{chunk-YTQ3TTI6.js.map → chunk-2GVPMQ7M.js.map} +1 -1
- package/out/esm/{chunk-A2CSR4RF.js → chunk-4SACVMDH.js} +2 -2
- package/out/esm/chunk-FYGTTP3G.js +30 -0
- package/out/esm/chunk-FYGTTP3G.js.map +1 -0
- package/out/esm/{chunk-TOF2KNST.js → chunk-JRXZBVXH.js} +2 -2
- package/out/esm/{chunk-2VLXJLVI.js → chunk-ZIKV2LUM.js} +3 -3
- package/out/esm/{chunk-2VLXJLVI.js.map → chunk-ZIKV2LUM.js.map} +1 -1
- package/out/esm/index.js +1 -1
- package/out/esm/internal/index.js +1 -1
- package/out/esm/mcp-gateway/index.js +3 -7
- package/out/esm/mcp-gateway/index.js.map +1 -1
- package/out/esm/mocks/index.js +1 -1
- package/out/types/mcp-gateway/index.d.ts +57 -0
- package/package.json +1 -1
- /package/out/esm/{chunk-YTQ3TTI6.js.LEGAL.txt → chunk-2GVPMQ7M.js.LEGAL.txt} +0 -0
- /package/out/esm/{chunk-A2CSR4RF.js.map → chunk-4SACVMDH.js.map} +0 -0
- /package/out/esm/{chunk-TOF2KNST.js.map → chunk-JRXZBVXH.js.map} +0 -0
- /package/out/esm/{chunk-2VLXJLVI.js.LEGAL.txt → chunk-ZIKV2LUM.js.LEGAL.txt} +0 -0
|
@@ -22,12 +22,8 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
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("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}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>
|
|
25
|
+
import{$ as xn,A as pn,Aa as A,B as mn,Ba as W,C as fn,Ca as C,D as hn,Da as jn,E as gn,Ea as Ha,F as j,Fa as Nn,G as yn,Ga as Gn,H as _,Ha as $n,I as F,Ia as Zn,J as I,K as wn,Ka as Fn,L as K,La as Kn,Ma as lt,N as _n,O as ce,P as g,Q as Rn,R as bn,S as Cn,T as at,U as ee,V as Mt,W as zt,X as Sn,Y as vn,Z as Dt,_ as Ht,a as Vr,aa as P,b as se,ba as In,c as Yr,ca as An,d as D,da as Un,e as Xr,ea as kn,f as Da,fa as Bt,g as Qr,ga as Pn,h as en,ha as Lt,i as tn,ia as jt,j as w,ja as st,k as rn,ka as ct,l as nn,la as Tn,m as H,ma as On,n as on,na as dt,o as an,oa as En,p as rt,pa as Nt,q as sn,qa as qn,r as qt,ra as Te,s as nt,sa as ut,t as ot,ta as Mn,u as Pe,ua as zn,v as cn,va as Dn,w as dn,wa as Hn,x as un,xa as Bn,y as it,ya as Ln,z as ln,za as R}from"../chunk-FYGTTP3G.js";import{B as Nr,J as Gr,L as u,M as $r,N as Et,O as Z,Q as Zr,S as f,T as Q,U as tt,_ as Fr,a as Qe,ca as Kr,da as Wr,ea as d,fa as z,j as ae,k as Br,m as Lr,ma as Jr,q as jr,s as et}from"../chunk-2GVPMQ7M.js";import"../chunk-JRXZBVXH.js";import{a as x}from"../chunk-4SACVMDH.js";import{$ as E,a as n,aa as y,ba as k,ca as Hr,da as Xe}from"../chunk-ZIKV2LUM.js";z();function Ba(e){let t=ot.safeParse(e);return t.success?t.data.id:void 0}n(Ba,"parseJsonRpcRequestId");function Wn(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Ba(t)}catch{return}}n(Wn,"readJsonRpcRequestIdFromBody");function pt(e){return cn.parse({jsonrpc:nt,...e.id===void 0?{}:{id:e.id},error:{code:e.error.code,message:e.error.message,...e.error.data===void 0?{}:{data:e.error.data}}})}n(pt,"jsonRpcErrorResponse");function Jn(e){return new un([dn.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Jn,"urlElicitationRequiredError");var mt=d.array(d.string()),La=d.object({tools:mt.optional(),prompts:mt.optional(),resources:mt.optional(),resourceTemplates:mt.optional()}).strict(),$t=[{option:"tools",listMethod:"tools/list",resultProperty:"tools",itemProperty:"name",directMethods:[{method:"tools/call",paramProperty:"name"}]},{option:"prompts",listMethod:"prompts/list",resultProperty:"prompts",itemProperty:"name",directMethods:[{method:"prompts/get",paramProperty:"name"}]},{option:"resources",listMethod:"resources/list",resultProperty:"resources",itemProperty:"uri",directMethods:[{method:"resources/read",paramProperty:"uri"}]},{option:"resourceTemplates",listMethod:"resources/templates/list",resultProperty:"resourceTemplates",itemProperty:"uriTemplate",directMethods:[]}];function ja(e,t){return Xr(La,e,`MCP capability filter policy "${t}"`)}n(ja,"parseMcpCapabilityFilterOptions");function B(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(B,"isRecord");function Na(e,t){if(!B(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(Na,"readParamString");function Zt(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(Zt,"readRequestId");function Xn(e){return e===void 0?void 0:JSON.stringify(e)}n(Xn,"requestIdKey");function Ga(e){let t={};for(let r of $t){let o=e[r.option];o!==void 0&&(t[r.option]=new Set(o))}return t}n(Ga,"buildAllowSets");function Ft(e){return $t.find(t=>t.listMethod===e)}n(Ft,"findListRule");function $a(e){return e.requests.some(t=>{if(!B(t))return!1;let r=Ft(t.method);return r!==void 0&&e.allowSets[r.option]!==void 0})}n($a,"shouldFilterListResponses");function Za(e){for(let t of $t){let r=e.allowSets[t.option];if(r!==void 0)for(let o of t.directMethods){if(e.request.method!==o.method)continue;let i=Na(e.request.params,o.paramProperty);if(i!==void 0&&!r.has(i))return{id:Zt(e.request)}}}}n(Za,"findDisallowedDirectAccess");function Fa(e){return Response.json(pt({id:e,error:{code:Pe.MethodNotFound,message:"Method not found"}}))}n(Fa,"methodNotFoundResponse");function Vn(e,t,r){if(!B(e))return e;let o=e.result;if(!B(o))return e;let i=o[t.resultProperty];return!Array.isArray(i)||!i.every(a=>B(a)&&typeof a[t.itemProperty]=="string")?e:{...e,result:{...o,[t.resultProperty]:i.filter(a=>{if(!B(a))return!1;let s=a[t.itemProperty];return typeof s=="string"&&r.has(s)})}}}n(Vn,"filterItems");function Ka(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!B(r))continue;let o=Ft(r.method),i=Zt(r),a=Xn(i);o!==void 0&&a!==void 0&&t.set(a,o)}return t}n(Ka,"buildListRulesByResponseId");function Wa(e){if(Array.isArray(e.responseBody)){let o=Ka(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(i=>{if(!B(i)||"error"in i)return i;let a=Xn(Zt(i)),s=a===void 0?void 0:o.get(a),c=s===void 0?void 0:e.allowSets[s.option];return s===void 0||c===void 0?i:Vn(i,s,c)})}if(!B(e.requestBody)||!B(e.responseBody)||"error"in e.responseBody)return e.responseBody;let t=Ft(e.requestBody.method),r=t===void 0?void 0:e.allowSets[t.option];return t===void 0||r===void 0?e.responseBody:Vn(e.responseBody,t,r)}n(Wa,"filterJsonRpcResponse");async function Yn(e){return e.clone().json()}n(Yn,"readJson");function Ja(e){return e.headers.get("content-type")?.includes("json")??!1}n(Ja,"isJsonResponse");var Gt=class extends et{static{n(this,"McpCapabilityFilterInboundPolicy")}#e;constructor(t,r){let o=ja(t,r);super(o,r),this.#e=Ga(o)}async handler(t,r){Qe("policy.inbound.mcp-capability-filter");let o;try{o=await Yn(t)}catch{return t}let i=Array.isArray(o)?o:[o];for(let a of i){if(!B(a))continue;let s=Za({request:a,allowSets:this.#e});if(s!==void 0)return Fa(s.id)}return $a({requests:i,allowSets:this.#e})&&r.addResponseSendingHook(async a=>{if(!Ja(a))return a;let s;try{s=await Yn(a)}catch{return a}let c=Wa({requestBody:o,responseBody:s,allowSets:this.#e});if(c===s)return a;let l=new Headers(a.headers);return l.delete("content-length"),new Response(JSON.stringify(c),{status:a.status,statusText:a.statusText,headers:l})}),t}};function te(e){let t=j().connectionsById.get(e);if(!t)throw new k(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,...t.description===void 0?{}:{description:t.description},...t.serverInfo===void 0?{}:{serverInfo:t.serverInfo},transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}n(te,"getUpstreamServerConfig");function Va(e){let t=j().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new k(`Unknown auth profile "${String(e.authProfileId)}" for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares a matching auth mode for that upstream connection.`);return t.authProfileId}n(Va,"resolveUpstreamAuthProfileId");function Kt(e){Va(e);let t=j().connectionsById.get(e.upstreamServerId);if(!t)throw new k(`Auth profile could not be resolved for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares the upstream connection before this handler runs.`);return t.authConfig}n(Kt,"getUpstreamAuthConfig");function de(e,t){let r=Kt({upstreamServerId:e,authProfileId:t});if(!pn(r))throw new k(`Upstream server "${e}" does not use upstream OAuth. Select an auth mode that supports the requested upstream connect flow or remove the upstream OAuth route for this server.`);return r.oauth}n(de,"requireUpstreamOAuthConfig");var Ya={"shared-oauth":{authMode:"shared-oauth",ownerMode:"shared",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"},"user-oauth":{authMode:"user-oauth",ownerMode:"user",connectSupport:"oauth_authorization",connectUnsupportedDetail:void 0,callbackSupport:"authorization_code",credentialAcquisition:"oauth_connection"}};function N(e){return Ya[e]}n(N,"describeUpstreamAuthMode");function ft(e){return N(e).ownerMode}n(ft,"resolveOwnerModeForUpstreamAuthMode");var Wt;Wt=globalThis.crypto;async function Xa(e){return(await Wt).getRandomValues(new Uint8Array(e))}n(Xa,"getRandomValues");async function Qa(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await Xa(e-o.length);for(let a of i)a<r&&(o+=t[a%t.length])}return o}n(Qa,"random");async function es(e){return await Qa(e)}n(es,"generateVerifier");async function ts(e){let t=await(await Wt).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(ts,"generateChallenge");async function Jt(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await es(e),r=await ts(t);return{code_verifier:t,code_challenge:r}}n(Jt,"pkceChallenge");z();var U=$r().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Kr.custom,message:"URL must be parseable",fatal:!0}),Gr}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),ht=tt({resource:u().url(),authorization_servers:f(U).optional(),jwks_uri:u().url().optional(),scopes_supported:f(u()).optional(),bearer_methods_supported:f(u()).optional(),resource_signing_alg_values_supported:f(u()).optional(),resource_name:u().optional(),resource_documentation:u().optional(),resource_policy_uri:u().url().optional(),resource_tos_uri:u().url().optional(),tls_client_certificate_bound_access_tokens:Z().optional(),authorization_details_types_supported:f(u()).optional(),dpop_signing_alg_values_supported:f(u()).optional(),dpop_bound_access_tokens_required:Z().optional()}),Oe=tt({issuer:u(),authorization_endpoint:U,token_endpoint:U,registration_endpoint:U.optional(),scopes_supported:f(u()).optional(),response_types_supported:f(u()),response_modes_supported:f(u()).optional(),grant_types_supported:f(u()).optional(),token_endpoint_auth_methods_supported:f(u()).optional(),token_endpoint_auth_signing_alg_values_supported:f(u()).optional(),service_documentation:U.optional(),revocation_endpoint:U.optional(),revocation_endpoint_auth_methods_supported:f(u()).optional(),revocation_endpoint_auth_signing_alg_values_supported:f(u()).optional(),introspection_endpoint:u().optional(),introspection_endpoint_auth_methods_supported:f(u()).optional(),introspection_endpoint_auth_signing_alg_values_supported:f(u()).optional(),code_challenge_methods_supported:f(u()).optional(),client_id_metadata_document_supported:Z().optional()}),rs=tt({issuer:u(),authorization_endpoint:U,token_endpoint:U,userinfo_endpoint:U.optional(),jwks_uri:U,registration_endpoint:U.optional(),scopes_supported:f(u()).optional(),response_types_supported:f(u()),response_modes_supported:f(u()).optional(),grant_types_supported:f(u()).optional(),acr_values_supported:f(u()).optional(),subject_types_supported:f(u()),id_token_signing_alg_values_supported:f(u()),id_token_encryption_alg_values_supported:f(u()).optional(),id_token_encryption_enc_values_supported:f(u()).optional(),userinfo_signing_alg_values_supported:f(u()).optional(),userinfo_encryption_alg_values_supported:f(u()).optional(),userinfo_encryption_enc_values_supported:f(u()).optional(),request_object_signing_alg_values_supported:f(u()).optional(),request_object_encryption_alg_values_supported:f(u()).optional(),request_object_encryption_enc_values_supported:f(u()).optional(),token_endpoint_auth_methods_supported:f(u()).optional(),token_endpoint_auth_signing_alg_values_supported:f(u()).optional(),display_values_supported:f(u()).optional(),claim_types_supported:f(u()).optional(),claims_supported:f(u()).optional(),service_documentation:u().optional(),claims_locales_supported:f(u()).optional(),ui_locales_supported:f(u()).optional(),claims_parameter_supported:Z().optional(),request_parameter_supported:Z().optional(),request_uri_parameter_supported:Z().optional(),require_request_uri_registration:Z().optional(),op_policy_uri:U.optional(),op_tos_uri:U.optional(),client_id_metadata_document_supported:Z().optional()}),gt=Q({...rs.shape,...Oe.pick({code_challenge_methods_supported:!0}).shape}),ye=Q({access_token:u(),id_token:u().optional(),token_type:u(),expires_in:Wr.number().optional(),scope:u().optional(),refresh_token:u().optional()}).strip(),eo=Q({error:u(),error_description:u().optional(),error_uri:u().optional()}),Qn=U.optional().or(Fr("").transform(()=>{})),ns=Q({redirect_uris:f(U),token_endpoint_auth_method:u().optional(),grant_types:f(u()).optional(),response_types:f(u()).optional(),client_name:u().optional(),client_uri:U.optional(),logo_uri:Qn,scope:u().optional(),contacts:f(u()).optional(),tos_uri:Qn,policy_uri:u().optional(),jwks_uri:U.optional(),jwks:Zr().optional(),software_id:u().optional(),software_version:u().optional(),software_statement:u().optional()}).strip(),Vt=Q({client_id:u(),client_secret:u().optional(),client_id_issued_at:Et().optional(),client_secret_expires_at:Et().optional()}).strip(),Ee=ns.merge(Vt),Zl=Q({error:u(),error_description:u().optional()}).strip(),Fl=Q({token:u(),token_type_hint:u().optional()}).strip();function to(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(to,"resourceUrlFromServerUrl");function ro({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",a=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return i.startsWith(a)}n(ro,"checkResourceAllowed");var S=class extends Error{static{n(this,"OAuthError")}constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},qe=class extends S{static{n(this,"InvalidRequestError")}};qe.errorCode="invalid_request";var ue=class extends S{static{n(this,"InvalidClientError")}};ue.errorCode="invalid_client";var le=class extends S{static{n(this,"InvalidGrantError")}};le.errorCode="invalid_grant";var pe=class extends S{static{n(this,"UnauthorizedClientError")}};pe.errorCode="unauthorized_client";var Me=class extends S{static{n(this,"UnsupportedGrantTypeError")}};Me.errorCode="unsupported_grant_type";var ze=class extends S{static{n(this,"InvalidScopeError")}};ze.errorCode="invalid_scope";var De=class extends S{static{n(this,"AccessDeniedError")}};De.errorCode="access_denied";var J=class extends S{static{n(this,"ServerError")}};J.errorCode="server_error";var He=class extends S{static{n(this,"TemporarilyUnavailableError")}};He.errorCode="temporarily_unavailable";var Be=class extends S{static{n(this,"UnsupportedResponseTypeError")}};Be.errorCode="unsupported_response_type";var Le=class extends S{static{n(this,"UnsupportedTokenTypeError")}};Le.errorCode="unsupported_token_type";var je=class extends S{static{n(this,"InvalidTokenError")}};je.errorCode="invalid_token";var Ne=class extends S{static{n(this,"MethodNotAllowedError")}};Ne.errorCode="method_not_allowed";var Ge=class extends S{static{n(this,"TooManyRequestsError")}};Ge.errorCode="too_many_requests";var me=class extends S{static{n(this,"InvalidClientMetadataError")}};me.errorCode="invalid_client_metadata";var $e=class extends S{static{n(this,"InsufficientScopeError")}};$e.errorCode="insufficient_scope";var Ze=class extends S{static{n(this,"InvalidTargetError")}};Ze.errorCode="invalid_target";var no={[qe.errorCode]:qe,[ue.errorCode]:ue,[le.errorCode]:le,[pe.errorCode]:pe,[Me.errorCode]:Me,[ze.errorCode]:ze,[De.errorCode]:De,[J.errorCode]:J,[He.errorCode]:He,[Be.errorCode]:Be,[Le.errorCode]:Le,[je.errorCode]:je,[Ne.errorCode]:Ne,[Ge.errorCode]:Ge,[me.errorCode]:me,[$e.errorCode]:$e,[Ze.errorCode]:Ze};function os(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(os,"isClientAuthMethod");var Yt="code",Xt="S256";function is(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&os(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}n(is,"selectClientAuthMethod");function as(e,t,r,o){let{client_id:i,client_secret:a}=t;switch(e){case"client_secret_basic":ss(i,a,r);return;case"client_secret_post":cs(i,a,o);return;case"none":ds(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(as,"applyClientAuthentication");function ss(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}n(ss,"applyBasicAuth");function cs(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(cs,"applyPostAuth");function ds(e,t){t.set("client_id",e)}n(ds,"applyPublicAuth");async function io(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=eo.parse(JSON.parse(r)),{error:i,error_description:a,error_uri:s}=o,c=no[i]||J;return new c(a||"",s)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new J(i)}}n(io,"parseErrorResponse");async function er(e,t){try{return await Qt(e,t)}catch(r){if(r instanceof ue||r instanceof pe)return await e.invalidateCredentials?.("all"),await Qt(e,t);if(r instanceof le)return await e.invalidateCredentials?.("tokens"),await Qt(e,t);throw r}}n(er,"auth");async function Qt(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:i,fetchFn:a}){let s=await e.discoveryState?.(),c,l,h,m=i;if(!m&&s?.resourceMetadataUrl&&(m=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(l=s.authorizationServerUrl,c=s.resourceMetadata,h=s.authorizationServerMetadata??await so(l,{fetchFn:a}),!c)try{c=await ao(t,{resourceMetadataUrl:m},a)}catch{}(h!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:m?.toString(),resourceMetadata:c,authorizationServerMetadata:h})}else{let O=await hs(t,{resourceMetadataUrl:m,fetchFn:a});l=O.authorizationServerUrl,h=O.authorizationServerMetadata,c=O.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(l),resourceMetadataUrl:m?.toString(),resourceMetadata:c,authorizationServerMetadata:h})}let v=await us(t,e,c),L=o||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,X=await Promise.resolve(e.clientInformation());if(!X){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let O=h?.client_id_metadata_document_supported===!0,ke=e.clientMetadataUrl;if(ke&&!tr(ke))throw new me(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ke}`);if(O&&ke)X={client_id:ke},await e.saveClientInformation?.(X);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Dr=await Rs(l,{metadata:h,clientMetadata:e.clientMetadata,scope:L,fetchFn:a});await e.saveClientInformation(Dr),X=Dr}}let Ye=!e.redirectUrl;if(r!==void 0||Ye){let O=await _s(e,l,{metadata:h,resource:v,authorizationCode:r,fetchFn:a});return await e.saveTokens(O),"AUTHORIZED"}let zr=await e.tokens();if(zr?.refresh_token)try{let O=await ws(l,{metadata:h,clientInformation:X,refreshToken:zr.refresh_token,resource:v,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(O),"AUTHORIZED"}catch(O){if(!(!(O instanceof S)||O instanceof J))throw O}let qa=e.state?await e.state():void 0,{authorizationUrl:Ma,codeVerifier:za}=await gs(l,{metadata:h,clientInformation:X,state:qa,redirectUrl:e.redirectUrl,scope:L,resource:v});return await e.saveCodeVerifier(za),await e.redirectToAuthorization(Ma),"REDIRECT"}n(Qt,"authInternal");function tr(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(tr,"isHttpsUrl");async function us(e,t,r){let o=to(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!ro({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}n(us,"selectResourceURL");async function ao(e,t,r=fetch){let o=await ms(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.body?.cancel(),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return ht.parse(await o.json())}n(ao,"discoverOAuthProtectedResourceMetadata");async function rr(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?rr(e,void 0,r):void 0;throw o}}n(rr,"fetchWithCorsRetry");function ls(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(ls,"buildWellKnownPath");async function oo(e,t,r=fetch){return await rr(e,{"MCP-Protocol-Version":t},r)}n(oo,"tryMetadataDiscovery");function ps(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(ps,"shouldAttemptFallback");async function ms(e,t,r,o){let i=new URL(e),a=o?.protocolVersion??qt,s;if(o?.metadataUrl)s=new URL(o.metadataUrl);else{let l=ls(t,i.pathname);s=new URL(l,o?.metadataServerUrl??i),s.search=i.search}let c=await oo(s,a,r);if(!o?.metadataUrl&&ps(c,i.pathname)){let l=new URL(`/.well-known/${t}`,i);c=await oo(l,a,r)}return c}n(ms,"discoverMetadataWithFallback");function fs(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let i=t.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:"oidc"}),o.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(fs,"buildDiscoveryUrls");async function so(e,{fetchFn:t=fetch,protocolVersion:r=qt}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=fs(e);for(let{url:a,type:s}of i){let c=await rr(a,o,t);if(c){if(!c.ok){if(await c.body?.cancel(),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${a}`)}return s==="oauth"?Oe.parse(await c.json()):gt.parse(await c.json())}}}n(so,"discoverAuthorizationServerMetadata");async function hs(e,t){let r,o;try{r=await ao(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch{}o||(o=String(new URL("/",e)));let i=await so(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(hs,"discoverOAuthServerInfo");async function gs(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:i,state:a,resource:s}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Yt))throw new Error(`Incompatible auth server: does not support response type ${Yt}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Xt))throw new Error(`Incompatible auth server: does not support code challenge method ${Xt}`)}else c=new URL("/authorize",e);let l=await Jt(),h=l.code_verifier,m=l.code_challenge;return c.searchParams.set("response_type",Yt),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",m),c.searchParams.set("code_challenge_method",Xt),c.searchParams.set("redirect_uri",String(o)),a&&c.searchParams.set("state",a),i&&c.searchParams.set("scope",i),i?.includes("offline_access")&&c.searchParams.append("prompt","consent"),s&&c.searchParams.set("resource",s.href),{authorizationUrl:c,codeVerifier:h}}n(gs,"startAuthorization");function ys(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(ys,"prepareAuthorizationCodeRequest");async function co(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:i,resource:a,fetchFn:s}){let c=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),l=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(a&&r.set("resource",a.href),i)await i(l,r,c,t);else if(o){let m=t?.token_endpoint_auth_methods_supported??[],v=is(o,m);as(v,o,l,r)}let h=await(s??fetch)(c,{method:"POST",headers:l,body:r});if(!h.ok)throw await io(h);return ye.parse(await h.json())}n(co,"executeTokenRequest");async function ws(e,{metadata:t,clientInformation:r,refreshToken:o,resource:i,addClientAuthentication:a,fetchFn:s}){let c=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),l=await co(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:a,resource:i,fetchFn:s});return{refresh_token:o,...l}}n(ws,"refreshAuthorization");async function _s(e,t,{metadata:r,resource:o,authorizationCode:i,fetchFn:a}={}){let s=e.clientMetadata.scope,c;if(e.prepareTokenRequest&&(c=await e.prepareTokenRequest(s)),!c){if(!i)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let h=await e.codeVerifier();c=ys(i,h,e.redirectUrl)}let l=await e.clientInformation();return co(t,{metadata:r,tokenRequestParams:c,clientInformation:l??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(_s,"fetchToken");async function Rs(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");a=new URL(t.registration_endpoint)}else a=new URL("/register",e);let s=await(i??fetch)(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!s.ok)throw await io(s);return Ee.parse(await s.json())}n(Rs,"registerClient");z();import{errors as yo,jwtVerify as wo,SignJWT as _o}from"jose";var T="zuplo-mcp-gateway",q=T,M="HS256";import{base64url as bs}from"jose";var Cs=new TextEncoder,Ss="MCP gateway could not initialize secure key material.",vs=32,uo=new Map,lo=new Map,xs;function Is(){return xs??Hr.instance.authPrivateKey}n(Is,"readAuthPrivateKey");function po(e){return new E(Ss,e===void 0?void 0:{cause:e})}n(po,"createGeneratedKeyMaterialError");function mo(e,t){let r=bs.decode(t);if(r.byteLength!==vs)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(mo,"decodeJwkKeyField");function As(e){let t=Is();if(!t)throw po();try{let r=JSON.parse(t);if(r.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.d!="string"||typeof r.x!="string")throw new Error("Generated deployment auth key is not an Ed25519 JWK.");let o=mo("d",r.d);mo("x",r.x);let i=Cs.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),a=new Uint8Array(i.byteLength+o.byteLength);return a.set(i),a.set(o,i.byteLength),a}catch(r){throw po(r)}}n(As,"decodeGeneratedKeyMaterial");function Us(e){let t=uo.get(e);return t||(t=As(e),uo.set(e,t)),t}n(Us,"getMasterKeyMaterial");async function G(e){let t=lo.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Us(e.keyMaterialPurpose));return lo.set(e.purpose,r),r}n(G,"readCachedDerivedKey");var ks="SHA-256";var Ps="zuplo-mcp-gateway:",Ts=new TextEncoder,fo=new WeakMap;async function re(e,t){let r=fo.get(e);r||(r=new Map,fo.set(e,r));let o=r.get(t);if(o)return o;let i=await Os(e,t);return r.set(t,i),i}n(re,"deriveGatewaySigningKey");async function Os(e,t){let r=ho(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=Ts.encode(`${Ps}${t}`),a=await crypto.subtle.deriveBits({name:"HKDF",hash:ks,salt:new Uint8Array,info:ho(i)},o,32*8);return new Uint8Array(a)}n(Os,"hkdfExpand");function ho(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(ho,"copyToArrayBuffer");var Ro=15*60,Es=15*60,qs=qn.extend({id:Mn}),Ms=qs.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),bo=Nt.extend({id:zn,purpose:d.literal("browser_connect")}),zs=Nt.extend({purpose:d.literal("browser_connect")}),Ds=bo.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),Co=Ro*1e3;async function So(){return G({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>re(e,"oauth-state"),"derive")})}n(So,"getOAuthStateKey");async function vo(){return G({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>re(e,"browser-connect"),"derive")})}n(vo,"getBrowserConnectKey");async function xo(e){let t=Math.floor(Date.now()/1e3)+Ro;return new _o(e).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(t).sign(await So())}n(xo,"signOAuthState");async function yt(e){try{let{payload:t}=await wo(e,await So(),{algorithms:[M],issuer:T,audience:q});return Ms.parse(t)}catch(t){throw t instanceof yo.JWTExpired?new y({message:"OAuth state has expired",extensionMembers:{[w]:"oauth_state_expired"}},{cause:t}):new y({message:"OAuth state could not be verified",extensionMembers:{[w]:"oauth_state_invalid"}},{cause:t})}}n(yt,"verifyOAuthState");async function Io(e){let t=Math.floor(Date.now()/1e3)+Es,r=zs.parse(e),o=bo.parse({...r,id:Ln()});return new _o(o).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(t).sign(await vo())}n(Io,"signBrowserConnectTicket");async function Ao(e){try{let{payload:t}=await wo(e,await vo(),{algorithms:[M],issuer:T,audience:q});return Ds.parse(t)}catch(t){throw t instanceof yo.JWTExpired?new y({message:"Browser connect ticket has expired",extensionMembers:{[w]:"oauth_state_expired"}},{cause:t}):new y({message:"Browser connect ticket could not be verified",extensionMembers:{[w]:"oauth_state_invalid"}},{cause:t})}}n(Ao,"verifyBrowserConnectTicket");async function Uo(e){if((await R().consumeBrowserConnectTicket({id:e.id,expiresAt:_(new Date(e.exp*1e3)),now:_(new Date)})).kind==="consumed")throw new y({message:"Browser connect ticket has already been used",extensionMembers:{[w]:"oauth_state_reused"}})}n(Uo,"consumeBrowserConnectTicket");function Hs(e,t,r=!1){return r?`${e} authorization must be renewed before this ${t} can be used.`:`${e} authorization is required before this ${t} can be used.`}n(Hs,"buildConnectRequiredMessage");async function Bs(e){let t=I(e.requestUrl),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("operationId",e.operationId),r.searchParams.set("browserTicket",await Io({...Te(e),purpose:"browser_connect"})),r.toString()}n(Bs,"buildGatewayBrowserTicketUrl");function Ls(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}n(Ls,"buildGatewayConnectPath");async function nr(e){return Bs({...e,path:Ls(e.upstreamServerId),redirect:!0})}n(nr,"buildGatewayConnectUrl");async function wt(e){let t={requestUrl:e.requestUrl,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await nr(t),message:Hs(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(wt,"buildRedirectConnectRequiredResponse");function ko(e){return js({...e,message:e.requiresReconsent?`An administrator must reconnect ${e.upstreamDisplayName} before this tool can be used.`:`An administrator must connect ${e.upstreamDisplayName} before this tool can be used.`})}n(ko,"buildAdminConnectRequiredResponse");function js(e){return{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},message:e.message,nextAction:"admin_setup_required"}}n(js,"buildAdminSetupRequiredResponse");z();function or(e){return`Zuplo MCP Gateway - ${e}`}n(or,"buildGatewayOAuthClientName");function Po(e,t){let r=new URL(e,I(t));return se(r)&&Vr(r.hostname)!=="localhost"&&(r.hostname="localhost"),r.toString()}n(Po,"buildGatewayOAuthRedirectUri");function ir(e){let t=new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin);return t.searchParams.set("authProfileId",e.authProfileId),t.toString()}n(ir,"buildOAuthClientMetadataDocumentUrl");function To(e){return I(e)}n(To,"requireOAuthClientMetadataOrigin");function Oo(e,t,r){let o=te(t),i=de(t,r);return{client_id:ir({origin:e,upstreamServerId:t,authProfileId:r}),client_name:or(o.displayName),client_uri:new URL("/",e).toString(),redirect_uris:[new URL(i.redirectPath,e).toString()],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",token_endpoint_auth_method:"none"}}n(Oo,"buildOAuthClientMetadataDocument");z();import{base64url as ne}from"jose";var Ns="SHA-256",_e="AES-GCM",Gs=12,sr="zuplo-secret",cr=1,Eo="generated:auth_private_key:token-encryption",$s=d.object({version:d.literal(cr),keyId:d.literal(Eo),algorithm:d.literal(_e),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();function we(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(we,"copyToArrayBuffer");async function ar(){return G({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(Ns,we(e));return crypto.subtle.importKey("raw",t,{name:_e},!1,["encrypt","decrypt"])},"derive")})}n(ar,"getEncryptionKey");function qo(e){return we(new TextEncoder().encode(`${sr}:v${e.version}:${e.keyId}`))}n(qo,"getAssociatedData");function Zs(e){return`${sr}:v${e.version}:${ne.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(Zs,"encodeEnvelope");function Fs(e){let t=`${sr}:v${cr}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(ne.decode(r));return $s.parse(JSON.parse(o))}n(Fs,"decodeEnvelope");async function _t(e){let t=await ar(),r=crypto.getRandomValues(new Uint8Array(Gs)),o={version:cr,keyId:Eo},i=await crypto.subtle.encrypt({name:_e,iv:r,additionalData:qo(o)},t,new TextEncoder().encode(e));return Zs({...o,algorithm:_e,iv:ne.encode(r),ciphertext:ne.encode(new Uint8Array(i))})}n(_t,"encryptSecret");async function Fe(e){let t=Fs(e);if(t){let s=await ar(),c=await crypto.subtle.decrypt({name:_e,iv:we(ne.decode(t.iv)),additionalData:qo(t)},s,we(ne.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,o]=e.split(".");if(!r||!o)throw new E("Encrypted payload is malformed");let i=await ar(),a=await crypto.subtle.decrypt({name:_e,iv:we(ne.decode(r))},i,we(ne.decode(o)));return new TextDecoder().decode(a)}n(Fe,"decryptSecret");var Ks=d.union([Ee,Vt]),Ws=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:ht.optional(),authorizationServerMetadata:d.union([Oe,gt]).optional()}).passthrough(),Js="Bearer",Vs="__zuplo_refresh_only_upstream_access_token__";function Ys(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Ys,"splitScopes");function Xs(e){return at.parse(e)}n(Xs,"parsePkceCodeVerifier");function Qs(e){if(typeof e.expires_in=="number")return _(new Date(Date.now()+e.expires_in*1e3))}n(Qs,"readTokenExpiry");async function Mo(e){if(e!==void 0)return _t(JSON.stringify(e))}n(Mo,"encryptJson");async function zo(e,t){if(!e)return;let r=await Fe(e);try{return t.parse(JSON.parse(r))}catch(o){throw new y({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[w]:"oauth_state_invalid"}},{cause:o})}}n(zo,"decryptJson");function ec(e){if(e===void 0)return;let t={authorizationServerUrl:e.authorizationServerUrl};return e.resourceMetadataUrl!==void 0&&(t.resourceMetadataUrl=e.resourceMetadataUrl),e.resourceMetadata!==void 0&&(t.resourceMetadata=e.resourceMetadata),e.authorizationServerMetadata!==void 0&&(t.authorizationServerMetadata=e.authorizationServerMetadata),t}n(ec,"toOAuthDiscoveryState");function tc(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(tc,"clientInformationAllowsRedirectUri");function rc(e,t,r){let o=te(e),i=de(e,t),a;return i.scopes.length>0&&(a=i.scopes.join(i.scopeDelimiter)),{client_name:or(o.displayName),client_uri:new URL("/",new URL(r).origin).toString(),redirect_uris:[r],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",scope:a,token_endpoint_auth_method:"none"}}n(rc,"buildOAuthClientMetadata");function nc(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new k(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return Ee.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(nc,"buildManualOAuthClientInformation");function oc(e,t,r){let o=ir({origin:new URL(r).origin,upstreamServerId:e,authProfileId:t});return tr(o)?o:void 0}n(oc,"buildClientMetadataUrl");function Do(e){for(let t of e)if(t!==void 0)return t}n(Do,"firstDefined");function ic(e){let t=de(e.target.upstreamServerId,e.target.authProfileId),r=rc(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);if(t.clientRegistration.mode==="manual")return{clientMetadata:r,configuredClientInformation:nc({clientMetadata:r,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let o=oc(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);return o===void 0?{clientMetadata:r}:{clientMetadata:r,clientMetadataUrl:o}}n(ic,"buildInitialOAuthClientSetup");function ac(e,t){if(t===void 0)return Do([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(ac,"readEncryptedClientInformation");function sc(e){return Do([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}n(sc,"readEncryptedDiscoveryState");var fe=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredClientInformation;authorizationUrlValue;connection;pendingState;encryptedClientInformation;encryptedDiscoveryState;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;constructor(t){let r=ic({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.clientMetadataValue=r.clientMetadata,this.configuredClientInformation=r.configuredClientInformation,r.clientMetadataUrl!==void 0&&(this.clientMetadataUrl=r.clientMetadataUrl),this.connection=t.connection,this.pendingState=t.pendingState?{...t.pendingState}:void 0,this.encryptedClientInformation=ac(t,this.configuredClientInformation),this.encryptedDiscoveryState=sc(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return this.clientMetadataValue}async state(){let t=await this.createPendingState();return xo({id:t.id,...Te({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId})})}async clientInformation(){return this.configuredClientInformation?this.configuredClientInformation:this.loadPersistedClientInformation()}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.encryptedClientInformation=await Mo(t),await this.syncPendingState(!1))}async discoveryState(){return this.loadPersistedDiscoveryState()}async saveDiscoveryState(t){this.cachedDiscoveryState=t,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await Mo(t),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=ye.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=r.refresh_token?await _t(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:ye.parse({...r,refresh_token:await Fe(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let a={id:this.connection?.id??Hn(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await _t(r.access_token),encryptedRefreshToken:i,scopes:Ys(r.scope??this.clientMetadataValue.scope),expiresAt:Qs(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await R().upsertUpstreamConnection(a)}async redirectToAuthorization(t){this.authorizationUrlValue=t.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:Xs(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new y({message:"OAuth code verifier is missing",extensionMembers:{[w]:"oauth_state_invalid"}});return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",o=t==="all"||t==="client",i=t==="all"||t==="discovery",a=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),i&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(a),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:Bn(),...Te({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,operationId:this.target.operationId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:_(new Date(Date.now()+Co)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await R().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await zo(this.encryptedClientInformation,Ks)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&!tc(t,this.redirectUriValue)){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1);return}return this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async loadPersistedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;try{this.cachedDiscoveryState=ec(await zo(this.encryptedDiscoveryState,Ws))}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1)}return this.discoveryStateLoaded=!0,this.cachedDiscoveryState}async loadStoredTokens(){if(this.tokensLoaded)return this.cachedTokens;if(this.tokensLoaded=!0,!this.connection||this.connection.status!=="active")return;let t=this.connection.encryptedAccessToken?await Fe(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await Fe(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=ye.parse({access_token:t??Vs,token_type:Js,refresh_token:r,scope:this.connection.scopes.length>0?this.connection.scopes.join(" "):void 0});return this.cachedTokens=o,o}async persistCredentialInvalidation(t){if(!this.connection)return;let r={id:this.connection.id,ownerMode:this.connection.ownerMode,subjectId:this.connection.subjectId,upstreamServerId:this.connection.upstreamServerId,authProfileId:this.connection.authProfileId,status:this.connection.status,encryptedAccessToken:this.connection.encryptedAccessToken,encryptedRefreshToken:this.connection.encryptedRefreshToken,scopes:[...this.connection.scopes],expiresAt:this.connection.expiresAt,metadata:this.connection.metadata?{...this.connection.metadata}:void 0};t&&(r.status="reconsent_required",r.encryptedAccessToken=void 0,r.encryptedRefreshToken=void 0,r.scopes=[],r.expiresAt=void 0),r.metadata=this.readStoredOAuthPersistence(this.connection.metadata?.connectedBySubjectId),this.connection=await R().upsertUpstreamConnection(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var cc=3e4,dc=256*1024,uc=2;function lc(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(lc,"hasUsableAccessToken");var pc="does not support dynamic client registration";function mc(e){return e instanceof Error&&e.message.includes(pc)}n(mc,"isDynamicClientRegistrationUnsupported");function fc(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(fc,"readOAuthFetchRequest");function hc(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(hc,"responseLooksJson");function Ho(e){return async(t,r)=>{let o=fc(t),i=await Zn(t,r,{maxRedirects:uc,maxResponseBytes:dc,problemCode:"upstream_token_exchange_failed",timeoutMs:cc}),a=await i.clone().text();if(!hc(i,a))return i;try{JSON.parse(a)}catch(s){throw new y({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[w]:"upstream_token_exchange_failed"}},{cause:s})}return i}}n(Ho,"createUpstreamOAuthFetch");async function Bo(e,t){try{return await er(e,{serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Ho(t.upstreamServerId)})}catch(r){throw mc(r)?new y({message:`The authorization server for ${t.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register a client for the gateway manually before retrying.`,extensionMembers:{[w]:"upstream_client_registration_required"}},{cause:r}):r}}n(Bo,"runUpstreamOAuth");async function gc(e,t){return er(e,{serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Ho(t.upstreamServerId)})}n(gc,"exchangeUpstreamAuthorizationCode");async function Lo(e,t){let r=await Bo(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new y({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}}):new y({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}})}n(Lo,"requireUpstreamAuthorizationRedirect");async function jo(e){if(!e.forceRefresh&&lc(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await Bo(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl});if(t==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(t!=="REDIRECT")throw new y({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new y({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}});return{kind:"connect_required",payload:await bc({requestUrl:e.target.request.url,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}n(jo,"authorizeUpstreamOAuthSession");async function yc(e){let t=await yt(e.stateToken),r=await R().consumeUpstreamOAuthState({id:t.id,now:_(new Date)}),o=wc(r);return _c({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),Rc(o),o}n(yc,"consumeStoredCallbackState");function wc(e){switch(e.kind){case"consumed":throw new y({message:"OAuth state has already been used",extensionMembers:{[w]:"oauth_state_reused"}});case"missing":throw new y({message:"OAuth state is missing or expired",extensionMembers:{[w]:"oauth_state_expired"}});case"available":return e.record}}n(wc,"readConsumedCallbackState");function _c(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.operationId===e.signedState.operationId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw new y({message:"OAuth callback did not match the initiating request",extensionMembers:{[w]:"oauth_callback_mismatch"}})}n(_c,"assertStoredCallbackStateMatches");function Rc(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new y({message:"OAuth state has expired",extensionMembers:{[w]:"oauth_state_expired"}})}n(Rc,"assertStoredCallbackStateFresh");async function bc(e){if(e.owner.mode==="shared"){let r={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,requiresReconsent:!!e.connection};return e.connection!==void 0&&(r.connectionId=e.connection.id),ko(r)}let t={requestUrl:e.requestUrl,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,subject:"tool",requiresReconsent:!!e.connection,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return e.connection!==void 0&&(t.connectionId=e.connection.id),wt(t)}n(bc,"buildOAuthConnectRequiredResponse");async function No(e){let t=await yc({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=ut(t),[o]=await R().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),i={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};o!==void 0&&(i.connection=o);let a=new fe(i),s=await gc(a,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(s==="AUTHORIZED")return t;throw s!=="REDIRECT"?new y({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${s}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}}):new y({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[w]:"upstream_token_exchange_failed"}})}n(No,"finishUpstreamOAuthCallback");async function Go(e){let t=te(e.upstreamServerId),r=de(e.upstreamServerId,e.authProfileId),o=Po(r.redirectPath,e.request.url),i="preloadedConnection"in e?e.preloadedConnection:(await R().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:i,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}},redirectUri:o,returnOrigin:I(e.request.url)}}}n(Go,"prepareUpstreamOAuthRequest");async function $o(e){let t=await Go(e),r=new fe({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Lo(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n($o,"startUpstreamConnect");async function Zo(e){let t=await Go(e),r=new fe({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return jo({target:e,provider:r,connection:t.connection,forceRefresh:e.forceRefresh,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Zo,"authorizeUpstreamRequest");async function Re(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return Zo({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,forceRefresh:e.forceRefresh,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},...t.returnTo===void 0?{}:{returnTo:t.returnTo}})}let r=t;throw new E(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(Re,"resolveUpstreamCredentialForRoute");async function Fo(e){let t,r={request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,operationId:e.connectRequest.operationId,...e.connectRequest.returnTo===void 0?{}:{returnTo:e.connectRequest.returnTo}},o=N(e.connectRequest.authMode);switch(o.connectSupport){case"oauth_authorization":t=await $o(r);break;case"none":throw new E(o.connectUnsupportedDetail??`Upstream server ${e.connectRequest.upstreamServerId} does not support browser connection flows.`)}return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}n(Fo,"startUpstreamConnectForRequest");async function Ko(e){let r=(await yt(e.callbackRequest.state)).authProfileId,o=Kt({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r});if(N(o.mode).callbackSupport!=="authorization_code")throw new E(`Upstream server ${e.callbackRequest.upstreamServerId} does not support OAuth callbacks.`);return No({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:te(e.callbackRequest.upstreamServerId)})}n(Ko,"finishUpstreamCallbackForRequest");function Cc(e){let t=N(e.connection.authMode);return{upstreamServerId:e.connection.upstreamServerId,operationId:e.operationId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:t.ownerMode}}n(Cc,"buildRouteAuthBaseFromConnection");function Jo(e){let t=N(e.connection.authMode);return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:it(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:t.ownerMode}}n(Jo,"buildRouteAuthBaseFromPolicyOptions");function Rt(e,t){let o=j().byOperationId.get(t);if(!o)throw new k(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new k(`MCP route "${t}" does not declare an MCP token exchange policy. Add one before starting an upstream connection flow.`);if(o.connection.upstreamServerId!==e)throw new k(`MCP route "${t}" does not bind upstream "${e}". Check the route's MCP upstream policies and bind the upstream before starting an upstream connection flow.`);return Cc({connection:o.connection,operationId:t})}n(Rt,"resolveRouteAuthBase");function Wo(e,t){switch(e){case"user":return dt(t.subjectId);case"shared":return En()}}n(Wo,"buildOwnerForPrincipal");function be(e,t){switch(e.ownerMode){case"shared":return{...e,owner:Wo(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"user":return{...e,owner:Wo(e.ownerMode,t),initiatedBySubjectId:t.subjectId}}}n(be,"resolveRouteAuthForPrincipal");var Sc=Pe.InvalidRequest,vc=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function xc(e){let t=e.route.raw();return rt.parse(t?.operationId)}n(xc,"readOperationId");async function Ic(e,t,r,o){let i=await Re({request:e,routeAuth:t});if(i.kind==="connect_required")return o.log.info({event:"mcp_upstream_connect_required",upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId},"MCP upstream proxy: upstream connection required"),{kind:"connect_required",payload:i.payload};let a=i.credential;switch(a.type){case"none":return{kind:"headers",headers:[]};case"bearer_token":return{kind:"headers",headers:[["authorization",`Bearer ${a.token}`]]};case"headers":return{kind:"headers",headers:Object.entries(a.headers)};case"mcp_oauth_provider":{let s=await a.provider.tokens();return s?{kind:"headers",headers:[["authorization",`${s.token_type??"Bearer"} ${s.access_token}`]]}:(o.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:t.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),Response.json({error:"no_upstream_tokens"},{status:401}))}}}n(Ic,"buildCredentialHeaders");var Ac=new Set(["authorization","cookie","cookie2"]);function Uc(e,t){let r=new Headers(e.headers);for(let o of Ac)r.delete(o);for(let[o,i]of t)r.set(o,i);return new Lr(e,{headers:r})}n(Uc,"applyUpstreamHeaders");function kc(e){let t=new Headers(e.headers);for(let r of vc)t.delete(r);return t}n(kc,"buildProxyHeaders");async function Pc(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(Pc,"readRetryBody");function Vo(e,t){let r=t.authUrl===void 0?void 0:Jn({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(pt({id:Wn(e),error:{code:r?.code??Sc,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(Vo,"connectRequiredJsonRpcResponse");async function Tc(e){let t=await Re({request:e.request,routeAuth:e.routeAuth,forceRefresh:!0});if(t.kind==="connect_required")return{kind:"connect_required",payload:t.payload};let r=new Headers(e.headers),o=t.credential;switch(o.type){case"none":return r.delete("authorization"),{kind:"headers",headers:r};case"bearer_token":return r.set("authorization",`Bearer ${o.token}`),{kind:"headers",headers:r};case"headers":for(let[i,a]of Object.entries(o.headers))r.set(i,a);return{kind:"headers",headers:r};case"mcp_oauth_provider":{let i=await o.provider.tokens();return i?(r.set("authorization",`${i.token_type??"Bearer"} ${i.access_token}`),{kind:"headers",headers:r}):(e.context.log.warn({event:"mcp_upstream_no_tokens_after_refresh",upstreamServerId:e.routeAuth.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens after refresh"),{kind:"response",response:Response.json({error:"no_upstream_tokens"},{status:401})})}}}n(Tc,"applyRefreshedCredentialHeaders");function Oc(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await Tc({request:e.request,context:e.context,headers:kc(r),routeAuth:e.routeAuth});if(o.kind==="connect_required")return Vo(e.requestBody,o.payload);if(o.kind==="response")return o.response;let i=on({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return Xe.fetch(i.url,i.init)})}n(Oc,"installUpstreamAuthRetryHook");async function dr(e,t,r){let o=xc(t),i=await Pc(e),a=Jo({connection:r,operationId:o}),s=be(a,Tn(e,t)),c=await Ic(e,s,r,t);if(!(c instanceof Response)&&c.kind==="connect_required")return Vo(i,c.payload);if(c instanceof Response)return c;let l=Uc(e,c.headers);return Oc({request:l,context:t,requestBody:i,routeAuth:s}),l}n(dr,"mcpTokenExchangePolicy");var ur=class extends et{static{n(this,"McpTokenExchangeInboundPolicy")}constructor(t,r){let o=ln(t,r);super(o,r)}async handler(t,r){return Qe("policy.inbound.mcp-token-exchange"),dr(t,r,this.options)}};z();var Yo=Symbol("Html");function Ec(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}n(Ec,"escapeHtml");function qc(e){return e===null||typeof e!="object"?!1:e[Yo]===!0}n(qc,"isHtml");function Xo(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Xo).join(""):qc(e)?e.value:Ec(String(e))}n(Xo,"renderValue");function V(e){return{[Yo]:!0,value:e}}n(V,"trustedHtml");var he=V("");function b(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=Xo(t[o]),r+=e[o+1]??"";return V(r)}n(b,"html");function Ce(e){return e.value}n(Ce,"renderHtml");function Qo(e){return b`<p data-gateway-error-code="${e.code}">${e.detail}</p>${e.guidance} ${e.action}`}n(Qo,"renderBrowserErrorPage");var Se=V('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;justify-content:center;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;min-height:40px;padding:8px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.reconnect-action{align-items:center;margin-right:auto;display:inline-flex;position:relative}.reconnect-button{gap:7px}.tooltip{width:16px;height:16px;color:var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);cursor:help;border:1.5px solid;border-radius:50%;justify-content:center;align-items:center;font-size:10.5px;font-weight:700;line-height:1;display:inline-flex;position:relative}.tooltip:after{content:attr(aria-label);z-index:10;border-radius:var(--radius-sm);background:var(--accent);width:280px;max-width:min(280px,100vw - 48px);color:var(--accent-text);box-shadow:var(--shadow);text-align:left;white-space:normal;opacity:0;pointer-events:none;padding:12px 14px;font-size:13px;font-weight:600;line-height:1.45;transition:opacity .12s;position:absolute;bottom:calc(100% + 12px);left:50%;transform:translate(-50%)}.tooltip:before{content:"";z-index:11;border-left:7px solid #0000;border-right:7px solid #0000;border-top:8px solid var(--accent);opacity:0;pointer-events:none;transition:opacity .12s;position:absolute;bottom:calc(100% + 5px);left:50%;transform:translate(-50%)}.tooltip:hover:after,.tooltip:hover:before,.tooltip:focus-visible:after,.tooltip:focus-visible:before{opacity:1}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}.reconnect-action{justify-content:center;width:100%;margin-right:0}.reconnect-action .button{flex:1}.tooltip:after{left:auto;right:0;transform:none}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function ve(e){return b`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" href="${e.iconHref}" /><style>
|
|
30
26
|
${e.styles}
|
|
31
|
-
</style></head><body><main class="card"><header class="card__head">${e.headerIcon}<h1 class="card__title">${e.heading}</h1>${e.subhead}</header><div class="card__body">${e.body}</div>${e.footer}</main></body></html>`}n(It,"renderShell");var 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};
|
|
27
|
+
</style></head><body><main class="card"><header class="card__head">${e.headerIcon}<h1 class="card__title">${e.heading}</h1>${e.subhead}</header><div class="card__body">${e.body}</div>${e.footer}</main></body></html>`}n(ve,"renderShell");var lr="zuplo.com";function ei(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(ei,"s2FaviconHref");function Mc(e){return`https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&drop_404_icon=true&fallback_opts=TYPE,SIZE,URL&url=http://${e}&size=128`}n(Mc,"strictFaviconHref");var bt=ei(lr);function Ct(e){let t=e.toLowerCase();return t===lr||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?ei(lr):Mc(e)}n(Ct,"resolveIconHref");function St(e){return b`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}n(St,"renderShellIcon");var zc="text/html; charset=utf-8";function xe(e){try{return new URL(e).host}catch{return""}}n(xe,"safeHostFromUrl");function $(e){let t=Ct(e.host),r=Dc(e.kind??"authorization_failed");return new Response(Ce(ve({title:e.title??r.title,iconHref:t,styles:Se,headerIcon:St({iconHref:t,fallbackIconHref:bt}),heading:e.title??r.title,subhead:"",body:Qo({code:e.code??"unknown",detail:e.detail,guidance:b`<p class="card__description">${r.guidance}</p>`,action:Hc(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":zc,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n($,"browserErrorPageResponse");function Dc(e){switch(e){case"session_expired":return{title:"Authorization expired",guidance:"Return to your MCP client and reconnect. Expired authorization requests cannot be resumed."};case"access_denied":return{title:"Authorization canceled",guidance:"Return to your MCP client to retry if you want to grant access."};case"configuration_error":return{title:"Configuration needs attention",guidance:"Contact your workspace admin with this error code. The gateway or upstream configuration must be fixed before retrying."};case"connection_failed":return{title:"Connection failed",guidance:"Return to your MCP client and reconnect this upstream. If this keeps happening, contact your gateway administrator with this error code."};case"invalid_request":return{title:"Authorization request invalid",guidance:"Return to your MCP client and try connecting again. If this keeps happening, the client request may need to be fixed."};case"admin_required":return{title:"Admin setup required",guidance:"Contact your workspace admin with this error code. This connection cannot be completed until setup is finished."};case"internal_error":return{title:"Gateway error",guidance:"Try again later from your MCP client. If this keeps happening, contact your gateway administrator with this error code."};case"authorization_failed":return{title:"Authorization failed",guidance:"Return to your MCP client and start authorization again. If this keeps happening, contact your gateway administrator with this error code."}}}n(Dc,"readBrowserErrorPagePresentation");function Hc(e){return e===void 0?he:b`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(Hc,"renderAction");var ti="application/json",Bc="application/x-www-form-urlencoded";function vt(e,t){return new y({message:e,extensionMembers:{[w]:"invalid_request"}},t===void 0?void 0:{cause:t})}n(vt,"invalidRequestError");function Lc(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}n(Lc,"normalizeContentType");function jc(e,t){return e===t?!0:t===ti&&e.endsWith("+json")}n(jc,"contentTypeMatches");function Nc(e,t){if(!t||t.length===0)return;let r=Lc(e.headers.get("content-type"));if(!t.some(o=>jc(r,o)))throw vt(`Request body must be ${t.join(" or ")}.`)}n(Nc,"assertExpectedContentType");function Gc(e,t,r){let o=e.headers.get("content-length");if(!o)return;let i=Number.parseInt(o,10);if(Number.isFinite(i)&&i>t)throw vt(`${r} exceeded the maximum allowed size.`)}n(Gc,"assertContentLengthWithinLimit");async function ri(e,t){let r=t.label??"Request body";Nc(e,t.expectedContentTypes),Gc(e,t.maxBytes,r);let o=await $n(e.body,{maxBytes:t.maxBytes,createLimitError:n(()=>vt(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(o)}n(ri,"readBoundedTextBody");async function ni(e,t){let r=await ri(e,{...t,expectedContentTypes:[ti]});try{return JSON.parse(r)}catch(o){throw vt("Request body must be valid JSON.",o)}}n(ni,"readBoundedJsonBody");async function oi(e,t){let r=await ri(e,{...t,expectedContentTypes:[Bc]});return new URLSearchParams(r)}n(oi,"readBoundedFormUrlEncodedBody");z();z();import{errors as ui,jwtVerify as li,SignJWT as pi}from"jose";z();import{errors as $c,jwtVerify as Zc,SignJWT as Fc}from"jose";var mr="zuplo_mcp_session",Kc=d.object({purpose:d.literal("gateway_browser_session"),sub:st,browserLoginOrigin:d.string().min(1),roles:d.array(d.string().min(1)).optional(),exp:d.number().int().positive(),iat:d.number().int().positive().optional()});function Wc(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let o=r.indexOf("=");if(o<0)continue;let i=r.slice(0,o).trim(),a=r.slice(o+1).trim();if(i)try{t.set(i,decodeURIComponent(a))}catch{t.set(i,a)}}return t}n(Wc,"parseCookieHeader");async function ii(){return G({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>re(e,"browser-session"),"derive")})}n(ii,"getBrowserSessionKey");function pr(e){let t=new URL(I(e)),r=[`${mr}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(pr,"buildBrowserSessionEvictionCookie");function Jc(e){let t=new URL(I(e.requestUrl)),r=[`${mr}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(Jc,"serializeSessionCookie");function ai(){return new URL(lt("url")).origin}n(ai,"readBrowserLoginOrigin");function fr(){return D().browserLogin.stateTtlSeconds}n(fr,"readBrowserLoginStateTtlSeconds");function si(e){if(!e.user)throw g("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return ct(e.user,e.url)}n(si,"resolveCurrentRequestPrincipal");async function xt(e,t={}){let r=Wc(e.headers.get("cookie")).get(mr);if(!r)return{};try{let{payload:o}=await Zc(r,await ii(),{algorithms:[M],issuer:T,audience:q}),i=Kc.parse(o);if(i.browserLoginOrigin!==ai())return{evictCookie:pr(e.url)};let a={subjectId:i.sub};return i.roles&&i.roles.length>0&&(a.roles=i.roles),{principal:a}}catch(o){return o instanceof $c.JWTExpired?{evictCookie:pr(e.url)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:o instanceof Error?o.name:"unknown",errorMessage:o instanceof Error?o.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:pr(e.url)})}}n(xt,"readBrowserSession");async function It(e){let t=D().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:ai()};e.principal.roles&&(r.roles=e.principal.roles);let o=await new Fc(r).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await ii());return Jc({value:o,requestUrl:e.requestUrl,ttlSeconds:t})}n(It,"createBrowserSessionCookie");async function ci(e){let t={};e.context!==void 0&&(t.context=e.context);let r=await xt(e.request,t);if(r.principal)return r.principal;let o=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(!o)throw g("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.");let{exchangeFederatedAuthorizationCode:i}=await import("../browser-login-idp-HWMCSYMR.js");return i({code:o,nonce:e.stateId,requestUrl:e.request.url,...e.context===void 0?{}:{context:e.context}})}n(ci,"resolveBrowserLoginCallbackPrincipal");function di(e){let t=D().browserLogin,r=new URL(lt("url")),o=new URL("/oauth/callback",wn(e.requestUrl));return An(r)?(r.searchParams.set("redirect_uri",o.toString()),r.searchParams.set("state",e.state),r):(r.searchParams.set("response_type","code"),r.searchParams.set("client_id",lt("clientId")),r.searchParams.set("redirect_uri",o.toString()),r.searchParams.set("scope",t.scope),r.searchParams.set("state",e.state),r.searchParams.set("nonce",e.nonce),t.audience&&r.searchParams.set("audience",t.audience),r)}n(di,"buildBrowserLoginUrl");var Vc={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},p=class extends Error{static{n(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,o=Vc[t],i){super(r,i),this.name="OAuthProtocolError",this.errorCode=t,this.status=o}};var Yc=5*60,Xc=d.object({purpose:d.literal("gateway_browser_login"),transactionId:Mt,stateId:zt,exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),Qc=d.object({purpose:d.literal("gateway_authorization_setup"),transactionId:Mt,stateId:zt,exp:d.number().int().positive(),iat:d.number().int().positive().optional()});async function mi(){return G({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>re(e,"browser-login"),"derive")})}n(mi,"getBrowserLoginKey");async function fi(){return G({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>re(e,"authorization-csrf"),"derive")})}n(fi,"getCsrfKey");function hi(e){return{now:e.now??new Date,ttlSeconds:fr()}}n(hi,"readPendingTransactionDependencies");function ed(e,t){return e.subjectId===t.subjectId}n(ed,"principalsMatch");function gi(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}n(gi,"toPendingPrincipal");function yi(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,operationId:e.transaction.operationId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:_(e.now),expiresAt:_(F(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw g("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:gi(e.principal)}}n(yi,"createTransactionRecord");async function wi(e){let{id:t,...r}=e.record,o=await R().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(o.kind){case"started":return o.transaction;case"already_exists":throw g("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new p("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new p("invalid_request","redirect_uri is not registered for the client.")}}n(wi,"startPendingTransaction");async function td(e){return new pi({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await mi())}n(td,"signBrowserLoginState");async function _i(e){return new pi({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:Ht()}).setProtectedHeader({alg:M,typ:"JWT"}).setIssuer(T).setAudience(q).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await fi())}n(_i,"signCsrfToken");async function hr(e){try{let{payload:t}=await li(e,await mi(),{algorithms:[M],issuer:T,audience:q}),r=Xc.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof ui.JWTExpired?g("oauth_state_expired","Browser login state has expired.",t):g("oauth_state_invalid","Browser login state could not be verified.",t)}}n(hr,"verifyBrowserLoginStateToken");async function At(e){try{let{payload:t}=await li(e,await fi(),{algorithms:[M],issuer:T,audience:q});return{transactionId:Qc.parse(t).transactionId}}catch(t){throw t instanceof ui.JWTExpired?g("oauth_state_expired","Authorization setup state has expired.",t):g("oauth_state_invalid","Authorization setup state could not be verified.",t)}}n(At,"verifyCsrfToken");function gr(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}n(gr,"pendingStateErrorCode");function rd(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}n(rd,"toPendingAuthorizationGetResult");function nd(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}n(nd,"toPendingAuthorizationAdvanceResult");function yr(e){return e==="principal_mismatch"?"oauth_callback_mismatch":gr(e==="consumed_already"?"consumed_already":e)}n(yr,"setupDecisionErrorCode");async function Ri(e){let t=e.now??new Date,r=await At(e.csrfToken),o=await R().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await C(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:_(t)});if(o.kind!=="marked")throw g(yr(o.kind),"Authorization setup state is invalid, expired, or already used.");return bi({kind:"available",record:o.transaction})}n(Ri,"markSetupApproved");function bi(e){if(e.kind!=="available")throw g(gr(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}n(bi,"requireAwaitingSetup");function od(e){if(!ed(e.currentBrowserPrincipal,e.transaction.principal))throw g("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}n(od,"requireCurrentPrincipalMatches");async function Ci(e){let t=e.now??new Date,r=fr(),o=Dt(),i=Ht(),a=await td({transactionId:o,stateId:i,ttlSeconds:r}),s=yi({id:o,transaction:e.transaction,currentStateHash:await C(a),phase:"awaiting_login",now:t,ttlSeconds:r});if(s.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");let c=await wi({record:s,client:e.transaction.client});if(c.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");return{transaction:c,browserLoginStateToken:a,browserLoginUrl:di({state:a,nonce:i,operationId:s.operationId,requestUrl:e.requestUrl})}}n(Ci,"startAwaitingLogin");async function Si(e){let{now:t,ttlSeconds:r}=hi(e),o=Dt(),i=await _i({transactionId:o,ttlSeconds:r}),a=yi({id:o,transaction:e.transaction,currentStateHash:await C(i),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(a.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");let s=await wi({record:a,client:e.transaction.client});if(s.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:s,csrfToken:i}}n(Si,"startAwaitingSetup");async function vi(e){let{now:t,ttlSeconds:r}=hi(e),o=await hr(e.browserLoginStateToken),i=await _i({transactionId:o.transactionId,ttlSeconds:r}),a=nd(await R().advancePendingAuthorization({transactionId:o.transactionId,expectedPhase:"awaiting_login",currentStateHash:await C(e.browserLoginStateToken),nextStateHash:await C(i),nextPhase:"awaiting_setup",principal:gi(e.principal),now:_(t)}));if(a.kind!=="advanced")throw g(gr(a.kind),"Browser login state is invalid, expired, or already used.");if(a.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:a.record,csrfToken:i}}n(vi,"completeLogin");async function xi(e){let t=await wr(e);return od({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}n(xi,"getSetup");async function wr(e){let t=e.now??new Date,r=await At(e.csrfToken);return bi(rd(await R().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await C(e.csrfToken),now:_(t)})))}n(wr,"getSetupTransaction");async function id(e){let t=await At(e.csrfToken),r=W(),o=_(F(e.now,Yc)),i=await R().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await C(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await C(r),authorizationCodeExpiresAt:o,grantId:xn(),now:_(e.now)});if(i.kind!=="approved")throw g(i.kind==="cancelled"?"oauth_state_invalid":yr(i.kind),"Authorization setup state is invalid, expired, or already used.");let a=new URL(i.transaction.redirectUri);return a.searchParams.set("code",r),i.transaction.clientState&&a.searchParams.set("state",i.transaction.clientState),a}n(id,"createAuthorizationCodeRedirectWithDecision");async function ad(e){let t=await At(e.csrfToken),r=await R().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await C(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:_(e.now)});if(r.kind!=="cancelled")throw g(r.kind==="approved"?"oauth_state_invalid":yr(r.kind),"Authorization setup state is invalid, expired, or already used.");return sd({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}n(ad,"createCancelRedirectWithDecision");function sd(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),t}n(sd,"buildClientCancelRedirect");async function Ii(e){let t=e.now??new Date;return id({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Ii,"approve");async function Ai(e){let t=e.now??new Date;return ad({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Ai,"cancel");z();var cd=1e4,dd=5*1024,ud=2,ld=90*24*60*60,_r=["authorization_code","refresh_token"],Rr=["code"],pd=d.object({client_name:d.string().min(1).optional(),redirect_uris:d.array(d.string().min(1)).min(1),grant_types:d.array(d.enum(_r)).min(1).max(2).optional(),response_types:d.array(d.enum(Rr)).min(1).max(1).optional(),scope:d.literal(P).optional(),token_endpoint_auth_method:Sn.default("none")});function md(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&se(t))&&t.pathname!=="/"}catch{return!1}}n(md,"isCimdClientIdCandidate");function Ie(e,t="invalid_request",r="authorize"){if(fd(e))throw new p(t,"redirect_uris must not include raw whitespace or control characters.");let o;try{o=new URL(e)}catch{throw new p(t,"redirect_uris must be absolute URIs.")}if(o.hash||o.username||o.password)throw new p(t,"redirect_uris must not include credentials or fragments.");let i={source:r},a=bn({url:o,context:i});if(a.kind!=="rejected"){a.mode!=="strict"&&void 0;return}throw new p(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}n(Ie,"assertValidRedirectUri");function fd(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}n(fd,"hasForbiddenRawRedirectUriCharacter");async function hd(e){let{response:t,json:r}=await Fn(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:ud,maxResponseBytes:dd,timeoutMs:cd});if(!t.ok)throw g("invalid_request","CIMD metadata could not be fetched.");let o=vn.parse(r);for(let i of o.redirect_uris)Ie(i,"invalid_request","cimd");if(o.client_id!==e.clientId)throw g("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return o}n(hd,"fetchCimdMetadata");async function gd(e){let t=Gn(e),r=await hd({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}n(gd,"resolveCimdClient");async function Ut(e,t){let r=ee.parse(e);if(md(r)){if(!D().gateway.cimdEnabled)throw new p("invalid_client","OAuth client is not registered.");try{return await gd(r)}catch{throw new p("invalid_client","OAuth client is not registered.")}}let o=await R().readClient({clientId:r});if(o.kind==="found"){let i=o.client,a={kind:"dcr",clientId:r,metadata:{client_id:i.clientId,client_name:i.clientName,redirect_uris:i.redirectUris,token_endpoint_auth_method:i.tokenEndpointAuthMethod}};return i.hashedClientSecret&&(a.hashedClientSecret=i.hashedClientSecret),a}throw new p("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}n(Ut,"resolveClient");function Ui(e,t){if(!e.metadata.redirect_uris.some(r=>In(r,t)))throw g("invalid_request","redirect_uri is not registered for the client.")}n(Ui,"assertRedirectRegistered");function yd(e){let t=ki(e.grant_types),r=e.response_types??[...Rr];if(!wd(t))throw new p("invalid_client_metadata","grant_types must be a subset of authorization_code and refresh_token.");if(!_d(r))throw new p("invalid_client_metadata","response_types must be code.");if(!Rd(e.scope))throw new p("invalid_client_metadata",`Only the ${P} scope is supported.`)}n(yd,"assertSupportedDcrRequest");function ki(e){return e===void 0?[..._r]:Array.from(new Set(e))}n(ki,"normalizeGrantTypes");function wd(e){return e.length===0?!1:e.every(t=>_r.includes(t))}n(wd,"isSupportedGrantTypes");function _d(e){return e.length===Rr.length&&e[0]==="code"}n(_d,"isSupportedResponseTypes");function Rd(e){return e===void 0||e===P}n(Rd,"isSupportedDcrScope");function Ke(e){if(e===void 0||e===P)return P;throw new p("invalid_request",`Only the ${P} scope is supported.`)}n(Ke,"assertSupportedOAuthScope");function Ae(e,t){let r;try{r=new URL(t)}catch{throw new p("invalid_target","resource must be an absolute URI.")}if(r.hash)throw new p("invalid_target","resource must not include a fragment.");if(r.protocol!=="https:"&&!se(r))throw new p("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let o=I(e),i=yn(),a=i?[...i.byOperationId.values()].find(s=>new URL(s.routePath,o).toString()===t):void 0;if(!a)throw new p("invalid_target","resource must match a published MCP route.");return a}n(Ae,"resolveResource");async function Pi(e){let t;try{t=pd.parse(e)}catch(m){if(m instanceof d.ZodError){let v=m.issues.some(L=>L.path[0]==="redirect_uris");throw new p(v?"invalid_redirect_uri":"invalid_client_metadata",m.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:m})}throw m}yd(t);for(let m of t.redirect_uris)Ie(m,"invalid_redirect_uri","dcr");let r=new Date,o=ee.parse(`dcr:${crypto.randomUUID()}`),i=F(r,ld),a=Math.floor(r.getTime()/1e3),s=Math.floor(i.getTime()/1e3),c={client_id:o,client_name:t.client_name??"Dynamically registered MCP client",redirect_uris:t.redirect_uris,grant_types:ki(t.grant_types),response_types:["code"],scope:P,token_endpoint_auth_method:t.token_endpoint_auth_method,client_id_issued_at:a},l={clientId:o,clientName:String(c.client_name),redirectUris:t.redirect_uris,tokenEndpointAuthMethod:t.token_endpoint_auth_method,createdAt:_(r),clientExpiresAt:_(i)};if(t.token_endpoint_auth_method!=="none"){let m=W();l.hashedClientSecret=await C(m),l.clientSecretExpiresAt=_(i),c.client_secret=m,c.client_secret_expires_at=s,c.client_secret_issued_at=a}if((await R().registerClient(l)).kind==="already_exists")throw g("invalid_request","OAuth client is already registered.");return c}n(Pi,"registerDownstreamClient");function Ti(e){return b`<form class="actions" method="post" action="/oauth/setup" ${e.submitOnceAttrs}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate >Cancel</button><button class="button button--primary" type="submit" name="decision" value="approve" ${e.authorizeAttrs} >Authorize</button></form>`}n(Ti,"renderActions");var _h=V('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="4.6" x2="8" y2="8.4"/><circle cx="8" cy="11" r=".7" fill="currentColor" stroke="none"/></svg>');var Rh=V('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),bh=V('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>');var Ch=V('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var bd="data:,",Oi=b`data-submit-once="true" onsubmit="if (this.dataset.submitted === 'true') return false; this.dataset.submitted = 'true'; setTimeout(() => this.querySelectorAll('button').forEach((button) => { button.disabled = true; }), 0);"`,Ei=b`data-activate-once="true" onclick="if (this.dataset.activated === 'true') return false; this.dataset.activated = 'true'; this.setAttribute('aria-disabled', 'true'); this.style.pointerEvents = 'none';"`;function Cd(e,t){if(e)try{let r=new URL(t).origin,o=new URL(e,r);return o.origin!==r||!o.pathname.startsWith("/auth/connections/")?void 0:o.toString()}catch{return}}n(Cd,"safeGatewayConnectHref");function Sd(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}n(Sd,"deriveMode");function vd(e){return Ti({state:e.state,submitOnceAttrs:Oi,authorizeAttrs:he})}n(vd,"renderActions");function br(e,t,r){for(let o of e){if(o.ownerMode!=="user"||o.status!==r)continue;let i=Cd(o.connectUrl,t);if(i)return i}}n(br,"firstUserConnectHref");function xd(e){let t=e.connectHref?b`<a class="button button--primary" href="${e.connectHref}" ${Ei}>Connect</a>`:b`<button class="button button--primary" type="button" disabled aria-disabled="true">Connect</button>`;return b`<form class="actions" method="post" action="/oauth/setup" ${Oi}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate>Cancel</button>${t}</form>`}n(xd,"renderSetupActions");function Id(e){return e?b`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${Ei}>Re-connect<span class="tooltip" tabindex="0" aria-label="Reset or change how the gateway connects to the upstream service, including changing scopes.">?</span></a></span>`:he}n(Id,"renderReconnectAction");function Cr(e){let t=Sd(e.upstreams),r=br(e.upstreams,e.gatewayOrigin,"not_connected"),o=br(e.upstreams,e.gatewayOrigin,"reconsent_required"),i=br(e.upstreams,e.gatewayOrigin,"active"),a=t==="setup"?r??o:void 0,s=b`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>`,c=t==="setup"?b`<footer class="card__footer">${xd({state:e.state,connectHref:a})}</footer>`:b`<footer class="card__footer">${Id(i)}${vd({state:e.state})}</footer>`;return Ce(ve({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:bd,styles:Se,headerIcon:he,heading:"MCP Gateway",subhead:he,body:s,footer:c}))}n(Cr,"renderConsentPage");var Ad=1e4,qi="mcp-session-id",Ud,Mi;function Li(){return{tools:[],prompts:[],resources:[]}}n(Li,"emptyCapabilities");function zi(e){let t=new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":Bt});switch(e.type){case"none":return t;case"bearer_token":return t.set("authorization",`Bearer ${e.token}`),t;case"headers":for(let[r,o]of Object.entries(e.headers))t.set(r,o);return t;case"mcp_oauth_provider":throw new Error("MCP OAuth provider credentials require async headers.")}}n(zi,"buildCredentialHeaders");async function Di(e){if(e.type!=="mcp_oauth_provider")return zi(e);let t=await e.provider.tokens();if(!t)return;let r=zi({type:"none"});return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}n(Di,"buildAsyncCredentialHeaders");function Hi(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(ot.parse({jsonrpc:nt,id:1,method:"initialize",params:{protocolVersion:Bt,capabilities:{},clientInfo:{name:"zuplo-mcp-gateway-readiness",version:"0.0.0"}}}))})}n(Hi,"buildInitializePreflight");async function Sr(e){Nn(e.url);let t=new AbortController,r=setTimeout(()=>t.abort(),Ad);try{let o=new Request(e,{redirect:"manual",signal:t.signal});return Mi?await Mi(o):await Xe.fetch(o)}finally{clearTimeout(r)}}n(Sr,"runPreflight");function vr(e){e.body?.cancel().catch(()=>{})}n(vr,"releasePreflightBody");async function kd(e){let t=e.response.headers.get(qi);if(!t)return;let r=new Headers(e.headers);r.set(qi,t),r.delete("content-type");try{let o=await Sr(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));vr(o)}catch{}}n(kd,"terminatePreflightSession");async function ji(e){let{response:t}=e;return vr(t),t.status>=200&&t.status<300?(await kd(e),{kind:"ready",upstreamStatus:t.status,capabilities:Li()}):t.status===401||t.status===403?{kind:"upstream_auth_rejected",status:t.status,message:"Upstream MCP server rejected the configured credential."}:{kind:"upstream_unavailable",status:t.status,message:"Upstream MCP server did not accept the readiness preflight."}}n(ji,"classifyResponse");function Bi(e){let t={status:e.state==="reconsent_required"?"reconsent_required":"not_connected",connected:!1};return e.nextAction==="admin_setup_required"?{kind:"admin_setup_required",payload:e,connectionStatus:t}:{kind:"connect_required",payload:e,connectionStatus:t}}n(Bi,"connectRequiredResult");async function Pd(e){try{return ji({response:await Sr(e.request),upstreamUrl:e.upstreamUrl,headers:e.headers})}catch(t){return{kind:"upstream_unavailable",message:t instanceof Error?t.message:"Upstream MCP server readiness preflight failed."}}}n(Pd,"classifyPreflight");async function Td(e){let t=e.route.connection;if(t===void 0)return{kind:"ready",upstreamStatus:204,capabilities:Li()};let r=Rt(t.upstreamServerId,e.route.operationId),o=be(r,e.principal),i=e.returnTo===void 0?o:{...o,returnTo:e.returnTo},a=await Re({request:new Request(e.requestUrl),routeAuth:i,preloadedConnection:e.preloadedConnection});if(a.kind==="connect_required")return Bi(a.payload);let s=await Di(a.credential);if(s===void 0)return{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens."};let c=Hi({upstreamUrl:t.mcpUrl,headers:s}),l;try{l=await Sr(c)}catch(v){return{kind:"upstream_unavailable",message:v instanceof Error?v.message:"Upstream MCP server readiness preflight failed."}}if(l.status!==401)return ji({response:l,upstreamUrl:t.mcpUrl,headers:s});vr(l);let h=await Re({request:new Request(e.requestUrl),routeAuth:i,forceRefresh:!0,preloadedConnection:e.preloadedConnection});if(h.kind==="connect_required")return Bi(h.payload);let m=await Di(h.credential);return m===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:Pd({request:Hi({upstreamUrl:t.mcpUrl,headers:m}),upstreamUrl:t.mcpUrl,headers:m})}n(Td,"checkUpstreamRouteReadinessImpl");function Ni(e){return(Ud??Td)(e)}n(Ni,"checkUpstreamRouteReadiness");function Od(e){try{return new URL(e).host}catch{return}}n(Od,"safeUrlHost");function Ed(e){if(e.mode==="user-oauth"||e.mode==="shared-oauth")return e.oauth.scopes}n(Ed,"readOAuthScopes");function Gi(e){return e!==void 0&&e.length>0}n(Gi,"hasItems");function qd(e){let t=e.serverInfo?.icons;return Gi(t)?t:void 0}n(qd,"readServerIcons");async function Md(e){if(!(e.returnTo===void 0||!e.isUserOwned))return nr({requestUrl:e.requestUrl,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:e.registeredConnection.upstreamServerId,authProfileId:e.registeredConnection.authProfileId,operationId:e.route.operationId,returnTo:e.returnTo})}n(Md,"readConnectUrl");function ge(e,t){return t===void 0?{}:{[e]:t}}n(ge,"optionalRequirementField");function zd(e){return e.readiness!==void 0?e.readiness:e.isUserOwned?Dn(e.connection):{connected:!0,status:"active"}}n(zd,"readSetupConnectionStatus");function Dd(e){let t=Ed(e);return Gi(t)?t:void 0}n(Dd,"readScopesRequested");function Hd(e){return e.isUserOwned&&"updatedAt"in e.connectionStatus&&e.connectionStatus.updatedAt!==void 0?e.connectionStatus.updatedAt:void 0}n(Hd,"readUpdatedAt");function Bd(){return{tools:[],prompts:[],resources:[]}}n(Bd,"readRouteCapabilities");async function Ld(e){let{authConfig:t,authMode:r,description:o,displayName:i,mcpUrl:a,upstreamServerId:s,authProfileId:c}=e.registeredConnection,l=ft(r),h=l==="user",m=zd({connection:e.connection,isUserOwned:h,readiness:e.readiness}),v=e.readiness?.connectUrl??await Md({...e,connected:m.connected,isUserOwned:h});return{upstreamServerId:s,authProfileId:c,authMode:r,ownerMode:l,upstreamDisplayName:i,status:m.status,connected:m.connected,capabilities:Bd(),...ge("description",o),...ge("transportHost",Od(a)),...ge("scopesRequested",Dd(t)),...ge("serverIcons",qd(e.registeredConnection)),...ge("connectUrl",v),...ge("updatedAt",Hd({connectionStatus:m,isUserOwned:h})),...ge("expiresAt",e.readiness?.expiresAt??e.connection?.expiresAt)}}n(Ld,"buildSetupRequirement");function $i(e){let t=j().byOperationId.get(e);if(!t)throw g("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}n($i,"requireRoute");async function xr(e){let t=$i(e.transaction.operationId),r=dt(e.transaction.principal.subjectId),o=[],i=new Map,a=t.connection;if(a===void 0)return[];ft(a.authMode)==="user"&&(i.set(a,o.length),o.push({owner:r,upstreamServerId:a.upstreamServerId,authProfileId:a.authProfileId}));let s=await R().batchGetUpstreamConnections(o),c=[],l=ft(a.authMode)==="user",h=i.get(a),m=await Ni({requestUrl:e.requestUrl,route:t,principal:e.transaction.principal,preloadedConnection:l&&h!==void 0?s[h]:void 0,...e.returnTo===void 0?{}:{returnTo:e.returnTo}}),v=(()=>{if("connectionStatus"in m&&m.connectionStatus)return m.connectionStatus})(),L=(m.kind==="connect_required"||m.kind==="admin_setup_required")&&m.payload.authUrl!==void 0?m.payload.authUrl:void 0;return c.push(await Ld({connection:l&&h!==void 0?s[h]:void 0,registeredConnection:a,route:t,requestUrl:e.requestUrl,returnTo:e.returnTo,transaction:e.transaction,userOwner:r,readiness:v===void 0?void 0:{...v,...L===void 0?{}:{connectUrl:L}}})),c}n(xr,"requirementsForSetup");function jd(e){return e.route.connection?.displayName??e.route.operationId}n(jd,"readRouteDisplayName");async function Ir(e){let t=$i(e.transaction.operationId),r=jd({route:t}),o=await R().readClient({clientId:e.transaction.clientId}),i=o.kind==="found"?o.client:void 0,a={gatewayOrigin:I(e.requestUrl),routeDisplayName:r,clientDisplayName:i?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},s=t.connection?.description;return s!==void 0&&(a.routeDescription=s),a}n(Ir,"consentContext");function Ar(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}n(Ar,"hasUnresolvedUserUpstream");var Nd=["mcp_user"],Gd="dev-browser-user",$d=["resource is required for /oauth/authorize.","MCP clients should start at the MCP server URL and follow its WWW-Authenticate resource_metadata link.","If your client reached this endpoint directly, use /oauth/authorize/{routePath} where {routePath} is the published MCP route path without a leading slash and each segment is URL-encoded as needed, for example /oauth/authorize/mcp/linear, or add resource={protected resource URI from protected-resource metadata}."].join(" "),Zd=d.object({response_type:d.literal("code"),client_id:d.string().min(1),redirect_uri:d.string().min(1),resource:d.url(),code_challenge:d.string().min(43),code_challenge_method:Cn,state:d.string().min(1).optional(),scope:d.literal(P).default(P)}),Fd=d.enum(["continue","approve","cancel"]).default("continue"),Kd=d.object({state:d.string().min(1),decision:Fd}),oe=class extends Error{static{n(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription}};function Zi(e){return typeof e=="string"&&e.length>0?e:void 0}n(Zi,"readQueryString");function Wd(e){let t=Array.from(j().byOperationId.values());if(t.length!==1)return;let r=t[0];if(r!==void 0)return Lt(r.operationId,e.url)}n(Wd,"inferSingleRouteResource");function Jd(e,t){let r=Zi(e.query.resource);if(t===void 0){if(r!==void 0)return r;let i=Wd(e);if(i!==void 0)return i;throw new p("invalid_target",$d)}let o=Lt(t,e.url);if(r===void 0||r===o)return o;throw new p("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}n(Jd,"requireAuthorizeResource");async function Vd(e,t){let r={};t!==void 0&&(r.context=t);let o=await xt(e,r);if(o.principal)return{principal:o.principal};if(!e.user)return o.evictCookie===void 0?{}:{setCookie:o.evictCookie};let i=si(e);return{principal:i,setCookie:await It({principal:i,requestUrl:e.url})}}n(Vd,"resolveBrowserPrincipal");async function Yd(e,t){let r={};t!==void 0&&(r.context=t);let o=await xt(e,r);if(!o.principal)throw g("authentication_required","Authorization setup requires a current browser session.");return o.principal}n(Yd,"requireSetupPrincipal");function Fi(e){return`/oauth/setup?state=${encodeURIComponent(e)}`}n(Fi,"buildSetupReturnTo");async function Ki(e){let t=await xr({transaction:e.transaction,requestUrl:e.requestUrl,returnTo:Fi(e.csrfToken)}),r=await Ir({transaction:e.transaction,requestUrl:e.requestUrl}),o={kind:"setup_page",html:Cr({state:e.csrfToken,operationId:e.transaction.operationId,upstreams:t,...r})};return e.setCookie!==void 0&&(o.setCookie=e.setCookie),o}n(Ki,"renderSetup");function Xd(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}n(Xd,"toAuthorizationTransactionClient");async function Ur(e,t={}){let r=Zd.parse({...e.query,resource:Jd(e,t.operationId),state:Zi(e.query.state)}),o=Ke(r.scope);Ie(r.redirect_uri,"invalid_request","authorize");let i=new Date,a=ee.parse(r.client_id),s=await Ut(r.client_id,i);Ui(s,r.redirect_uri);try{let c=Ae(e.url,r.resource),l=Xd(s);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:a,operationId:c.operationId,scope:o,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved"),t.context&&A(t.context,{eventType:x.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:c.operationId,attributes:{clientId:a,scope:o,responseType:r.response_type}});let h={clientId:s?.clientId??a,...l===void 0?{}:{client:l},redirectUri:r.redirect_uri,resource:r.resource,operationId:c.operationId,scope:o,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state}},{principal:m,setCookie:v}=await Vd(e,t.context);if(!m){let X=await Ci({transaction:h,requestUrl:e.url,now:i});t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:a,operationId:c.operationId},"Downstream OAuth authorize: redirecting to browser login (no session)");let Ye={kind:"redirect",location:X.browserLoginUrl};return v!==void 0&&(Ye.setCookie=v),Ye}let L=await Si({transaction:h,principal:m,now:i});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:a,operationId:c.operationId,subjectId:m.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),t.context&&A(t.context,{eventType:x.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:c.operationId,attributes:{clientId:a,scope:o,responseType:r.response_type,subjectId:m.subjectId}}),Ki({transaction:L.transaction,csrfToken:L.csrfToken,requestUrl:e.url,setCookie:v})}catch(c){throw Qd({redirectUri:r.redirect_uri,clientState:r.state,cause:c})}}n(Ur,"authorizeDownstreamClient");function Qd(e){if(e.cause instanceof oe)return e.cause;let t=eu(e.cause);return t?new oe({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}n(Qd,"toDownstreamAuthorizeRedirectError");function eu(e){if(e instanceof p)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof d.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}n(eu,"mapToOAuthRedirectError");async function Wi(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let h=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,m=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...h===void 0?{}:{idpErrorDescription:h},...m===void 0?{}:{idpErrorUri:m}},"Identity provider redirected browser-login callback with an error"),g("provider_access_denied",h??"The delegated browser login was not completed.")}let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),g("oauth_state_invalid","Browser login callback is missing state.");let i=await hr(o),a={request:e,stateId:i.stateId};t.context!==void 0&&(a.context=t.context);let s=await ci(a),c=await vi({browserLoginStateToken:o,principal:s}),l=await Ki({transaction:c.transaction,csrfToken:c.csrfToken,requestUrl:e.url});return l.setCookie=await It({principal:s,requestUrl:e.url}),l}n(Wi,"completeBrowserLoginCallback");async function Ji(e){let t=D(),r=new URL(e.url);if(!se(r))throw g("forbidden","Local browser login is only available on loopback HTTP origins.");let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw g("oauth_state_invalid","Local browser login is missing state.");let i=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:"/oauth/callback",I(e.url)),a=new URL(I(e.url)).origin;if(i.origin!==a||i.pathname!=="/oauth/callback")throw g("oauth_callback_mismatch","Local browser login redirect_uri must target this gateway's /oauth/callback route.");i.searchParams.set("state",o);let s={subjectId:st.parse(Gd),roles:Nd};return{kind:"redirect",location:i,setCookie:await It({principal:s,requestUrl:e.url})}}n(Ji,"completeLocalDevBrowserLogin");function tu(e){let t=e.method==="POST"?e.body:e.query;return Kd.parse(t)}n(tu,"readSetupContinueRequest");async function Vi(e){let{state:t,decision:r}=tu({method:e.request.method,query:e.request.query,body:e.body}),o=new Date,i=await wr({csrfToken:t,now:o}),a=await Yd(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await Ai({csrfToken:t,currentBrowserPrincipal:a,now:o})};let s=await xi({csrfToken:t,currentBrowserPrincipal:a,now:o}),c=await xr({transaction:s,requestUrl:e.request.url,returnTo:Fi(t)});if(r==="approve"&&Ar(c)&&await Ri({csrfToken:t,currentBrowserPrincipal:a,now:o}),Ar(c)){let l=await Ir({transaction:s,requestUrl:e.request.url});return{kind:"setup_page",html:Cr({state:t,operationId:s.operationId,upstreams:c,...l})}}return{kind:"redirect",location:await Ii({csrfToken:t,currentBrowserPrincipal:a,now:o})}}n(Vi,"continueDownstreamAuthorizeSetup");z();import{createLocalJWKSet as ru,decodeJwt as nu,errors as We,jwtVerify as ou}from"jose";var iu=new Set(["authorization_code","refresh_token"]),au="urn:ietf:params:oauth:client-assertion-type:jwt-bearer",su=1e4,cu=32*1024,du=2,Yi=d.object({client_id:d.string().min(1).optional(),client_secret:d.string().min(1).optional(),client_assertion_type:d.string().min(1).optional(),client_assertion:d.string().min(1).optional()}),uu=d.discriminatedUnion("grant_type",[Yi.extend({grant_type:d.literal("authorization_code"),code:d.string().min(1),redirect_uri:d.string().min(1),code_verifier:at,resource:d.url().optional(),scope:d.literal(P).optional()}),Yi.extend({grant_type:d.literal("refresh_token"),refresh_token:d.string().min(1),resource:d.url().optional(),scope:d.literal(P).optional()})]);function lu(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!iu.has(t)))throw new p("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}n(lu,"assertSupportedGrantType");var pu=d.object({token:d.string().min(1),client_id:d.string().min(1).optional(),token_type_hint:d.string().optional(),client_secret:d.string().min(1).optional(),client_assertion_type:d.string().min(1).optional(),client_assertion:d.string().min(1).optional()}),mu=d.object({keys:d.array(d.record(d.string(),d.unknown())).min(1)}).passthrough();function Xi(){return D().gateway.accessTokenTtlSeconds}n(Xi,"readAccessTokenTtlSeconds");function fu(){return D().gateway.refreshTokenTtlSeconds}n(fu,"readRefreshTokenTtlSeconds");function hu(e,t){let r=Xi(),o=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),i=Math.min(r,o);return{expiresAt:_(F(e,i)),expiresIn:i}}n(hu,"calculateAccessTokenExpiresAt");function Qi(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new p("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new p("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new p("invalid_client","Malformed HTTP Basic client authentication.")}}n(Qi,"readBasicClientSecret");function ea(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new p("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t!==void 0)return t;if(e.clientAssertion!==void 0){try{let r=nu(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new p("invalid_client","Malformed private_key_jwt client assertion.")}throw new p("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new p("invalid_client","Client authentication or client_id is required.")}n(ea,"resolveAuthenticatedClientId");function gu(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new p("invalid_request","Use only one client authentication method per request.");return e.basicClientSecret!==void 0?{clientSecret:e.basicClientSecret,clientSecretSource:"basic"}:e.bodyClientSecret!==void 0?{clientSecret:e.bodyClientSecret,clientSecretSource:"post"}:{}}n(gu,"resolveClientSecretInput");function yu(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}n(yu,"hasClientAssertion");function wu(e){if(e.requestUrl===void 0)throw new p("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(e.pathname,e.requestUrl);return t.search="",t.hash="",t.toString()}n(wu,"buildEndpointAudience");function _u(e){return e instanceof We.JWTExpired?"expired":e instanceof We.JWTClaimValidationFailed?"claim":e instanceof We.JWSSignatureVerificationFailed?"signature":e instanceof We.JWKSNoMatchingKey?"jwks_no_match":e instanceof We.JWTInvalid?"invalid":e instanceof d.ZodError?"schema":"other"}n(_u,"readJwtFailureKind");async function Ru(e){let{response:t,json:r}=await Kn(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:du,maxResponseBytes:cu,timeoutMs:su});if(!t.ok)throw new p("invalid_client","Client JWKS could not be fetched.");return mu.parse(r)}n(Ru,"fetchClientJwks");async function bu(e){if(e.clientAssertionType!==au||e.clientAssertion===void 0)throw new p("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=ee.parse(e.clientId),r=await Ut(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new p("invalid_client","Client is not registered for private_key_jwt authentication.");let o=r.metadata.jwks_uri;if(o===void 0)throw new p("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let i=wu({requestUrl:e.requestUrl,pathname:e.endpointPathname});try{let a=await Ru({jwksUri:o,context:e.context});await ou(e.clientAssertion,ru(a),{issuer:t,subject:t,audience:i,currentDate:e.now})}catch(a){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:_u(a)},"OAuth private_key_jwt client authentication failed"),new p("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}n(bu,"verifyPrivateKeyJwtClientAssertion");async function Cu(e){let t=ee.parse(e.clientId);return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await C(e.clientSecret)}}n(Cu,"buildRuntimeHttpClientAuth");async function ta(e){if(yu({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new p("invalid_request","Use only one client authentication method per request.");return bu(e)}let t=gu({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return Cu({clientId:e.clientId,...t})}n(ta,"resolveRuntimeHttpClientAuth");async function ra(e){lu(e.body);let t=uu.parse(e.body),r=Qi(e.authorizationHeader),o=ea({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),i=new Date,a=await ta({clientId:o,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,endpointPathname:"/oauth/token",now:i,context:e.context});return Su({parsed:t,clientId:o,clientAuth:a,now:i,requestUrl:e.requestUrl,context:e.context})}n(ra,"exchangeDownstreamToken");async function Su(e){if(e.parsed.grant_type==="authorization_code"){Ie(e.parsed.redirect_uri,"invalid_request","token"),Ke(e.parsed.scope),e.parsed.resource!==void 0&&Ae(e.requestUrl??e.parsed.resource,e.parsed.resource);let s=W(),c=W(),l=_(F(e.now,fu())),h=hu(e.now,l),m=await R().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await C(e.parsed.code),redirectUri:e.parsed.redirect_uri,...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},codeChallenge:await jn(e.parsed.code_verifier),currentRefreshTokenHash:await C(s),accessTokenHash:await C(c),grantExpiresAt:l,accessTokenExpiresAt:h.expiresAt,now:_(e.now)});if(m.kind==="invalid_client")throw new p("invalid_client","Client authentication failed.");if(m.kind==="resource_mismatch")throw new p("invalid_target","Token request resource must match the authorization code resource.");if(m.kind!=="exchanged")throw new p("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&A(e.context,{eventType:x.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:c,token_type:"Bearer",expires_in:h.expiresIn,refresh_token:s,scope:m.grant.scope,resource:m.grant.resource}}Ke(e.parsed.scope),e.parsed.resource!==void 0&&Ae(e.requestUrl??e.parsed.resource,e.parsed.resource);let t=W(),r=W(),o=_(F(e.now,Xi())),i=await R().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:await C(e.parsed.refresh_token),nextRefreshTokenHash:await C(t),accessTokenHash:await C(r),...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},accessTokenExpiresAt:o,now:_(e.now)});if(i.kind==="invalid_client")throw new p("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new p("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new p("invalid_grant","Refresh token is invalid, expired, or revoked.");Ae(e.requestUrl??i.grant.resource,i.grant.resource);let a=i.accessToken.expiresAt;return e.context&&(A(e.context,{eventType:x.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),A(e.context,{eventType:x.MCP_OAUTH_TOKEN_REFRESH_ROTATED,outcome:"success",attributes:{clientId:e.clientId}})),{access_token:r,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(a).getTime()-e.now.getTime())/1e3)),refresh_token:t,scope:i.grant.scope,resource:i.grant.resource}}n(Su,"exchangeDownstreamTokenWithRuntimeHttp");async function na(e){let t=pu.parse(e.body),r=Qi(e.authorizationHeader),o=ea({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),i=new Date;if((await R().revokeOAuthToken({clientAuth:await ta({clientId:o,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,endpointPathname:"/oauth/revoke",now:i,context:e.context}),tokenHash:await C(t.token),now:_(i)})).kind==="invalid_client")throw new p("invalid_client","Client authentication failed.");e.context?.log.info({event:"oauth_token_revoked",clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed"),e.context&&A(e.context,{eventType:x.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}n(na,"revokeDownstreamToken");var vu=64*1024,xu=16*1024,Iu="text/html; charset=utf-8";function Au(e){let t={};for(let[r,o]of e.entries())t[r]=o;return t}n(Au,"formDataToObject");async function Uu(e){return ni(e,{maxBytes:vu,label:"Request body"})}n(Uu,"readJsonBody");async function kr(e){return Au(await oi(e,{maxBytes:xu,label:"Request body"}))}n(kr,"readFormBody");async function oa(e,t,r){let o=ce(r),i=r instanceof d.ZodError?kt(r):void 0,a={code:o??(r instanceof d.ZodError?"invalid_request":"internal_server_error")};return i!==void 0&&(a.detail=i),Rn(e,t,a)}n(oa,"handleProblem");function Je(e){let t=new Headers(e.headers);t.set("cache-control","no-store"),t.set("pragma","no-cache");let r={error:e.error};return e.errorDescription!==void 0&&(r.error_description=e.errorDescription),Response.json(r,{status:e.status??400,headers:t})}n(Je,"oauthErrorResponse");function ku(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}n(ku,"readOAuthProtocolHeaders");function Pu(e,t){let r=H("internal_server_error");return Je({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:ku(e,t)})}n(Pu,"oauthProtocolErrorResponse");function ia(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}n(ia,"readZodOAuthErrorCode");function Tu(e){let t={error:ia(e)},r=kt(e);return r!==void 0&&(t.errorDescription=r),Je(t)}n(Tu,"oauthZodErrorResponse");function Ou(e){let t=ce(e);if(t===void 0)return;let r=H(t);if(r.oauthError===void 0)return;let o={error:r.oauthError,status:qu(r.oauthError)};return r.oauthError==="server_error"?o.errorDescription=r.publicDetail:e instanceof Error?o.errorDescription=e.message:o.errorDescription=r.publicDetail,Je(o)}n(Ou,"oauthGatewayProblemResponse");function Eu(){let t={error:"server_error",status:500,errorDescription:H("internal_server_error").publicDetail};return Je(t)}n(Eu,"oauthFallbackErrorResponse");function qu(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}n(qu,"readOAuthStatus");function Pr(e,t={}){return e instanceof oe?ca(e):e instanceof p?Pu(e,t):e instanceof d.ZodError?Tu(e):Ou(e)??Eu()}n(Pr,"oauthProblemResponse");function Tr(e,t){let r=xe(e.url);if(t instanceof oe)return ca(t);if(t instanceof p){let a=H("internal_server_error");return $({host:r,kind:Mu(t.errorCode),title:"Authorization failed",detail:t.errorCode==="server_error"?a.publicDetail:t.message,code:t.errorCode,status:t.status})}if(t instanceof d.ZodError)return $({host:r,kind:"invalid_request",detail:kt(t)??"The authorization request was invalid.",code:ia(t)});let o=ce(t);if(o!==void 0){let a=H(o);return $({host:r,kind:sa(o),detail:a.status<500&&t instanceof Error?t.message:a.publicDetail,code:a.oauthError??o,status:a.status})}let i=H("internal_server_error");return $({host:r,kind:"internal_error",detail:i.publicDetail,code:"server_error",status:i.status})}n(Tr,"browserOAuthProblemResponse");function aa(e,t){let r=xe(e.url),o=ce(t);if(o!==void 0){let a=H(o);return $({host:r,kind:sa(o),detail:a.status<500&&t instanceof Error?t.message:a.publicDetail,code:o,status:a.status})}if(t instanceof d.ZodError)return $({host:r,kind:"invalid_request",detail:kt(t)??"The authorization request was invalid.",code:"invalid_request"});let i=H("internal_server_error");return $({host:r,kind:"internal_error",detail:i.publicDetail,code:"internal_server_error",status:i.status})}n(aa,"browserGatewayProblemResponse");function Mu(e){return e==="server_error"?"internal_error":"invalid_request"}n(Mu,"readOAuthBrowserErrorKind");function sa(e){if(H(e).status>=500)return"internal_error";switch(e){case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"configuration_error";case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"upstream_client_registration_required":return"admin_required";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"invalid_request":case"authentication_required":case"forbidden":case"not_found":case"too_many_requests":case"identity_context_missing":return"invalid_request";case"upstream_capability_invocation_failed":case"upstream_capability_unavailable":case"upstream_import_failed":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}n(sa,"readGatewayBrowserErrorKind");function Y(e,t,r){let o={event:t},i=!1;if(r instanceof p)o.oauthError=r.errorCode,o.status=r.status,K(o,"error",r);else if(r instanceof oe)o.oauthError=r.errorCode,K(o,"error",r);else if(r instanceof d.ZodError){o.code="invalid_request",K(o,"error",r);let a=r.issues[0];a&&(o.zodPath=a.path.join("."))}else{let a=ce(r);if(a!==void 0){let s=H(a);o.code=a,o.status=s.status,s.oauthError!==void 0&&(o.oauthError=s.oauthError),i=s.status>=500||s.oauthError==="server_error",K(o,"error",r)}else i=!0,K(o,"error",r)}if(i){let a=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(o,a.message)}else e.log.warn(o,"OAuth handler rejected the request")}n(Y,"logUnexpectedOAuthHandlerError");function ca(e){let t;try{t=new URL(e.redirectUri)}catch{return Je({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}n(ca,"downstreamAuthorizeRedirectErrorResponse");function kt(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}n(kt,"formatZodErrorDetail");function zu(e,t){let r={event:"browser_login_callback_failed",code:ce(t)??"invalid_request"};K(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}n(zu,"logBrowserLoginCallbackFailure");function da(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(null,{status:302,headers:t})}n(da,"redirectResultResponse");function Pt(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":Iu,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(e.html,{status:200,headers:t})}return da(e)}n(Pt,"authorizeResultResponse");async function ua(e,t){try{return Response.json(Un(e.url))}catch(r){return Y(t,"oauth_authorization_server_metadata_failed",r),oa(e,t,r)}}n(ua,"authorizationServerMetadataHandler");async function la(e,t){try{let r=jt(e.params.routePath);return Response.json(kn({operationId:r.operationId,requestUrl:e.url}))}catch(r){return Y(t,"oauth_authorization_server_metadata_failed",r),oa(e,t,r)}}n(la,"scopedAuthorizationServerMetadataHandler");async function pa(e,t){try{let r=await Pi(await Uu(e)),o=r,i=typeof o.client_id=="string"?o.client_id:void 0,a=typeof o.client_name=="string"?o.client_name:void 0,s=Array.isArray(o.redirect_uris)?o.redirect_uris.length:void 0,c=typeof o.token_endpoint_auth_method=="string"?o.token_endpoint_auth_method:void 0;return t.log.info({event:"oauth_dcr_client_registered",clientId:i,clientName:a,redirectUriCount:s,tokenEndpointAuthMethod:c},"OAuth Dynamic Client Registration completed"),A(t,{eventType:x.MCP_OAUTH_CLIENT_REGISTERED,outcome:"success",clientName:a,attributes:{clientId:i,redirectUriCount:s,tokenEndpointAuthMethod:c}}),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return Y(t,"oauth_register_failed",r),Pr(r)}}n(pa,"registerHandler");async function ma(e,t){try{return Pt(await Ur(e,{context:t}))}catch(r){return Y(t,"oauth_authorize_failed",r),Tr(e,r)}}n(ma,"authorizeHandler");async function fa(e,t){try{let r=jt(e.params.routePath);return Pt(await Ur(e,{operationId:r.operationId,context:t}))}catch(r){return Y(t,"oauth_authorize_scoped_failed",r),Tr(e,r)}}n(fa,"scopedAuthorizeHandler");async function ha(e,t){try{let r=await Wi(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),Pt(r)}catch(r){return zu(t,r),aa(e,r)}}n(ha,"callbackHandler");async function ga(e,t){try{return da(await Ji(e))}catch(r){return Y(t,"oauth_dev_login_failed",r),Tr(e,r)}}n(ga,"devLoginHandler");async function ya(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await Vi({request:e,body:e.method==="POST"?await kr(e):void 0,context:t});return Pt(r)}catch(r){return Y(t,"oauth_setup_failed",r),aa(e,r)}}n(ya,"setupHandler");async function wa(e,t){try{return Response.json(await ra({body:await kr(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return Y(t,"oauth_token_failed",r),Pr(r)}}n(wa,"tokenHandler");async function _a(e,t){try{return await na({body:await kr(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return Y(t,"oauth_revoke_failed",r),Pr(r)}}n(_a,"revokeHandler");var Du={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},Ra=new Nr("upstream-request");function Hu(e){let t=Ra.get(e);if(!t)throw new E("Upstream request context has not been set");return t}n(Hu,"readUpstreamRequestContext");function Bu(e,t){return t.some(r=>r===e)}n(Bu,"requestContextMatchesKind");function Lu(e){return typeof e=="string"?[e]:e}n(Lu,"toExpectedKinds");function Ue(e,t){Ra.set(e,t)}n(Ue,"setUpstreamRequestContext");function Ve(e,t){let r=Hu(e),o=Lu(t);if(!Bu(r.kind,o)){let i=Du[o[0]];throw new E(`${i} request context has not been set`)}return r}n(Ve,"requireUpstreamRequestContext");function ba(e){return b`<p data-gateway-error-code="${e.code}">${e.body}</p>`}n(ba,"renderBrowserResult");var ju="text/html; charset=utf-8",Nu="none";function Gu(e){let t=Ct(e.host);return ve({title:e.title,iconHref:t,styles:Se,headerIcon:St({iconHref:t,fallbackIconHref:bt}),heading:e.title,subhead:"",body:ba({body:e.body,code:e.code??Nu}),footer:""})}n(Gu,"browserResultHtml");function $u(e,t=200){return new Response(Ce(e),{status:t,headers:{"content-type":ju,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n($u,"browserResultResponse");function Ca(e){return $u(Gu(e))}n(Ca,"browserConnectionSuccessResponse");function Tt(e,t){let r=_n(t);return $({host:e,kind:Zu(t),detail:r.body,code:t})}n(Tt,"browserConnectionFailureResponse");function Zu(e){switch(e){case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed"}}n(Zu,"readCallbackFailureBrowserErrorKind");var Fu=["callback_authorization_code","callback_provider_error","callback_invalid"];function Ku(e){return"cause"in e?e.cause:void 0}n(Ku,"readErrorCause");function Wu(e){return e.stack?.split(`
|
|
28
|
+
`).slice(1,4).map(t=>t.trim()).join(" | ")}n(Wu,"readFirstStackFrame");function Sa(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=Wu(r))}n(Sa,"addErrorAttributes");function Or(e){if(!(e instanceof y))return;let t=e.extensionMembers?.[w];return rn(t)?t:void 0}n(Or,"readRuntimeGatewayCode");function Ju(e,t,r){switch(t.kind){case"callback_provider_error":return e.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:t.upstreamServerId,providerError:t.error,...t.errorDescription===void 0?{}:{providerErrorDescription:t.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),A(e,{eventType:x.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:t.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:t.error,errorDescription:t.errorDescription}}),Tt(r,"provider_access_denied");case"callback_invalid":return e.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:t.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),Tt(r,"oauth_state_invalid");case"callback_authorization_code":return t}}n(Ju,"requireAuthorizationCallbackRequest");function Vu(e,t){A(e,{eventType:x.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}n(Vu,"emitCallbackReceivedAnalyticsEvent");function Yu(e,t){A(e,{eventType:x.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}n(Yu,"emitTokenExchangeSucceededAnalyticsEvent");function Xu(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return Ca({host:xe(e.url),title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}n(Xu,"buildSuccessfulCallbackResponse");function Qu(e){let t={detail:e instanceof Error?e.message:void 0};return Sa(t,"error",e),e instanceof Error&&Sa(t,"cause",Ku(e)),t}n(Qu,"buildTokenExchangeFailureAttributes");function el(e){A(e.context,{eventType:x.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:Or(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:Qu(e.error)})}n(el,"emitTokenExchangeFailedAnalyticsEvent");function tl(e,t){let r=Or(t);return Tt(e,nn(r)?r:"upstream_token_exchange_failed")}n(tl,"tokenExchangeFailureResponse");async function Er(e,t){let r=Ve(t,Fu),o=xe(e.url),i=Ju(t,r,o);if(i instanceof Response)return i;Vu(t,i);try{let a=await Ko({request:e,callbackRequest:i});return Yu(t,a),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:a.upstreamServerId,operationId:a.operationId,authProfileId:a.authProfileId,ownerMode:a.ownerMode},"Upstream OAuth token exchange completed; user connection established"),Xu(e,a)}catch(a){let s={event:"upstream_oauth_token_exchange_failed",code:Or(a)??"upstream_token_exchange_failed",upstreamServerId:i.upstreamServerId};return K(s,"error",a),t.log.warn(s,"Upstream OAuth token exchange failed; user shown connection-failure page"),el({context:t,callbackRequest:i,error:a}),tl(o,a)}}n(Er,"callbackHandler");function rl(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}n(rl,"clientMetadataProblemDetail");async function va(e,t){let r=Ve(t,"connect"),o=await Fo({request:e,connectRequest:r});if(A(t,{eventType:x.MCP_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:o.operationId,upstreamServerTitle:o.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:o.authProfileId,operationId:o.operationId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),r.redirect)return Response.redirect(o.authUrl,302);let i=await wt({requestUrl:e.url,owner:o.owner,initiatedBySubjectId:o.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:o.authProfileId,upstreamDisplayName:o.upstreamDisplayName,operationId:o.operationId,subject:"MCP route",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(i,{status:428})}n(va,"connectHandler");async function xa(e,t){let r=Ve(t,"client_metadata");try{let o=To(e.url),i=Oo(o,r.upstreamServerId,r.authProfileId);return Response.json(i)}catch(o){if(!(o instanceof k))throw o;let i=o instanceof Error?o.message:String(o);return t.log.warn({event:"oauth_client_metadata_request_failed",upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:i},"Failed to serve OAuth client metadata document for upstream connection"),ae.notFound(e,t,{code:"not_found",detail:rl(o)})}}n(xa,"oauthClientMetadataHandler");function ie(e){if(typeof e=="string"&&e.length!==0)return e}n(ie,"readOptionalQueryString");function nl(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new E(`Validated path parameter ${t} is missing`);return r}n(nl,"requirePathString");function ol(e){let t=ie(e);return t?rt.parse(t):void 0}n(ol,"readOptionalOperationId");function il(e,t){let r=ie(e);return r?sn.parse(r):it(t,"user-oauth")}n(il,"readOptionalAuthProfileId");function al(e){let t=ol(e);if(!t)throw new y({message:"operationId query parameter is required.",extensionMembers:{[w]:"invalid_request"}});return t}n(al,"readRequiredOperationId");function sl(e){let t=On(ie(e));return t===void 0?{}:{returnTo:t}}n(sl,"readOptionalReturnTo");function cl(e){let t=ie(e.query.error_description);return t===void 0?{}:{errorDescription:t}}n(cl,"readOptionalProviderErrorDescription");function dl(e){let t=N(e.authMode);if(t.connectSupport!=="none")return e;throw new y({message:t.connectUnsupportedDetail??"This upstream does not support browser connection flows.",extensionMembers:{[w]:"invalid_request"}})}n(dl,"requireConnectableRouteAuth");function ul(e,t,r,o){return{kind:"connect",...be(e,t),...o===void 0?{}:{returnTo:o},redirect:r}}n(ul,"buildConnectContextForPrincipal");function ll(e,t,r){let o=ut(t),i=N(e.authMode);if(o.mode!==i.ownerMode)throw new y({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[w]:"oauth_callback_mismatch"}});return{kind:"connect",...e,...t.returnTo===void 0?{}:{returnTo:t.returnTo},owner:o,initiatedBySubjectId:t.initiatedBySubjectId,redirect:r}}n(ll,"buildConnectContextForTicket");async function pl(e,t){let r=dl(Rt(t,al(e.query.operationId))),o=e.query.redirect==="true",i=ie(e.query.browserTicket);if(e.user){if(i)throw new y({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[w]:"invalid_request"}});let s=ct(e.user,e.url);return ul(r,s,o,sl(e.query.returnTo).returnTo)}if(!i)throw new y({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[w]:"authentication_required"}});let a=await Ao(i);if(a.ownerMode!==r.ownerMode||a.upstreamServerId!==r.upstreamServerId||a.authProfileId!==r.authProfileId||a.operationId!==r.operationId)throw new y({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[w]:"oauth_callback_mismatch"}});return await Uo(a),ll(r,a,o)}n(pl,"resolveConnectContext");async function ml(e,t,r){let o=an.parse(nl(e,"connection"));switch(r){case"connect":Ue(t,await pl(e,o));return;case"callback":{let i=ie(e.query.error);if(i){Ue(t,{kind:"callback_provider_error",upstreamServerId:o,error:i,...cl(e)});return}let a=ie(e.query.code),s=ie(e.query.state);if(a&&s){Ue(t,{kind:"callback_authorization_code",upstreamServerId:o,code:a,state:s});return}Ue(t,{kind:"callback_invalid",upstreamServerId:o});return}case"client_metadata":Ue(t,{kind:"client_metadata",upstreamServerId:o,authProfileId:il(e.query.authProfileId,o)});return}}n(ml,"resolveUpstreamRequestInbound");async function fl(e,t,r){try{await ml(e,t,r);return}catch(o){let i=o instanceof y?o.extensionMembers?.[w]:void 0,a=o instanceof Error?o.message:void 0;switch(i){case"invalid_request":case"oauth_callback_mismatch":return ae.badRequest(e,t,{code:i,detail:a});case"authentication_required":return ae.unauthorized(e,t,{code:i,detail:a});default:throw o}}}n(fl,"applyUpstreamRequestContext");function Ot(e,t){return n(async(o,i)=>{let a=await fl(o,i,e);return a||t(o,i)},"wrapped")}n(Ot,"withUpstreamRequestContext");var hl={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function gl(){return new Response(null,{status:204,headers:hl})}n(gl,"buildWellKnownPreflightResponse");function yl(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}n(yl,"withWellKnownCorsHeaders");function qr(e){return async(t,r)=>t.method==="OPTIONS"?gl():yl(await e(t,r))}n(qr,"wrapWellKnownHandler");var Ua=[{routeName:"oauth_as_metadata",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:qr(ua),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:qr(la),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:qr(Pn),corsPolicy:"anything-goes"},{routeName:"oauth_register",path:"/oauth/register",methods:["POST"],handler:pa},{routeName:"oauth_authorize",path:"/oauth/authorize",methods:["GET"],handler:ma},{routeName:"oauth_authorize_scoped",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:fa},{routeName:"oauth_callback",path:"/oauth/callback",methods:["GET"],handler:ha},{routeName:"oauth_dev_login",path:"/oauth/dev-login",methods:["GET"],handler:ga},{routeName:"oauth_setup",path:"/oauth/setup",methods:["GET","POST"],handler:ya},{routeName:"oauth_token",path:"/oauth/token",methods:["POST"],handler:wa},{routeName:"oauth_revoke",path:"/oauth/revoke",methods:["POST"],handler:_a},{routeName:"upstream_client_metadata",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:Ot("client_metadata",xa)},{routeName:"upstream_connect",path:"/auth/connections/:connection/connect",methods:["GET"],handler:Ot("connect",va)},{routeName:"upstream_callback",path:"/auth/connections/:connection/callback",methods:["GET"],handler:Ot("callback",Er)}],wl=Ua.filter(e=>!e.routeName.startsWith("upstream_")),_l=Ua.filter(e=>e.routeName.startsWith("upstream_"));function ka(e){return e?.some(en)??!1}n(ka,"hasMcpOAuthRuntimeConfigPolicy");function Pa(e){return e?.some(t=>mn(t.policyType))??!1}n(Pa,"hasMcpTokenExchangePolicy");function Ta(e){return ka(e)||Pa(e)}n(Ta,"shouldRegisterMcpGatewayInternalRoutes");function Rl(e){gn(fn({routes:e.routes,policies:e.policies}))}n(Rl,"initializeMcpGatewayConnectionRegistry");function bl(e){let t=tn(e.policies);if(!t){let r=[...Qr].map(o=>`\`${o}\``).join(", ");throw new k(`MCP gateway: could not find an MCP authorization policy in policies.json. Add one of [${r}] and reference it on your MCP routes.`)}return t.config}n(bl,"initializeMcpGatewayOAuthRuntimeConfig");function Ia(e,t,r){return async(o,i)=>{r&&Yr(i,r());let a=o.method==="OPTIONS",s=Date.now();a||i.log.info({event:`${e}_received`,method:o.method},`MCP gateway: ${e} received`);let c=await t(o,i);return a||i.log.info({event:`${e}_responded`,status:c.status,durationMs:Date.now()-s},`MCP gateway: ${e} responded`),c}}n(Ia,"wrapInternalHandler");function Aa(e,t,r){e.addPluginRoute({path:t.path,methods:t.methods,handler:r,processors:[jr],corsPolicy:t.corsPolicy??"none"})}n(Aa,"addInternalRoute");function Oa(e,t){Rl(t);let r=ka(t.policies),o=Pa(t.policies),i,a=n(()=>(i===void 0&&(i=bl(t)),i),"readOAuthConfig");if(r)for(let s of wl)Aa(e,s,Ia(s.routeName,s.handler,a));if(o)for(let s of _l)Aa(e,s,Ia(s.routeName,s.handler))}n(Oa,"registerMcpGatewayInternalRoutes");function Ea(e){hn(e)}n(Ea,"configureLazyMcpGatewayState");var Mr=class extends Br{static{n(this,"McpGatewayPlugin")}registerRoutes(t){let r=t.parsedRouteData;if(!r||!Ta(r.policies))return;let o={routes:r.routes,policies:r.policies};Ea(o),Oa(t.router,o)}};var Cl={Allow:"POST"};async function Sl(e,t){return e.method==="GET"?ae.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},Cl):Jr(e,t)}n(Sl,"McpProxyHandler");export{Ha as McpAuth0OAuthInboundPolicy,Gt as McpCapabilityFilterInboundPolicy,Mr as McpGatewayPlugin,Da as McpOAuthInboundPolicy,Sl as McpProxyHandler,ur as McpTokenExchangeInboundPolicy};
|
|
33
29
|
//# sourceMappingURL=index.js.map
|