@zuplo/runtime 6.70.49 → 6.70.50

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.
@@ -1,30 +0,0 @@
1
-
2
- /*---------------------------------------------------------------------------------------------
3
- * Copyright (c) Zuplo, Inc. All rights reserved.
4
- *
5
- * This software and associated documentation files (the "Software") is intended to be used
6
- * only by Zuplo customers solely to develop and test applications that will be deployed
7
- * to Zuplo hosted services. You and others in your organization may use these files on your
8
- * Development Devices solely for the above stated purpose.
9
- *
10
- * Outside of uses stated above, no license is granted for any other purpose including
11
- * without limitation the rights to use, copy, modify, merge, publish, distribute,
12
- * sublicense, host, and/or sell copies of the Software.
13
- *
14
- * The software may include third party components with separate legal notices or governed by
15
- * other agreements, as described in licenses either embedded in or accompanying the Software.
16
- *
17
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
18
- * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
19
- * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
20
- * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21
- * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22
- * DEALINGS IN THE SOFTWARE.
23
- *--------------------------------------------------------------------------------------------*/
24
-
25
- import{$ as C,A as pt,B as De,K as yo,L as a,N as g,O as I,P as bo,R as _,S as h,T as p,U as P,V as R,W as dt,X as mt,Y as S,Z as M,_ as d,a as pe,aa as Co,b as So,ba as lt,ea as n,fa as E,ga as wo,j as ze,m as Ro,s as de,x as ut}from"./chunk-J7JE2DD5.js";import{d as me}from"./chunk-JRXZBVXH.js";import{a as U}from"./chunk-4SACVMDH.js";import{$ as ct,a as r,aa as A,ba as f,ca as qe}from"./chunk-ZIKV2LUM.js";E();var Wr=new Set(["localhost","::1"]);function te(e){return e.replace(/^\[(.*)\]$/,"$1").replace(/\.+$/,"").toLowerCase()}r(te,"normalizeHostname");function j(e){let t=te(e.hostname);return e.protocol==="http:"&&(Wr.has(t)||/^127(?:\.\d{1,3}){3}$/.test(t))}r(j,"isLoopbackHttpUrl");var Ao=new De("gateway-route");function _o(e,t){Ao.set(e,t)}r(_o,"setGatewayRouteContext");function Le(e){return Ao.get(e)}r(Le,"readGatewayRouteContext");var xo=new De("mcp-oauth-runtime-config");function le(e,t){xo.set(e,t)}r(le,"setMcpOAuthRuntimeConfig");function zo(e){let t=xo.get(e);if(!t)throw new f("MCP gateway OAuth config has not been set on the request context. An MCP OAuth inbound policy must run before this handler, or the internal OAuth route wrapper must have populated the context.");return t}r(zo,"requireMcpOAuthRuntimeConfig");var Ie=n.string().trim().min(1),Kr=60,Yr=24*60*60,Jr=15*Kr,Xr=10*365*Yr,Te={accessTokenTtlSeconds:Jr,refreshTokenTtlSeconds:Xr,cimdEnabled:!0},Qr=n.object({issuer:n.url(),jwksUrl:n.url(),audience:Ie.optional()}),ei=n.object({url:n.url(),tokenUrl:n.url().optional(),clientId:Ie.optional(),clientSecret:Ie.optional(),scope:Ie.default("openid profile email"),audience:Ie.optional(),remoteTimeoutMs:n.coerce.number().int().positive().default(1e4),stateTtlSeconds:n.coerce.number().int().positive().default(900),sessionTtlSeconds:n.coerce.number().int().positive().default(28800)}).strict().superRefine((e,t)=>{if(!To(e.url))for(let o of["tokenUrl","clientId","clientSecret"])e[o]||t.addIssue({code:n.ZodIssueCode.custom,message:`${o} is required for federated browser login`,path:[o]})}),ti=n.object({accessTokenTtlSeconds:n.coerce.number().int().positive().default(Te.accessTokenTtlSeconds),refreshTokenTtlSeconds:n.coerce.number().int().positive().default(Te.refreshTokenTtlSeconds),cimdEnabled:n.boolean().default(Te.cimdEnabled)}).strict().default(Te),ht=n.object({oidc:Qr,browserLogin:ei,gateway:ti.optional().default(Te)}).strict();function Io(e){return To(e.browserLogin.url)?"local_dev":"federated_oidc"}r(Io,"readBrowserLoginKind");function To(e){let t;try{t=new URL(e)}catch{return!1}return j(t)&&t.pathname==="/oauth/dev-login"}r(To,"isLoopbackDevLoginUrl");function ft(e){return ht.parse(e)}r(ft,"parseMcpOAuthRuntimeConfig");function Ge(){let e;try{e=ut()}catch(t){throw new ct("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 zo(e)}r(Ge,"getGatewayOAuthConfig");E();function ke(e,t,o){let i=e.safeParse(t);if(i.success)return i.data;throw new f(`${o} is misconfigured. Validation failed:
26
- ${oi(i.error)}`,{cause:i.error})}r(ke,"parseConfigOrThrow");function oi(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
27
- `)}r(oi,"formatZodIssues");var ni=n.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.'}),ri=n.object({auth0Domain:ni,audience:n.string().trim().min(1).optional(),clientId:n.string({error:"clientId is required and must be a string"}).trim().min(1,"clientId is required (commonly set via $env(AUTH0_CLIENT_ID))"),clientSecret:n.string({error:"clientSecret is required and must be a string"}).trim().min(1,"clientSecret is required (commonly set via $env(AUTH0_CLIENT_SECRET))"),scope:n.string().trim().min(1).optional(),gateway:n.object({accessTokenTtlSeconds:n.number().int().positive().optional(),refreshTokenTtlSeconds:n.number().int().positive().optional(),cimdEnabled:n.boolean().optional()}).strict().optional(),browserLoginOverrides:n.object({remoteTimeoutMs:n.number().int().positive().optional(),stateTtlSeconds:n.number().int().positive().optional(),sessionTtlSeconds:n.number().int().positive().optional()}).strict().optional()}).strict(),ii=n.string({error:"clientId is required and must be a string"}).trim().min(1,"clientId is required (commonly set via $env(WORKOS_CLIENT_ID))").regex(/^client_[A-Za-z0-9]{20,40}$/,{message:'clientId must be a WorkOS client ID like "client_01KC6057N3C66XJAXZ65YHAC72"; do not pass the WorkOS issuer URL or API hostname'}),ai=n.object({clientId:ii,clientSecret:n.string({error:"clientSecret is required and must be a string"}).trim().min(1,"clientSecret is required (commonly set via $env(WORKOS_CLIENT_SECRET))"),scope:n.string().trim().min(1).optional(),gateway:n.object({accessTokenTtlSeconds:n.number().int().positive().optional(),refreshTokenTtlSeconds:n.number().int().positive().optional(),cimdEnabled:n.boolean().optional()}).strict().optional(),browserLoginOverrides:n.object({remoteTimeoutMs:n.number().int().positive().optional(),stateTtlSeconds:n.number().int().positive().optional(),sessionTtlSeconds:n.number().int().positive().optional()}).strict().optional()}).strict();function gt(e,t){return ke(ri,e,`MCP Auth0 OAuth policy "${t}"`)}r(gt,"parseAuth0ProviderOptions");function ko(e,t="mcp-auth0-oauth-inbound"){let o=gt(e,t);return Rt(o,t)}r(ko,"auth0ProviderOptionsToMcpOAuthRuntimeConfig");function St(e,t){return ke(ai,e,`MCP WorkOS OAuth policy "${t}"`)}r(St,"parseWorkosProviderOptions");function Oo(e,t="mcp-workos-oauth-inbound"){let o=St(e,t);return yt(o,t)}r(Oo,"workosProviderOptionsToMcpOAuthRuntimeConfig");function Rt(e,t){let o=`https://${e.auth0Domain}/`,i=`https://${e.auth0Domain}/.well-known/jwks.json`,s=`https://${e.auth0Domain}/authorize`,u=`https://${e.auth0Domain}/oauth/token`;try{return ft({oidc:{issuer:o,jwksUrl:i,...e.audience===void 0?{}:{audience:e.audience}},browserLogin:{url:s,tokenUrl:u,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(c){let l=c instanceof Error?` Validation failed: ${c.message}`:"";throw new f(`MCP Auth0 OAuth policy "${t}" is misconfigured. Check the policy options in policies.json.${l}`,c instanceof Error?{cause:c}:void 0)}}r(Rt,"buildAuth0McpOAuthRuntimeConfig");function yt(e,t){let o=`https://api.workos.com/user_management/${e.clientId}`,i=`https://api.workos.com/sso/jwks/${e.clientId}`;try{return ft({oidc:{issuer:o,jwksUrl:i},browserLogin:{url:"https://api.workos.com/user_management/authorize",tokenUrl:"https://api.workos.com/user_management/authenticate",clientId:e.clientId,clientSecret:e.clientSecret,scope:e.scope??"openid profile email",...e.browserLoginOverrides??{}},gateway:e.gateway})}catch(s){let u=s instanceof Error?` Validation failed: ${s.message}`:"";throw new f(`MCP WorkOS OAuth policy "${t}" is misconfigured. Check the policy options in policies.json.${u}`,s instanceof Error?{cause:s}:void 0)}}r(yt,"buildWorkosMcpOAuthRuntimeConfig");var vo=class extends de{static{r(this,"McpAuth0OAuthInboundPolicy")}#t;constructor(t,o){let i=si(t,o);super(i,o),this.#t=Rt(i,o)}async handler(t,o){return pe("policy.inbound.mcp-auth0-oauth"),le(o,this.#t),oe(t,o)}};function si(e,t){return gt(e,t)}r(si,"parseAuth0OAuthOptions");function Po(e,t="mcp-auth0-oauth-inbound"){return ko(e,t)}r(Po,"auth0OptionsToMcpOAuthRuntimeConfig");var Eo=class extends de{static{r(this,"McpWorkosOAuthInboundPolicy")}#t;constructor(t,o){let i=ci(t,o);super(i,o),this.#t=yt(i,o)}async handler(t,o){return pe("policy.inbound.mcp-workos-oauth"),le(o,this.#t),oe(t,o)}};function ci(e,t){return St(e,t)}r(ci,"parseWorkosOAuthOptions");function Uo(e,t="mcp-workos-oauth-inbound"){return Oo(e,t)}r(Uo,"workosOptionsToMcpOAuthRuntimeConfig");var ui=["mcp-oauth-inbound","mcp-auth0-oauth-inbound","mcp-workos-oauth-inbound"],bt={"mcp-oauth-inbound":"McpOAuthInboundPolicy","mcp-auth0-oauth-inbound":"McpAuth0OAuthInboundPolicy","mcp-workos-oauth-inbound":"McpWorkosOAuthInboundPolicy"};function pi(e,t,o){switch(e){case"mcp-oauth-inbound":return Ct(o,t);case"mcp-auth0-oauth-inbound":return Po(o,t);case"mcp-workos-oauth-inbound":return Uo(o,t);default:return}}r(pi,"parseMcpOAuthPolicyConfig");function Mo(e){return e!==void 0&&ui.some(t=>t===e)}r(Mo,"isMcpOAuthInboundPolicyType");function di(e){switch(e.policyType){case"mcp-oauth-inbound":return e.handler.export===bt["mcp-oauth-inbound"];case"mcp-auth0-oauth-inbound":return e.handler.export===bt["mcp-auth0-oauth-inbound"];case"mcp-workos-oauth-inbound":return e.handler.export===bt["mcp-workos-oauth-inbound"];default:return!1}}r(di,"isMcpOAuthRuntimeConfigPolicy");function qp(e){if(!e)return;let t=e.filter(di);if(t.length>1){let s=t.map(u=>`"${u.name}" (${u.policyType})`).join(", ");throw new f(`MCP gateway found multiple OAuth policies in policies.json: ${s}. Use exactly one MCP OAuth policy for the gateway so internal OAuth routes resolve a single runtime config.`)}let o=t[0];if(!o)return;let i=pi(o.policyType,o.name,o.handler.options);if(!i)throw new f(`MCP gateway: policy '${o.name}' has unsupported MCP OAuth policy type '${o.policyType}'.`);return{policyName:o.name,config:i}}r(qp,"resolveMcpOAuthRuntimeConfigFromPolicies");var w="gatewayCode",Np="upstreamErrorContentType",Bp="upstreamErrorHtml",$p="upstreamErrorStatus",Fp="upstreamErrorUrl",he={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_oauth_discovery_unavailable:{code:"upstream_oauth_discovery_unavailable",status:400,title:"Upstream OAuth discovery unavailable",publicDetail:"There was an error connecting to this service. This may require provider or administrator setup.",callbackFailure:!0,oauthError:"invalid_request"},upstream_provider_access_denied:{code:"upstream_provider_access_denied",status:400,title:"Upstream provider access denied",publicDetail:"There was an error connecting to this service. This may require provider or administrator setup.",callbackFailure:!0,oauthError:"invalid_request"},upstream_client_registration_required:{code:"upstream_client_registration_required",status:400,title:"Upstream OAuth client registration required",publicDetail:"There was an error connecting to this service. This may require provider or administrator setup.",callbackFailure:!0,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."}}},Ne={...he.runtime,...he.config,...he.downstream_auth,...he.downstream_oauth,...he.upstream_auth,...he.upstream_mcp};function ne(e){return typeof e=="string"&&Object.hasOwn(Ne,e)}r(ne,"isGatewayProblemCode");function Zp(e){return ne(e)&&re(e).callbackFailure===!0}r(Zp,"isGatewayCallbackFailureCode");function re(e){return Ne[e]}r(re,"readGatewayProblemDefinition");function Ho(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"}}r(Ho,"readDefaultGatewayProblemCodeForStatus");var mi=/^\$\{env\.([A-Za-z_][A-Za-z0-9_]*)\}$/;function jo(e,t){let o;try{o=new URL(e)}catch{throw new f(`${t} must be an absolute URL.`)}if(o.protocol!=="https:"&&o.protocol!=="http:")throw new f(`${t} must be an HTTP(S) URL.`);return e}r(jo,"assertHttpUrl");function qo(e){return e.options??{}}r(qo,"readHandlerOptions");function li(e){let t=mi.exec(e);if(t){let o=t[1],i=me[o];if(typeof i!="string"||i==="")throw new f(`MCP route handler rewritePattern references env.${o}, but that environment variable is not set.`);return jo(i,`env.${o}`)}if(e.includes("${"))throw new f("MCP token exchange requires a static route handler rewritePattern. Dynamic request-based rewrite patterns are not supported for MCP upstream OAuth.");return jo(e,"MCP route handler rewritePattern")}r(li,"readRewritePatternUrl");function wt(e){let t=qo(e);if(typeof t.rewritePattern=="string"&&t.rewritePattern!=="")return li(t.rewritePattern);throw new f("MCP route must configure handler.options.rewritePattern.")}r(wt,"readMcpRouteUpstreamUrl");function Jp(e){let t=qo(e.handler),o=new URL(wt(e.handler));if(t.forwardSearch!==!1)for(let[s,u]of new URL(e.request.url).searchParams)o.searchParams.append(s,u);let i={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:o.toString(),init:i}}r(Jp,"buildMcpRouteUpstreamFetch");E();var hi=["shared-oauth","user-oauth"],fi=["none","client_secret_basic","client_secret_post"],q=n.string().min(1).brand(),D=n.string().min(1),B=n.string().min(1).brand(),At=n.enum(hi),_t=n.enum(fi);E();var Do="2025-11-25";var gi="io.modelcontextprotocol/related-task",Fe="2.0",z=Co(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Lo=R([a(),g().int()]),Go=a(),nd=P({ttl:g().optional(),pollInterval:g().optional()}),Si=p({ttl:g().optional()}),Ri=p({taskId:a()}),It=P({progressToken:Lo.optional(),[gi]:Ri.optional()}),H=p({_meta:It.optional()}),Ze=H.extend({task:Si.optional()});var O=p({method:a(),params:H.loose().optional()}),L=p({_meta:It.optional()}),G=p({method:a(),params:L.loose().optional()}),v=P({_meta:It.optional()}),We=R([a(),g().int()]),yi=p({jsonrpc:d(Fe),id:We,...O.shape}).strict();var bi=p({jsonrpc:d(Fe),...G.shape}).strict();var No=p({jsonrpc:d(Fe),id:We,result:v}).strict();var Be;(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"})(Be||(Be={}));var Bo=p({jsonrpc:d(Fe),id:We.optional(),error:p({code:g().int(),message:a(),data:_().optional()})}).strict();var rd=R([yi,bi,No,Bo]),id=R([No,Bo]),$o=v.strict(),Ci=L.extend({requestId:We.optional(),reason:a().optional()}),Fo=G.extend({method:d("notifications/cancelled"),params:Ci}),wi=p({src:a(),mimeType:a().optional(),sizes:h(a()).optional(),theme:M(["light","dark"]).optional()}),Oe=p({icons:h(wi).optional()}),fe=p({name:a(),title:a().optional()}),ge=fe.extend({...fe.shape,...Oe.shape,version:a(),websiteUrl:a().optional(),description:a().optional()}),Ai=mt(p({applyDefaults:I().optional()}),S(a(),_())),_i=lt(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,mt(p({form:Ai.optional(),url:z.optional()}),S(a(),_()).optional())),xi=P({list:z.optional(),cancel:z.optional(),requests:P({sampling:P({createMessage:z.optional()}).optional(),elicitation:P({create:z.optional()}).optional()}).optional()}),zi=P({list:z.optional(),cancel:z.optional(),requests:P({tools:P({call:z.optional()}).optional()}).optional()}),Ii=p({experimental:S(a(),z).optional(),sampling:p({context:z.optional(),tools:z.optional()}).optional(),elicitation:_i.optional(),roots:p({listChanged:I().optional()}).optional(),tasks:xi.optional(),extensions:S(a(),z).optional()}),Ti=H.extend({protocolVersion:a(),capabilities:Ii,clientInfo:ge}),ki=O.extend({method:d("initialize"),params:Ti});var Oi=p({experimental:S(a(),z).optional(),logging:z.optional(),completions:z.optional(),prompts:p({listChanged:I().optional()}).optional(),resources:p({subscribe:I().optional(),listChanged:I().optional()}).optional(),tools:p({listChanged:I().optional()}).optional(),tasks:zi.optional(),extensions:S(a(),z).optional()}),vi=v.extend({protocolVersion:a(),capabilities:Oi,serverInfo:ge,instructions:a().optional()}),Pi=G.extend({method:d("notifications/initialized"),params:L.optional()});var Zo=O.extend({method:d("ping"),params:H.optional()}),Ei=p({progress:g(),total:C(g()),message:C(a())}),Ui=p({...L.shape,...Ei.shape,progressToken:Lo}),Wo=G.extend({method:d("notifications/progress"),params:Ui}),Mi=H.extend({cursor:Go.optional()}),ve=O.extend({params:Mi.optional()}),Pe=v.extend({nextCursor:Go.optional()}),Hi=M(["working","input_required","completed","failed","cancelled"]),Ee=p({taskId:a(),status:Hi,ttl:R([g(),bo()]),createdAt:a(),lastUpdatedAt:a(),pollInterval:C(g()),statusMessage:C(a())}),Vo=v.extend({task:Ee}),ji=L.merge(Ee),Ko=G.extend({method:d("notifications/tasks/status"),params:ji}),Yo=O.extend({method:d("tasks/get"),params:H.extend({taskId:a()})}),Jo=v.merge(Ee),Xo=O.extend({method:d("tasks/result"),params:H.extend({taskId:a()})}),ad=v.loose(),Qo=ve.extend({method:d("tasks/list")}),en=Pe.extend({tasks:h(Ee)}),tn=O.extend({method:d("tasks/cancel"),params:H.extend({taskId:a()})}),sd=v.merge(Ee),on=p({uri:a(),mimeType:C(a()),_meta:S(a(),_()).optional()}),nn=on.extend({text:a()}),Tt=a().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),rn=on.extend({blob:Tt}),Ue=M(["user","assistant"]),Se=p({audience:h(Ue).optional(),priority:g().min(0).max(1).optional(),lastModified:yo.datetime({offset:!0}).optional()}),an=p({...fe.shape,...Oe.shape,uri:a(),description:C(a()),mimeType:C(a()),size:C(g()),annotations:Se.optional(),_meta:C(P({}))}),qi=p({...fe.shape,...Oe.shape,uriTemplate:a(),description:C(a()),mimeType:C(a()),annotations:Se.optional(),_meta:C(P({}))}),Di=ve.extend({method:d("resources/list")}),Li=Pe.extend({resources:h(an)}),Gi=ve.extend({method:d("resources/templates/list")}),Ni=Pe.extend({resourceTemplates:h(qi)}),kt=H.extend({uri:a()}),Bi=kt,$i=O.extend({method:d("resources/read"),params:Bi}),Fi=v.extend({contents:h(R([nn,rn]))}),Zi=G.extend({method:d("notifications/resources/list_changed"),params:L.optional()}),Wi=kt,Vi=O.extend({method:d("resources/subscribe"),params:Wi}),Ki=kt,Yi=O.extend({method:d("resources/unsubscribe"),params:Ki}),Ji=L.extend({uri:a()}),Xi=G.extend({method:d("notifications/resources/updated"),params:Ji}),Qi=p({name:a(),description:C(a()),required:C(I())}),ea=p({...fe.shape,...Oe.shape,description:C(a()),arguments:C(h(Qi)),_meta:C(P({}))}),ta=ve.extend({method:d("prompts/list")}),oa=Pe.extend({prompts:h(ea)}),na=H.extend({name:a(),arguments:S(a(),a()).optional()}),ra=O.extend({method:d("prompts/get"),params:na}),Ot=p({type:d("text"),text:a(),annotations:Se.optional(),_meta:S(a(),_()).optional()}),vt=p({type:d("image"),data:Tt,mimeType:a(),annotations:Se.optional(),_meta:S(a(),_()).optional()}),Pt=p({type:d("audio"),data:Tt,mimeType:a(),annotations:Se.optional(),_meta:S(a(),_()).optional()}),ia=p({type:d("tool_use"),name:a(),id:a(),input:S(a(),_()),_meta:S(a(),_()).optional()}),aa=p({type:d("resource"),resource:R([nn,rn]),annotations:Se.optional(),_meta:S(a(),_()).optional()}),sa=an.extend({type:d("resource_link")}),Et=R([Ot,vt,Pt,sa,aa]),ca=p({role:Ue,content:Et}),ua=v.extend({description:a().optional(),messages:h(ca)}),pa=G.extend({method:d("notifications/prompts/list_changed"),params:L.optional()}),da=p({title:a().optional(),readOnlyHint:I().optional(),destructiveHint:I().optional(),idempotentHint:I().optional(),openWorldHint:I().optional()}),ma=p({taskSupport:M(["required","optional","forbidden"]).optional()}),sn=p({...fe.shape,...Oe.shape,description:a().optional(),inputSchema:p({type:d("object"),properties:S(a(),z).optional(),required:h(a()).optional()}).catchall(_()),outputSchema:p({type:d("object"),properties:S(a(),z).optional(),required:h(a()).optional()}).catchall(_()).optional(),annotations:da.optional(),execution:ma.optional(),_meta:S(a(),_()).optional()}),la=ve.extend({method:d("tools/list")}),ha=Pe.extend({tools:h(sn)}),cn=v.extend({content:h(Et).default([]),structuredContent:S(a(),_()).optional(),isError:I().optional()}),cd=cn.or(v.extend({toolResult:_()})),fa=Ze.extend({name:a(),arguments:S(a(),_()).optional()}),ga=O.extend({method:d("tools/call"),params:fa}),Sa=G.extend({method:d("notifications/tools/list_changed"),params:L.optional()}),ud=p({autoRefresh:I().default(!0),debounceMs:g().int().nonnegative().default(300)}),un=M(["debug","info","notice","warning","error","critical","alert","emergency"]),Ra=H.extend({level:un}),ya=O.extend({method:d("logging/setLevel"),params:Ra}),ba=L.extend({level:un,logger:a().optional(),data:_()}),Ca=G.extend({method:d("notifications/message"),params:ba}),wa=p({name:a().optional()}),Aa=p({hints:h(wa).optional(),costPriority:g().min(0).max(1).optional(),speedPriority:g().min(0).max(1).optional(),intelligencePriority:g().min(0).max(1).optional()}),_a=p({mode:M(["auto","required","none"]).optional()}),xa=p({type:d("tool_result"),toolUseId:a().describe("The unique identifier for the corresponding tool call."),content:h(Et).default([]),structuredContent:p({}).loose().optional(),isError:I().optional(),_meta:S(a(),_()).optional()}),za=dt("type",[Ot,vt,Pt]),$e=dt("type",[Ot,vt,Pt,ia,xa]),Ia=p({role:Ue,content:R([$e,h($e)]),_meta:S(a(),_()).optional()}),Ta=Ze.extend({messages:h(Ia),modelPreferences:Aa.optional(),systemPrompt:a().optional(),includeContext:M(["none","thisServer","allServers"]).optional(),temperature:g().optional(),maxTokens:g().int(),stopSequences:h(a()).optional(),metadata:z.optional(),tools:h(sn).optional(),toolChoice:_a.optional()}),ka=O.extend({method:d("sampling/createMessage"),params:Ta}),Oa=v.extend({model:a(),stopReason:C(M(["endTurn","stopSequence","maxTokens"]).or(a())),role:Ue,content:za}),va=v.extend({model:a(),stopReason:C(M(["endTurn","stopSequence","maxTokens","toolUse"]).or(a())),role:Ue,content:R([$e,h($e)])}),Pa=p({type:d("boolean"),title:a().optional(),description:a().optional(),default:I().optional()}),Ea=p({type:d("string"),title:a().optional(),description:a().optional(),minLength:g().optional(),maxLength:g().optional(),format:M(["email","uri","date","date-time"]).optional(),default:a().optional()}),Ua=p({type:M(["number","integer"]),title:a().optional(),description:a().optional(),minimum:g().optional(),maximum:g().optional(),default:g().optional()}),Ma=p({type:d("string"),title:a().optional(),description:a().optional(),enum:h(a()),default:a().optional()}),Ha=p({type:d("string"),title:a().optional(),description:a().optional(),oneOf:h(p({const:a(),title:a()})),default:a().optional()}),ja=p({type:d("string"),title:a().optional(),description:a().optional(),enum:h(a()),enumNames:h(a()).optional(),default:a().optional()}),qa=R([Ma,Ha]),Da=p({type:d("array"),title:a().optional(),description:a().optional(),minItems:g().optional(),maxItems:g().optional(),items:p({type:d("string"),enum:h(a())}),default:h(a()).optional()}),La=p({type:d("array"),title:a().optional(),description:a().optional(),minItems:g().optional(),maxItems:g().optional(),items:p({anyOf:h(p({const:a(),title:a()}))}),default:h(a()).optional()}),Ga=R([Da,La]),Na=R([ja,qa,Ga]),Ba=R([Na,Pa,Ea,Ua]),$a=Ze.extend({mode:d("form").optional(),message:a(),requestedSchema:p({type:d("object"),properties:S(a(),Ba),required:h(a()).optional()})}),Fa=Ze.extend({mode:d("url"),message:a(),elicitationId:a(),url:a().url()}),Za=R([$a,Fa]),Wa=O.extend({method:d("elicitation/create"),params:Za}),Va=L.extend({elicitationId:a()}),Ka=G.extend({method:d("notifications/elicitation/complete"),params:Va}),Ya=v.extend({action:M(["accept","decline","cancel"]),content:lt(e=>e===null?void 0:e,S(a(),R([a(),g(),I(),h(a())])).optional())}),Ja=p({type:d("ref/resource"),uri:a()});var Xa=p({type:d("ref/prompt"),name:a()}),Qa=H.extend({ref:R([Xa,Ja]),argument:p({name:a(),value:a()}),context:p({arguments:S(a(),a()).optional()}).optional()}),es=O.extend({method:d("completion/complete"),params:Qa});var ts=v.extend({completion:P({values:h(a()).max(100),total:C(g().int()),hasMore:C(I())})}),os=p({uri:a().startsWith("file://"),name:a().optional(),_meta:S(a(),_()).optional()}),ns=O.extend({method:d("roots/list"),params:H.optional()}),rs=v.extend({roots:h(os)}),is=G.extend({method:d("notifications/roots/list_changed"),params:L.optional()}),pd=R([Zo,ki,es,ya,ra,ta,Di,Gi,$i,Vi,Yi,ga,la,Yo,Xo,Qo,tn]),dd=R([Fo,Wo,Pi,is,Ko]),md=R([$o,Oa,va,Ya,rs,Jo,en,Vo]),ld=R([Zo,ka,Wa,ns,Yo,Xo,Qo,tn]),hd=R([Fo,Wo,Ca,Xi,Zi,Sa,pa,Ko,Ka]),fd=R([$o,vi,ts,ua,oa,Li,Ni,Fi,cn,ha,Jo,en,Vo]),xt=class e extends Error{static{r(this,"McpError")}constructor(t,o,i){super(`MCP error ${t}: ${o}`),this.code=t,this.data=i,this.name="McpError"}static fromError(t,o,i){if(t===Be.UrlElicitationRequired&&i){let s=i;if(s.elicitations)return new zt(s.elicitations,o)}return new e(t,o,i)}},zt=class extends xt{static{r(this,"UrlElicitationRequiredError")}constructor(t,o=`URL elicitation${t.length>1?"s":""} required`){super(Be.UrlElicitationRequired,o,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};E();var dn=q,as=n.object({mode:n.literal("auto")}).strict(),ss=n.object({mode:n.literal("manual"),clientId:n.string().trim().min(1),clientSecret:n.string().min(1).optional(),tokenEndpointAuthMethod:_t.default("client_secret_basic")}).strict().superRefine((e,t)=>{e.tokenEndpointAuthMethod!=="none"&&!e.clientSecret&&t.addIssue({code:n.ZodIssueCode.custom,message:`${e.tokenEndpointAuthMethod} requires clientSecret`,path:["clientSecret"]})}),mn=n.discriminatedUnion("mode",[as,ss]),cs=mn.default({mode:"auto"}),us=n.object({scopes:n.array(n.string().min(1)).default([]),scopeDelimiter:n.string().min(1).default(" "),clientRegistration:cs}).strict(),pn=us.extend({redirectPath:n.string().startsWith("/auth/connections/")}).strict(),ps=n.discriminatedUnion("mode",[n.object({mode:n.literal("shared-oauth"),oauth:pn}).strict(),n.object({mode:n.literal("user-oauth"),oauth:pn}).strict()]),ds=n.object({baseUrl:n.url(),resourceMetadataUrl:n.url()}).strict(),wd=n.object({displayName:n.string().min(1),description:n.string().min(1).optional(),serverInfo:ge.optional(),transport:ds}).strict(),ms=n.object({id:dn,displayName:n.string().min(1),description:n.string().min(1).optional(),serverInfo:ge.optional(),protectedResourceMetadataUrl:n.url().optional(),authMode:At,authConfig:ps}).strict().refine(e=>e.authMode===e.authConfig.mode,{message:"authMode must match authConfig.mode",path:["authConfig","mode"]}),ls={id:dn.optional(),displayName:n.string().min(1),summary:n.string().min(1).optional(),serverInfo:ge.optional(),protectedResourceMetadataUrl:n.url().optional()},hs=n.object({...ls,authMode:At,scopes:n.array(n.string().min(1)).default([]),scopeDelimiter:n.string().min(1).default(" "),clientRegistration:mn.optional(),clientId:n.string().trim().min(1).optional(),clientSecret:n.string().min(1).optional(),tokenEndpointAuthMethod:_t.optional()}).strict();function fs(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
28
- `)}r(fs,"formatZodIssues");function gs(e){let t="mcp-token-exchange-";if(!e.startsWith(t))throw new f(`MCP token exchange policy ${e} must use the ${t}{upstream-id} naming convention when id is omitted.`);return q.parse(e.slice(t.length))}r(gs,"inferUpstreamConnectionIdFromPolicyName");function ln(e){let t=new URL(e),o=t.pathname==="/"?"":t.pathname;return`${t.origin}/.well-known/oauth-protected-resource${o}`}r(ln,"buildDefaultProtectedResourceMetadataUrl");function hn(e,t){return B.parse(`${e}:${t}`)}r(hn,"buildUpstreamAuthProfileId");function Ss(e,t){let o=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:o}}}r(Ss,"resolveAuthConfig");function fn(e,t){try{let o=hs.parse(e),i=o.id??(t===void 0?void 0:gs(t));if(i===void 0)throw new f("MCP token exchange policy options must include id when policy name is unavailable.");return ms.parse({id:i,displayName:o.displayName,...o.summary===void 0?{}:{description:o.summary},...o.serverInfo===void 0?{}:{serverInfo:o.serverInfo},...o.protectedResourceMetadataUrl===void 0?{}:{protectedResourceMetadataUrl:o.protectedResourceMetadataUrl},authMode:o.authMode,authConfig:Ss(o,i)})}catch(o){if(o instanceof n.ZodError){let i=t===void 0?"MCP token exchange policy":`Policy "${t}"`;throw new f(`${i} is misconfigured. Missing/invalid options in policies.json:
29
- ${fs(o)}`,{cause:o})}throw o}}r(fn,"parseUpstreamTokenExchangePolicyOptions");function Ad(e){return e.mode==="shared-oauth"||e.mode==="user-oauth"}r(Ad,"isUpstreamOAuthAuthConfig");var Rs="mcp-token-exchange-inbound";function gn(e,t,o){let i=new f(t,o===void 0?void 0:{cause:o});return i.extensionMembers={[w]:e},i}r(gn,"configurationProblem");function Sn(e){return e===Rs}r(Sn,"isMcpTokenExchangePolicyType");function ys(e){let t=hn(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??ln(e.mcpUrl),authMode:e.connection.authMode,authProfileId:t,authConfig:e.connection.authConfig}}r(ys,"buildRegisteredConnection");function bs(e){let t=new Map;for(let o of e){if(t.has(o.name))throw new f(`Duplicate policy name ${o.name} in policies.json.`);t.set(o.name,{name:o.name,policyType:o.policyType,handler:{options:o.handler.options}})}return t}r(bs,"buildPolicyMap");function Cs(e){if(typeof e.raw!="function")throw new f(`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 f(`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 D.parse(t.operationId)}r(Cs,"readOperationId");function ws(e){let t=[];for(let o of e.route.policies?.inbound??[]){let i=e.policyByName.get(o);i&&Sn(i.policyType)&&t.push(i)}if(t.length>1)throw new f(`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],wt(e.route.handler))}r(ws,"readRouteUpstreamConnection");function As(e){let t=new Map,o=new Map,i=new Map,s=new Set;function u(c,l){let y=i.get(c.name);if(y)return y;let x=fn(c.handler.options,c.name);if(s.has(x.id))throw new f(`Duplicate upstream MCP connection id ${x.id} in policies.json.`);s.add(x.id);let $=ys({policyName:c.name,connection:x,mcpUrl:l});return i.set(c.name,$),$}r(u,"readConnectionForPolicy");for(let c of e.routes){let l=c.policies?.inbound??[];if(l.length===0||!l.map(K=>e.policyByName.get(K)).filter(K=>K!==void 0).some(K=>Mo(K.policyType)||Sn(K.policyType)))continue;let x=Cs(c);if(t.has(x))throw new f(`Duplicate MCP route operationId ${x} across routes.`);if(o.has(c.path))throw new f(`Duplicate MCP route path ${c.path} across routes.`);let $=ws({route:c,policyByName:e.policyByName,readConnectionForPolicy:u}),Ae={operationId:x,routePath:c.path,...$===void 0?{}:{connection:$}};t.set(x,Ae),o.set(c.path,Ae)}return{byOperationId:t,byRoutePath:o,connectionsByPolicyName:i}}r(As,"buildMcpRoutes");function _s(e){let t=bs(e.policies),{byOperationId:o,byRoutePath:i,connectionsByPolicyName:s}=As({routes:e.routes,policyByName:t}),u=new Map;for(let c of s.values())u.set(c.upstreamServerId,c);return{byOperationId:o,byRoutePath:i,connectionsById:u}}r(_s,"buildGatewayConnectionRegistry");var ie,Ut;function Pd(e){Ut=e,ie=void 0}r(Pd,"configureGatewayConnectionRegistrySource");function Ed(e){ie=e}r(Ed,"setGatewayConnectionRegistry");function Rn(){if(!ie&&Ut&&(ie=_s(Ut)),!ie)throw new f("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 ie}r(Rn,"getGatewayConnectionRegistry");function ae(e){let o=Rn().byOperationId.get(e);if(!o)throw gn("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 o}r(ae,"getRegisteredMcpRoute");function Ve(e){let o=Rn().byRoutePath.get(e);if(!o)throw gn("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 o}r(Ve,"getRegisteredMcpRouteByRoutePath");function Ud(){return ie}r(Ud,"tryGetGatewayConnectionRegistry");E();var m=n.string().datetime({offset:!0}).brand();function yn(e){return m.parse(e.toISOString())}r(yn,"toIsoTimestamp");function qd(e,t){return new Date(e.getTime()+t*1e3)}r(qd,"addSeconds");E();function Ke(e,t){return e?.get(t)?.split(",",1)[0]?.trim()??""}r(Ke,"readHeaderValue");function xs(e){if(e===void 0)return"";let t=e.trim();return t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}r(xs,"unquoteForwardedValue");function zs(e){let t=Ke(e,"forwarded");if(t){let s=Object.fromEntries(t.split(";").map(l=>l.trim().split("=",2)).filter(l=>l.length===2).map(([l,y])=>[l.toLowerCase(),xs(y)])),u=s.proto,c=s.host;if(u||c)return{...u===void 0?{}:{proto:u},...c===void 0?{}:{host:c}}}let o=Ke(e,"x-forwarded-proto"),i=Ke(e,"x-forwarded-host");return!o&&!i?{}:{...o?{proto:o}:{},...i?{host:i}:{}}}r(zs,"readForwardedOriginHints");function Mt(e,t){let o=e.toLowerCase();if(!(o!=="https"&&o!=="http"))try{let i=new URL(`${o}://${t}`);return i.username||i.password||i.pathname!=="/"?void 0:i.origin}catch{return}}r(Mt,"parseHttpOrigin");function Is(e,t){let o=Ke(t,"host");if(!o)return;let i=zs(t);if(i.host!==void 0){let s=Mt(i.proto??e.protocol.replace(/:$/u,""),i.host),u=Mt(i.proto??e.protocol.replace(/:$/u,""),o);if(s!==void 0&&u!==void 0&&new URL(s).host!==new URL(u).host)return}return Mt(i.proto??e.protocol.replace(/:$/u,""),o)}r(Is,"readHostOrigin");function J(e,t){let o=new URL(e),i=Is(o,t);return i!==void 0?i:o.origin}r(J,"readGatewayRequestOrigin");function Me(e,t){return J(e,t)}r(Me,"readGatewayOAuthIssuer");function Ht(e){return e.length>512?`${e.slice(0,512)}\u2026`:e}r(Ht,"truncate");function bn(e){return"cause"in e?e.cause:void 0}r(bn,"readCause");function jt(e,t,o){if(!(o instanceof Error)){o!=null&&(e[`${t}Message`]=Ht(String(o)));return}e[`${t}Name`]=o.name,e[`${t}Message`]=Ht(o.message);let i=bn(o);for(let s=1;s<=4&&i instanceof Error;s+=1){let u=s===1?"cause":`cause${s}`;e[`${u}Name`]=i.name,e[`${u}Message`]=Ht(i.message),i=bn(i)}}r(jt,"addErrorLogFields");function X(e){if(e!==void 0)try{return typeof e=="string"?new URL(e).host:e.host}catch{return}}r(X,"safeHost");function Cn(e,t){let o=Object.entries(t).filter(i=>i[1]!==void 0);o.length!==0&&e.log.setLogProperties?.(Object.fromEntries(o))}r(Cn,"setLogProperties");function qt(e,t){Cn(e,{subjectId:t.subjectId})}r(qt,"applyGatewayUserLogProperties");function wn(e,t){Cn(e,{upstreamServerId:t.upstreamServerId,operationId:t.operationId})}r(wn,"applyGatewayRouteLogProperties");function em(e){let t=re(e);return{title:t.title,body:t.publicDetail}}r(em,"readGatewayCallbackFailureContent");function Ye(e){if(!(e instanceof A))return;let t=e.extensionMembers?.[w];return ne(t)?t:void 0}r(Ye,"readGatewayProblemCode");function se(e,t,o){let i=typeof e=="string"?{code:e,...t===void 0?{}:{publicDetail:t,privateDetail:t},...o===void 0?{}:{cause:o}}:e,s=re(i.code),u=i.privateDetail??(Je(i.code)?i.publicDetail??s.publicDetail:s.publicDetail),c=Ts(i);return new A({message:u,extensionMembers:{[w]:i.code}},c===void 0?void 0:{cause:c})}r(se,"createGatewayRuntimeError");async function Re(e,t,o){let i=re(o.code),s=ks(o.code,o.detail),u=Je(o.code)?o.title??i.title:i.title,l={problem:{...ze.getProblemFromStatus(i.status,{detail:s,instance:o.instance,type:o.type}),...o.extensions??{},status:i.status,title:u,detail:s,code:o.code}};return o.headers!==void 0&&(l.additionalHeaders=o.headers),ze.format(l,e,t)}r(Re,"gatewayProblemResponse");function Je(e){return re(e).status<500}r(Je,"canExposeGatewayProblemDetail");function Ts(e){return!e.privateDetail||Je(e.code)?e.cause:e.cause===void 0?new Error(e.privateDetail):new Error(e.privateDetail,{cause:e.cause})}r(Ts,"readRuntimeErrorCause");function ks(e,t){let o=re(e);return Je(e)&&t||o.publicDetail}r(ks,"readSafeGatewayProblemDetail");var Os=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function vs(e){return e.protocol.replace(/:$/u,"").toLowerCase()}r(vs,"readScheme");function Ps(e){return e.protocol==="https:"}r(Ps,"isSpecCompliantRedirectUri");function Es(e){let t=vs(e);return t.length>0&&t!=="http"&&t!=="https"&&!Os.has(t)}r(Es,"isNativeAppCustomSchemeRedirectUri");var _n=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:r(e=>Ps(e),"accepts")},{id:"oauth.redirect_uri.loopback_http",mode:"native_app",accepts:r(e=>j(e),"accepts"),matches:r((e,t)=>j(e)&&j(t)&&e.pathname===t.pathname&&e.search===t.search,"matches")},{id:"oauth.redirect_uri.custom_scheme",mode:"native_app",accepts:r(e=>Es(e),"accepts")}];function rm(e){let t=_n.find(o=>o.accepts(e.url,e.context));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}r(rm,"evaluateBuiltInRedirectUriCompatibility");function An(e){try{return new URL(e)}catch{return}}r(An,"parseUrl");function xn(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=An(e.registeredRedirectUri),o=An(e.requestedRedirectUri);if(t===void 0||o===void 0)return!1;let i=e.context??{source:"registration_match"};return _n.some(s=>s.matches?.(t,o,i))}r(xn,"redirectUriMatchesBuiltInCompatibility");E();var Us=43,Ms=128,Hs=/^[A-Za-z0-9._~-]+$/,Dt="S256",cm=n.literal(Dt),um=n.string().min(Us).max(Ms).regex(Hs);function Xe(e){return e.replace(/^\/+/,"").split("/").map(t=>encodeURIComponent(t)).join("/")}r(Xe,"encodeMcpRoutePathForScopedOAuthRoute");function zn(e){let t=typeof e=="string"?e:"";return t===""?"":`/${t.replace(/^\/+/,"")}`}r(zn,"decodeMcpRoutePathFromScopedOAuthParam");E();var In=["none","client_secret_post","client_secret_basic","private_key_jwt"],Lt=[...In],js=["awaiting_login","awaiting_setup"],qs=n.string().min(1).brand(),Z=n.string().min(1).brand(),He=n.uuid().brand(),Y=n.uuid().brand(),Ds=n.uuid().brand(),Ls=n.enum(In),Gs=n.enum(Lt),gm=n.enum(js),Sm=n.object({client_id:Z,client_name:n.string().min(1),redirect_uris:n.array(n.string().min(1)).min(1),jwks_uri:n.string().min(1).optional(),token_endpoint_auth_method:Gs}).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."})}),Gt=n.object({clientId:Z,clientName:n.string().min(1),redirectUris:n.array(n.string().min(1)),tokenEndpointAuthMethod:Ls,jwksUri:n.string().min(1).optional(),hashedClientSecret:n.string().optional(),clientSecretExpiresAt:m.optional(),clientExpiresAt:m,revokedAt:m.optional(),createdAt:m}),Tn=n.object({clientId:Z,resource:n.string(),operationId:D,subjectId:qs,scope:n.string(),roles:n.array(n.string()),createdAt:m,expiresAt:m}),Nt=Tn.extend({id:He,currentRefreshTokenHash:n.string().optional(),previousRefreshTokenHash:n.string().optional(),previousRefreshTokenRotatedAt:m.optional(),revokedAt:m.optional(),revokedReason:n.string().optional()}),Qe=Tn.extend({tokenHash:n.string(),grantId:He,revokedAt:m.optional()});function Rm(){return Y.parse(crypto.randomUUID())}r(Rm,"createDownstreamAuthorizationTransactionId");function ym(){return Ds.parse(crypto.randomUUID())}r(ym,"createDownstreamBrowserLoginStateId");function bm(){return He.parse(crypto.randomUUID())}r(bm,"createDownstreamGrantId");var W="mcp:tools";function Em(e,t){return xn({registeredRedirectUri:e,requestedRedirectUri:t,context:{source:"registration_match"}})}r(Em,"redirectUriMatchesRegistration");function Um(e){return j(e)&&e.pathname==="/oauth/dev-login"}r(Um,"isLoopbackDevLoginUrl");function et(e,t,o){return new URL(e,Me(t,o)).toString()}r(et,"buildGatewayOAuthUrl");function Bt(e){let t=ae(D.parse(e.operationId));return new URL(t.routePath,J(e.requestUrl,e.requestHeaders)).toString()}r(Bt,"buildScopedAuthorizationServerIssuer");function Ns(e){let t=ae(D.parse(e.operationId));return new URL(`/oauth/authorize/${Xe(t.routePath)}`,J(e.requestUrl,e.requestHeaders)).toString()}r(Ns,"buildScopedAuthorizationEndpoint");function Bs(e,t){let o=Ge();return{issuer:Me(e,t),authorization_endpoint:et("/oauth/authorize",e,t),token_endpoint:et("/oauth/token",e,t),registration_endpoint:et("/oauth/register",e,t),revocation_endpoint:et("/oauth/revoke",e,t),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],scopes_supported:[W],code_challenge_methods_supported:[Dt],token_endpoint_auth_methods_supported:Lt,revocation_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post","private_key_jwt","none"],client_id_metadata_document_supported:o.gateway.cimdEnabled,"x-zuplo-browser-login-kind":Io(o)}}r(Bs,"buildAuthorizationServerMetadata");function Mm(e){let t=Bt(e);return{...Bs(e.requestUrl,e.requestHeaders),issuer:t,authorization_endpoint:Ns(e)}}r(Mm,"buildScopedAuthorizationServerMetadata");var kn=Do;async function Zm(e,t){try{let o=Fs(e.params.routePath);return Response.json($s(o.operationId,e.url,e.headers))}catch(o){let i=Ye(o);return Re(e,t,{code:i==="unknown_mcp_route"?i:"not_found",detail:(o instanceof Error?o.message:void 0)??"The requested protected resource metadata document was not found."})}}r(Zm,"protectedResourceMetadataHandler");function $s(e,t,o){let i=ae(e);return{resource:$t(i.operationId,t,o),resource_name:i.routePath,authorization_servers:[Bt({operationId:i.operationId,requestUrl:t,requestHeaders:o})],bearer_methods_supported:["header"],scopes_supported:[W],mcp_protocol_version:kn}}r($s,"buildProtectedResourceMetadataResponseBody");function $t(e,t,o){let i=ae(e);return new URL(i.routePath,J(t,o)).toString()}r($t,"buildCanonicalMcpResourceForRoute");function On(e,t,o){let i=ae(e);return new URL(`/.well-known/oauth-protected-resource/${Xe(i.routePath)}`,J(t,o)).toString()}r(On,"buildProtectedResourceMetadataUrlForRoute");function Fs(e){return Ve(zn(e))}r(Fs,"getRegisteredMcpRouteByExternalPathParam");E();var T=n.string().min(1).brand();var Zs=n.record(n.string(),n.unknown()),vn=n.string().min(1),Ws=n.union([vn.transform(e=>[e]),n.array(vn)]);var Vs=["zuploSubjectId","zuplo_subject_id","gatewaySubjectId","gateway_subject_id","subjectId","subject_id","https://zuplo.com/subject_id"],Ks=["https://zuplo.com/roles","roles","role","permissions","groups"];function Ys(e){let t=Zs.safeParse(e);return t.success?t.data:{}}r(Ys,"toClaimRecord");function Js(e){return e.issues[0]?.message??"Gateway request user is invalid"}r(Js,"readValidationFailureDetail");function Xs(e,t,o,i){for(let c of Vs){let l=T.safeParse(t[c]);if(l.success)return l.data}let s=T.safeParse(e?.sub);if(!s.success)throw se("identity_context_missing",Js(s.error));let u=typeof t.iss=="string"?t.iss:void 0;return!u||u===Me(o,i)?s.data:T.parse(`${u}|${s.data}`)}r(Xs,"readNormalizedSubjectId");function Qs(e){let t=new Set;for(let o of Ks){let i=Ws.safeParse(e[o]);if(i.success)for(let s of i.data)t.add(s)}return t.size>0?[...t]:void 0}r(Qs,"readRoles");function ec(e,t,o){let i=Ys(e?.data),s={subjectId:Xs(e,i,t,o)},u=Qs(i);return u&&(s.roles=u),s}r(ec,"parseGatewayRequestUser");function Pn(e,t,o){try{return ec(e,t,o)}catch{return}}r(Pn,"tryParseGatewayRequestUser");function tt(e){let o=['realm="OAuth"',`resource_metadata="${Ft(On(e.operationId,e.requestUrl,e.requestHeaders))}"`];return e.error!==void 0&&o.push(`error="${e.error}"`),e.errorDescription!==void 0&&o.push(`error_description="${Ft(e.errorDescription)}"`),e.scope!==void 0&&o.push(`scope="${Ft(e.scope)}"`),`Bearer ${o.join(", ")}`}r(tt,"buildGatewayBearerChallenge");function Ft(e){let t="";for(let o=0;o<e.length;o+=1){let i=e.charCodeAt(o);i<=31||i===127||(t+=e[o])}return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}r(Ft,"sanitizeQuotedHeaderParameter");E();E();function En(e){return new A({message:e,extensionMembers:{[w]:"invalid_request"}})}r(En,"invalidReturnTo");function Un(e){if(e===void 0||e.length===0)return;if(!e.startsWith("/")||e.startsWith("//"))throw En("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 En("returnTo must be a same-origin relative path without credentials or fragments.");return`${t.pathname}${t.search}`}r(Un,"parseSafeRelativeReturnTo");E();var tc=["user","shared"],ye=n.enum(tc);function Mn(e){return{mode:"user",subjectId:e}}r(Mn,"buildUserUpstreamConnectionOwner");function Hn(){return{mode:"shared"}}r(Hn,"buildSharedUpstreamConnectionOwner");var jn=n.object({ownerMode:ye,initiatedBySubjectId:T,ownerSubjectId:T.optional(),upstreamServerId:q,authProfileId:B,operationId:D,returnTo:n.string().min(1).transform(e=>Un(e)).optional()});function qn(e,t){e.ownerMode==="user"&&!e.ownerSubjectId&&t.addIssue({code:n.ZodIssueCode.custom,message:"User-owned state requires ownerSubjectId",path:["ownerSubjectId"]}),e.ownerMode==="shared"&&e.ownerSubjectId&&t.addIssue({code:n.ZodIssueCode.custom,message:"Shared state must not include ownerSubjectId",path:["ownerSubjectId"]})}r(qn,"validateUpstreamOwnerState");var Zt=jn.superRefine(qn),bl=jn.omit({returnTo:!0}).superRefine(qn);function Cl(e){return Zt.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})}r(Cl,"buildUpstreamOwnerState");function wl(e){if(e.ownerMode==="shared")return Hn();if(!e.ownerSubjectId)throw new A({message:"User-owned upstream state is missing the owner subject.",extensionMembers:{[w]:"oauth_state_invalid"}});return Mn(e.ownerSubjectId)}r(wl,"resolveUpstreamConnectionOwnerFromState");var oc=["active","not_connected","reconsent_required"],nc=["basic_auth_app_password","bearer_token"],Dn=n.string().trim().min(1).brand(),ot=n.uuid().brand(),Wt=n.uuid().brand(),Vt=n.enum(oc),rc=n.enum(nc),Ln=n.object({encryptedClientInformation:n.string().optional(),encryptedDiscoveryState:n.string().optional(),connectedBySubjectId:T.optional()}),ic=Ln.extend({encryptedStaticSecret:n.string().optional(),staticSecretKind:rc.optional(),staticSecretLabel:n.string().min(1).optional(),staticSecretUsername:n.string().min(1).optional()}).strict(),ac=n.object({id:Dn,subjectId:T.optional(),ownerMode:ye,upstreamServerId:q,authProfileId:B,status:Vt,encryptedAccessToken:n.string().min(1).optional(),encryptedRefreshToken:n.string().min(1).optional(),scopes:n.array(n.string()),expiresAt:m.optional(),metadata:ic.optional(),createdAt:m,updatedAt:m});function Kt(e,t){e.ownerMode==="user"&&(e.subjectId||t.addIssue({code:n.ZodIssueCode.custom,message:"User-owned upstream connections require subjectId",path:["subjectId"]})),e.ownerMode==="shared"&&e.subjectId!==void 0&&t.addIssue({code:n.ZodIssueCode.custom,message:"Shared upstream connections must not include subjectId",path:["subjectId"]})}r(Kt,"validateUpstreamConnectionOwnerShape");var be=ac.superRefine(Kt);function Gn(e){return JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId])}r(Gn,"readUpstreamConnectionLookupKey");var Yt=Zt.extend({id:ot,callbackPath:n.string().min(1),expiresAt:m,codeVerifier:n.string().optional(),redirectUri:n.url(),returnOrigin:n.url().optional()}).extend(Ln.shape);function vl(e){let t=e?.status??"not_connected",o={connected:t==="active",status:t};return e?.updatedAt!==void 0&&(o.updatedAt=e.updatedAt),o}r(vl,"readUpstreamConnectionStatus");function Pl(){return Dn.parse(`mcpgw2uc_${crypto.randomUUID()}`)}r(Pl,"createUpstreamConnectionId");function El(){return ot.parse(crypto.randomUUID())}r(El,"createOAuthStateId");function Ul(){return Wt.parse(crypto.randomUUID())}r(Ul,"createBrowserConnectTicketId");E();var Xt=n.discriminatedUnion("mode",[n.object({mode:n.literal("user"),subjectId:T}).strict(),n.object({mode:n.literal("shared")}).strict()]),Bn=n.object({owner:Xt,upstreamServerId:q,authProfileId:B}).strict(),$n=n.object({items:n.array(Bn).min(1).max(100)}).strict(),Qt=n.object({items:n.array(n.object({key:n.object({ownerMode:ye,subjectId:T.optional(),upstreamServerId:q,authProfileId:B}).strict(),connection:be.strict().optional()}).strict())}).strict(),Fn=be.omit({createdAt:!0,updatedAt:!0}).strict().superRefine(Kt),Zn=be.strict(),Wn=n.object({owner:Xt,upstreamServerId:q,authProfileId:B}).strict(),Vn=n.object({owner:Xt,upstreamServerId:q,authProfileId:B,connection:be.strict().optional(),connectionStatus:n.object({connected:n.boolean(),status:Vt,updatedAt:be.shape.updatedAt.optional()}).strict()}).strict(),sc=n.enum(["none","client_secret_basic","client_secret_post","private_key_jwt"]),ce=n.object({clientId:Z,clientName:n.string().min(1),tokenEndpointAuthMethod:sc}).strict(),eo=n.discriminatedUnion("method",[n.object({method:n.literal("none"),clientId:Z}).strict(),n.object({method:n.enum(["client_secret_basic","client_secret_post"]),clientId:Z,clientSecretHashInput:n.string().min(1)}).strict(),n.object({method:n.literal("private_key_jwt"),clientId:Z}).strict()]),to=n.object({id:Y,currentStateHash:n.string().min(1),clientId:Z,redirectUri:n.string().min(1),resource:n.string().min(1),operationId:D,clientState:n.string().optional(),scope:n.string(),codeChallenge:n.string().min(1),codeChallengeMethod:n.literal("S256"),setupApprovedAt:m.optional(),createdAt:m,expiresAt:m,consumedAt:m.optional()}).strict(),Nn=to.omit({id:!0,consumedAt:!0}).extend({transactionId:Y,client:ce.optional()}).strict(),oo=n.object({subjectId:T,roles:n.array(n.string()).optional()}).strict(),cc=to.extend({phase:n.literal("awaiting_login")}).strict(),Jt=to.extend({phase:n.literal("awaiting_setup"),principal:oo}).strict(),uc=n.discriminatedUnion("phase",[cc,Jt]),nt=n.object({transaction:uc,client:ce}).strict(),Kn=Gt.omit({revokedAt:!0}).strict(),Yn=n.discriminatedUnion("kind",[n.object({kind:n.literal("registered"),client:ce}).strict(),n.object({kind:n.literal("already_exists")}).strict()]),Jn=n.object({clientId:Z}).strict(),Xn=n.discriminatedUnion("kind",[n.object({kind:n.literal("found"),client:Gt.strict()}).strict(),n.object({kind:n.literal("missing")}).strict()]),Qn=n.discriminatedUnion("phase",[Nn.extend({phase:n.literal("awaiting_login")}).strict(),Nn.extend({phase:n.literal("awaiting_setup"),principal:oo}).strict()]),er=n.discriminatedUnion("kind",[nt.extend({kind:n.literal("started")}).strict(),n.object({kind:n.literal("invalid_client")}).strict(),n.object({kind:n.literal("redirect_uri_mismatch")}).strict(),n.object({kind:n.literal("already_exists")}).strict()]),tr=n.object({transactionId:Y,currentStateHash:n.string().min(1),now:m}).strict(),or=n.discriminatedUnion("kind",[nt.extend({kind:n.literal("available")}).strict(),n.object({kind:n.literal("stale_hash")}).strict(),n.object({kind:n.literal("consumed")}).strict(),n.object({kind:n.literal("expired")}).strict(),n.object({kind:n.literal("missing")}).strict()]),nr=n.object({transactionId:Y,expectedPhase:n.literal("awaiting_login"),currentStateHash:n.string().min(1),nextStateHash:n.string().min(1),nextPhase:n.literal("awaiting_setup"),principal:oo,now:m}).strict(),rr=n.discriminatedUnion("kind",[nt.extend({kind:n.literal("advanced")}).strict(),n.object({kind:n.literal("wrong_phase"),current:n.enum(["awaiting_login","awaiting_setup"])}).strict(),n.object({kind:n.literal("stale_hash")}).strict(),n.object({kind:n.literal("consumed")}).strict(),n.object({kind:n.literal("expired")}).strict(),n.object({kind:n.literal("missing")}).strict()]),ir=n.object({transactionId:Y,currentStateHash:n.string().min(1),currentPrincipal:n.object({subjectId:T}).strict(),now:m}).strict(),ar=n.discriminatedUnion("kind",[nt.extend({kind:n.literal("marked")}).strict(),n.object({kind:n.literal("wrong_phase"),current:n.enum(["awaiting_login","awaiting_setup"])}).strict(),n.object({kind:n.literal("principal_mismatch")}).strict(),n.object({kind:n.literal("stale_hash")}).strict(),n.object({kind:n.literal("consumed")}).strict(),n.object({kind:n.literal("expired")}).strict(),n.object({kind:n.literal("missing")}).strict()]),sr=n.discriminatedUnion("decision",[n.object({decision:n.literal("approve"),transactionId:Y,currentStateHash:n.string().min(1),currentPrincipal:n.object({subjectId:T}).strict(),authorizationCodeHash:n.string().min(1),authorizationCodeExpiresAt:m,grantId:He,now:m}).strict(),n.object({decision:n.literal("cancel"),transactionId:Y,currentStateHash:n.string().min(1),currentPrincipal:n.object({subjectId:T}).strict(),now:m}).strict()]),cr=n.discriminatedUnion("kind",[n.object({kind:n.literal("approved"),transaction:Jt,client:ce}).strict(),n.object({kind:n.literal("cancelled"),transaction:Jt,client:ce}).strict(),n.object({kind:n.literal("principal_mismatch")}).strict(),n.object({kind:n.literal("stale_hash")}).strict(),n.object({kind:n.literal("consumed_already")}).strict(),n.object({kind:n.literal("expired")}).strict(),n.object({kind:n.literal("missing")}).strict()]),ur=n.object({clientAuth:eo,codeHash:n.string().min(1),redirectUri:n.string().min(1),resource:n.string().min(1).optional(),codeChallenge:n.string().min(1),currentRefreshTokenHash:n.string().min(1),accessTokenHash:n.string().min(1),grantExpiresAt:m,accessTokenExpiresAt:m,now:m}).strict(),pr=n.discriminatedUnion("kind",[n.object({kind:n.literal("exchanged"),client:ce,grant:Nt.strict()}).strict(),n.object({kind:n.literal("invalid_client")}).strict(),n.object({kind:n.literal("consumed")}).strict(),n.object({kind:n.literal("missing")}).strict(),n.object({kind:n.literal("expired")}).strict(),n.object({kind:n.literal("resource_mismatch")}).strict(),n.object({kind:n.literal("binding_mismatch")}).strict()]),dr=n.object({clientAuth:eo,currentRefreshTokenHash:n.string().min(1),nextRefreshTokenHash:n.string().min(1),accessTokenHash:n.string().min(1),resource:n.string().min(1).optional(),accessTokenExpiresAt:m,now:m}).strict(),mr=n.discriminatedUnion("kind",[n.object({kind:n.literal("rotated"),client:ce,grant:Nt.strict(),accessToken:Qe.strict(),matched:n.literal("current")}).strict(),n.object({kind:n.literal("invalid_client")}).strict(),n.object({kind:n.literal("missing")}).strict(),n.object({kind:n.literal("expired")}).strict(),n.object({kind:n.literal("resource_mismatch")}).strict(),n.object({kind:n.literal("previous_token_grace")}).strict(),n.object({kind:n.literal("revoked")}).strict()]),lr=n.object({clientAuth:eo,tokenHash:n.string().min(1),now:m}).strict(),hr=n.discriminatedUnion("kind",[n.object({kind:n.literal("revoked_access_token")}).strict(),n.object({kind:n.literal("revoked_grant")}).strict(),n.object({kind:n.literal("client_mismatch")}).strict(),n.object({kind:n.literal("missing")}).strict(),n.object({kind:n.literal("invalid_client")}).strict()]),fr=n.object({tokenHash:n.string().min(1),now:m}).strict(),gr=n.discriminatedUnion("kind",[n.object({kind:n.literal("valid"),record:Qe.strict()}).strict(),n.object({kind:n.literal("missing")}).strict(),n.object({kind:n.literal("expired")}).strict(),n.object({kind:n.literal("revoked")}).strict()]),Sr=n.object({accessTokenHash:n.string().min(1),resource:n.string().min(1),operationId:D,upstreamConnectionKeys:n.array(Bn).max(100),now:m}).strict(),Rr=n.discriminatedUnion("kind",[n.object({kind:n.literal("authorized"),principal:n.object({subjectId:T,roles:n.array(n.string())}).strict(),accessToken:Qe.strict(),upstreamConnections:Qt.shape.items.optional().default([])}).strict(),n.object({kind:n.literal("missing")}).strict(),n.object({kind:n.literal("expired")}).strict(),n.object({kind:n.literal("revoked")}).strict(),n.object({kind:n.literal("resource_mismatch")}).strict(),n.object({kind:n.literal("principal_mismatch")}).strict()]),yr=n.object({record:Yt}).strict(),br=n.object({kind:n.literal("saved")}).strict(),Cr=n.object({id:ot,now:m}).strict(),wr=n.discriminatedUnion("kind",[n.object({kind:n.literal("available"),record:Yt}).strict(),n.object({kind:n.literal("consumed")}).strict(),n.object({kind:n.literal("missing")}).strict()]),Ar=n.object({id:Wt,expiresAt:m,now:m}).strict(),_r=n.discriminatedUnion("kind",[n.object({kind:n.literal("available")}).strict(),n.object({kind:n.literal("consumed")}).strict()]);var xr=100,pc=new Set(["undefined","null","nan"]);function zr(e){return e!==null&&typeof e=="object"}r(zr,"isProblemDetailsShape");var Ir="bckt_";function k(e){let t=qe.instance.runtime.ZUPLO_SERVICE_BUCKET_ID;if(!t)throw ue("internal_server_error","MCP Gateway runtime storage requires ZUPLO_SERVICE_BUCKET_ID.");if(!t.startsWith(Ir))throw ue("internal_server_error",`MCP Gateway runtime storage bucket ID must start with "${Ir}".`);return`/zups/v2/buckets/${encodeURIComponent(t)}/mcp/storage/${e}`}r(k,"buildStoragePath");function dc(){return k("upstream-connections/batch-get")}r(dc,"buildBatchGetUpstreamConnectionsPath");function mc(){return k("upstream-connections/upsert")}r(mc,"buildUpsertUpstreamConnectionPath");function lc(){return k("authorization/read-setup")}r(lc,"buildReadAuthorizationSetupPath");function hc(){return k("oauth/register-client")}r(hc,"buildRegisterClientPath");function fc(){return k("oauth/read-client")}r(fc,"buildReadClientPath");function gc(){return k("authorization/start")}r(gc,"buildStartAuthorizationPath");function Sc(){return k("authorization/read-pending")}r(Sc,"buildReadPendingAuthorizationPath");function Rc(){return k("authorization/advance-pending")}r(Rc,"buildAdvancePendingAuthorizationPath");function yc(){return k("authorization/mark-setup-approved")}r(yc,"buildMarkAuthorizationSetupApprovedPath");function bc(){return k("authorization/decide-setup")}r(bc,"buildDecideAuthorizationSetupPath");function Cc(){return k("token/exchange-authorization-code")}r(Cc,"buildExchangeAuthorizationCodePath");function wc(){return k("token/refresh")}r(wc,"buildRefreshTokenPath");function Ac(){return k("token/revoke")}r(Ac,"buildRevokeOAuthTokenPath");function _c(){return k("token/validate-access-token")}r(_c,"buildValidateAccessTokenPath");function xc(){return k("mcp/authorize-and-load-connections")}r(xc,"buildAuthorizeAndLoadConnectionsPath");function zc(){return k("upstream-oauth-state/save")}r(zc,"buildSaveUpstreamOAuthStatePath");function Ic(){return k("upstream-oauth-state/consume")}r(Ic,"buildConsumeUpstreamOAuthStatePath");function Tc(){return k("browser-connect-ticket/consume")}r(Tc,"buildConsumeBrowserConnectTicketPath");function kc(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}r(kc,"responseKeyMatchesLookup");function Oc(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}r(Oc,"authorizationSetupMatchesLookup");function Or(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}r(Or,"connectionMatchesLookup");function vc(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??"")&&io(e.scopes,t.scopes)&&ro(e.expiresAt,t.expiresAt)&&Pc(e.metadata,t.metadata)}r(vc,"connectionMatchesUpsertRecord");function ro(e,t){return e===void 0||t===void 0?e===t:Date.parse(e)===Date.parse(t)}r(ro,"optionalTimestampInstantsMatch");function Tr(e,t){return Date.parse(e)<=Date.parse(t)}r(Tr,"timestampInstantIsAtOrBefore");function io(e,t){return e.length===t.length&&e.every((o,i)=>o===t[i])}r(io,"stringArraysMatch");function Pc(e,t){let o=kr(e),i=kr(t),s=Object.fromEntries(i);return o.length===i.length&&o.every(([u,c])=>s[u]===c)}r(Pc,"metadataMatches");function kr(e){return Object.entries(e??{}).filter(t=>t[1]!==void 0)}r(kr,"definedMetadataEntries");function b(e,t){throw ue("internal_server_error",e,t)}r(b,"throwInvalidStorageResponse");function ue(e,t,o){let i=Ne[e],s=i.status<500,u=s?o:new Error(t,o===void 0?void 0:{cause:o});return new A({message:s?t:i.publicDetail,extensionMembers:{[w]:e}},u===void 0?void 0:{cause:u})}r(ue,"storageRuntimeError");async function Ec(e,t){try{let o=await e.json();return o&&typeof o=="object"&&!Array.isArray(o)&&delete o.$schema,t.parse(o)}catch(o){b("Gateway Service storage response did not match the runtime storage contract.",o)}}r(Ec,"parseRuntimeHttpStorageResponse");function vr(e,t){e.length!==t.length&&b("Gateway Service storage response item count did not match the request.");for(let[o,i]of e.entries()){let s=t[o];kc(i.key,s)||b("Gateway Service storage response key did not match the request."),i.connection!==void 0&&!Or(i.connection,s)&&b("Gateway Service storage response connection did not match the response key.")}}r(vr,"validateUpstreamConnectionItemsMatchLookups");function Uc(e,t){Oc(e,t)||b("Gateway Service storage response authorization setup did not match the request."),e.connection!==void 0&&!Or(e.connection,t)&&b("Gateway Service storage response authorization setup connection did not match the request.");let o=e.connection?.status==="active",i=e.connection?.status??"not_connected",s=e.connection?.updatedAt;(e.connectionStatus.connected!==o||e.connectionStatus.status!==i||!ro(e.connectionStatus.updatedAt,s))&&b("Gateway Service storage response authorization setup status did not match the connection.")}r(Uc,"validateAuthorizationSetupResponseMatchesLookup");function Mc(e,t){e.kind==="registered"&&(e.client.clientId!==t.clientId||e.client.clientName!==t.clientName||e.client.tokenEndpointAuthMethod!==t.tokenEndpointAuthMethod)&&b("Gateway Service storage response registered client did not match the request.")}r(Mc,"validateRegisterClientResponseMatchesRequest");function Hc(e,t){e.kind==="found"&&e.client.clientId!==t.clientId&&b("Gateway Service storage response client did not match the request.")}r(Hc,"validateReadClientResponseMatchesRequest");function jc(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)&&b("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)&&b("Gateway Service storage response started authorization principal did not match the request."))}r(jc,"validateStartAuthorizationResponseMatchesRequest");function no(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))&&b("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)&&b("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)&&b("Gateway Service storage response marked authorization principal did not match the request."),e.kind==="marked"&&"currentPrincipal"in t&&e.transaction.setupApprovedAt!==t.now&&b("Gateway Service storage response marked authorization setup approval timestamp did not match the request."))}r(no,"validatePendingAuthorizationResponseMatchesRequest");function qc(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)&&b("Gateway Service storage response authorization setup transaction did not match the request.")}r(qc,"validateAuthorizationSetupDecisionResponseMatchesRequest");function Dc(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||!ro(e.grant.expiresAt,t.grantExpiresAt)||t.resource!==void 0&&e.grant.resource!==t.resource)&&b("Gateway Service storage response authorization-code exchange did not match the request.")}r(Dc,"validateExchangeAuthorizationCodeResponseMatchesRequest");function Lc(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)&&b("Gateway Service storage response token refresh grant did not match the request."),(e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.grantId!==e.grant.id||!Tr(e.accessToken.expiresAt,t.accessTokenExpiresAt)||!Tr(e.accessToken.expiresAt,e.grant.expiresAt)||!Bc(e.accessToken,e.grant))&&b("Gateway Service storage response token refresh access token did not match the request."))}r(Lc,"validateRefreshTokenResponseMatchesRequest");function Gc(e,t){e.kind==="valid"&&e.record.tokenHash!==t.tokenHash&&b("Gateway Service storage response access token did not match the request.")}r(Gc,"validateAccessTokenValidationResponseMatchesRequest");function Nc(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||!io(e.principal.roles,e.accessToken.roles))&&b("Gateway Service storage response MCP authorization did not match the request."),vr(e.upstreamConnections,t.upstreamConnectionKeys))}r(Nc,"validateAuthorizeAndLoadConnectionsResponseMatchesRequest");function Bc(e,t){return e.clientId===t.clientId&&e.resource===t.resource&&e.operationId===t.operationId&&e.subjectId===t.subjectId&&e.scope===t.scope&&io(e.roles,t.roles)}r(Bc,"accessTokenMatchesGrant");async function $c(e){try{return await e.clone().json()}catch{return}}r($c,"readProblemDetails");async function Fc(e){let t=await $c(e),o=zr(t)&&typeof t.status=="number"?t.status:e.status,i=zr(t)&&ne(t.code)?t.code:Ho(o);throw ue(i,`Gateway Service storage request failed with HTTP ${o}.`)}r(Fc,"throwRuntimeHttpStorageError");var rt=class{static{r(this,"RuntimeHttpStorageClient")}#t;#o;constructor(t){this.#t=t.baseUrl??qe.instance.zuploEdgeApiUrl,this.#o=t.fetch??fetch}#n(t){let o;try{o=new URL(t,this.#t)}catch(i){throw ue("internal_server_error",`Gateway Service storage base URL is not a valid URL. Got ${JSON.stringify(this.#t)}. Verify the gateway runtime configuration.`,i)}if(o.protocol!=="https:"&&o.protocol!=="http:")throw ue("internal_server_error",`Gateway Service storage base URL must use http(s); got protocol "${o.protocol}" from ${JSON.stringify(this.#t)}.`);if(!o.hostname||pc.has(o.hostname))throw ue("internal_server_error",`Gateway Service storage base URL has an invalid hostname "${o.hostname}" (parsed from ${JSON.stringify(this.#t)}). The configured value is likely coerced from an unset environment variable.`);return o}async#e(t){let o=t.requestSchema.parse(t.input),i=this.#n(t.path),s=new Headers({"Content-Type":"application/json"});So(s);let u=await this.#o(i,{method:"POST",headers:s,body:JSON.stringify(o)});return u.ok||await Fc(u),{request:o,response:await Ec(u,t.responseSchema)}}async batchGetUpstreamConnections(t){if(t.length===0)return[];let o=[],i=new Map,s=t.map(c=>{let l=Gn(c),y=i.get(l);if(y!==void 0)return y;let x=o.length;return o.push(c),i.set(l,x),x}),u=[];for(let c=0;c<o.length;c+=xr){let l=o.slice(c,c+xr);u.push(...await this.#r(l))}return s.map(c=>u[c])}async upsertUpstreamConnection(t){let{request:o,response:i}=await this.#e({input:t,path:mc(),requestSchema:Fn,responseSchema:Zn});return vc(i,o)||b("Gateway Service storage response connection did not match the request."),i}async readAuthorizationSetup(t){let{request:o,response:i}=await this.#e({input:t,path:lc(),requestSchema:Wn,responseSchema:Vn});return Uc(i,o),i}async registerClient(t){let{request:o,response:i}=await this.#e({input:t,path:hc(),requestSchema:Kn,responseSchema:Yn});return Mc(i,o),i}async readClient(t){let{request:o,response:i}=await this.#e({input:t,path:fc(),requestSchema:Jn,responseSchema:Xn});return Hc(i,o),i}async startAuthorization(t){let{request:o,response:i}=await this.#e({input:t,path:gc(),requestSchema:Qn,responseSchema:er});return jc(i,o),i}async readPendingAuthorization(t){let{request:o,response:i}=await this.#e({input:t,path:Sc(),requestSchema:tr,responseSchema:or});return no(i,o),i}async advancePendingAuthorization(t){let{request:o,response:i}=await this.#e({input:t,path:Rc(),requestSchema:nr,responseSchema:rr});return no(i,o),i}async markAuthorizationSetupApproved(t){let{request:o,response:i}=await this.#e({input:t,path:yc(),requestSchema:ir,responseSchema:ar});return no(i,o),i}async decideAuthorizationSetup(t){let{request:o,response:i}=await this.#e({input:t,path:bc(),requestSchema:sr,responseSchema:cr});return qc(i,o),i}async saveUpstreamOAuthState(t){let{response:o}=await this.#e({input:t,path:zc(),requestSchema:yr,responseSchema:br});return o}async consumeUpstreamOAuthState(t){let{request:o,response:i}=await this.#e({input:t,path:Ic(),requestSchema:Cr,responseSchema:wr});return i.kind==="available"&&i.record.id!==o.id&&b("Gateway Service storage response upstream OAuth state did not match the request."),i}async consumeBrowserConnectTicket(t){let{response:o}=await this.#e({input:t,path:Tc(),requestSchema:Ar,responseSchema:_r});return o}async exchangeAuthorizationCode(t){let{request:o,response:i}=await this.#e({input:t,path:Cc(),requestSchema:ur,responseSchema:pr});return Dc(i,o),i}async refreshToken(t){let{request:o,response:i}=await this.#e({input:t,path:wc(),requestSchema:dr,responseSchema:mr});return Lc(i,o),i}async revokeOAuthToken(t){let{response:o}=await this.#e({input:t,path:Ac(),requestSchema:lr,responseSchema:hr});return o}async validateAccessToken(t){let{request:o,response:i}=await this.#e({input:t,path:_c(),requestSchema:fr,responseSchema:gr});return Gc(i,o),i}async authorizeAndLoadConnections(t){let{request:o,response:i}=await this.#e({input:t,path:xc(),requestSchema:Sr,responseSchema:Rr});return Nc(i,o),i}async#r(t){let o={items:[...t]},{response:i}=await this.#e({input:o,path:dc(),requestSchema:$n,responseSchema:Qt});return vr(i.items,t),i.items.map(s=>s.connection)}};var Zc="__zuploMcpGatewayStorageBackend",ao;function Wc(){return new rt({})}r(Wc,"buildProductionStorageBackend");function Pr(){let e=globalThis[Zc];return e||(ao||(ao=Wc()),ao)}r(Pr,"getStorage");function Vc(e,t){let o=Le(e),i=t.ownerMode??t.routeBinding?.ownerMode,s=t.upstreamAuthMode??t.routeBinding?.authMode,u=t.virtualServerName??t.routeBinding?.operationId??o?.operationId,c=t.upstreamServerName??t.routeBinding?.upstreamServerId??o?.upstreamServerId,l=t.upstreamServerTitle??t.routeBinding?.upstreamDisplayName,y=t.authProfileId??t.routeBinding?.authProfileId??o?.authProfileId;return wo(e,{...t,subjectId:t.subjectId??t.routeBinding?.initiatedBySubjectId,ownerMode:i,upstreamAuthMode:s,virtualServerName:u,upstreamServerName:c,upstreamServerTitle:l,authProfileId:y})}r(Vc,"buildMcpAnalyticsMetadata");function N(e,t){try{e.analyticsContext.addAnalyticsEvent(t.value??1,t.eventType,Vc(e,t),t.unit)}catch(o){e.log?.warn?.({event:"mcp_analytics_emit_failed",errorName:o instanceof Error?o.name:"unknown"})}}r(N,"emitMcpAnalyticsEvent");import{base64url as so}from"jose";var Kc="sha256:",Yc=32;function Er(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}r(Er,"copyToArrayBuffer");function bh(){let e=crypto.getRandomValues(new Uint8Array(Yc));return so.encode(e)}r(bh,"createOpaqueToken");async function Ur(e){let t=await crypto.subtle.digest("SHA-256",Er(new TextEncoder().encode(e)));return`${Kc}${so.encode(new Uint8Array(t))}`}r(Ur,"hashOpaqueValue");async function Ch(e){let t=await crypto.subtle.digest("SHA-256",Er(new TextEncoder().encode(e)));return so.encode(new Uint8Array(t))}r(Ch,"calculatePkceS256Challenge");function Jc(e){let t=e.headers.get("authorization"),[o,i]=t?.split(/\s+/,2)??[];if(!(o?.toLowerCase()!=="bearer"||!i))return i}r(Jc,"readBearerToken");function Xc(e,t,o){return Re(e,t,{code:"authentication_required",detail:"Gateway access token is required.",headers:{"WWW-Authenticate":o}})}r(Xc,"gatewayAuthenticationRequiredResponse");function Qc(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"}}}r(Qc,"tokenValidationReasonCode");async function eu(e,t,o){let i=await Pr().validateAccessToken({tokenHash:await Ur(e),now:yn(new Date)});if(i.kind!=="valid"){t.log.warn({event:"gateway_access_token_validate_failed",code:"authentication_required",validationKind:i.kind,operationId:o},"Gateway access token validation failed");let s=Qc(i.kind);throw N(t,{eventType:U.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:o,reasonClass:"auth",reasonCode:s,attributes:{validationKind:i.kind}}),N(t,{eventType:U.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:o,httpStatusCode:401,reasonClass:"auth",reasonCode:s}),se("authentication_required","Gateway access token is expired, revoked, or invalid.")}return i.record}r(eu,"validateGatewayAccessToken");function tu(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"),N(t,{eventType:U.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:e.operationId,reasonClass:"auth",reasonCode:"invalid_audience"}),N(t,{eventType:U.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:e.operationId,httpStatusCode:401,reasonClass:"auth",reasonCode:"invalid_audience"}),se("authentication_required","Gateway access token was not issued for this MCP resource.")}r(tu,"assertAccessTokenResource");function ou(e,t,o){return Re(e,t,{code:"forbidden",detail:"Gateway access token is missing the required MCP scope.",headers:{"WWW-Authenticate":tt({operationId:o,requestUrl:e.url,requestHeaders:e.headers,error:"insufficient_scope",errorDescription:`The access token is missing the ${W} scope required by this MCP resource.`,scope:W})}})}r(ou,"insufficientScopeResponse");function nu(e){return{zuploSubjectId:e.subjectId,roles:e.roles,clientId:e.clientId,scope:e.scope,resource:e.resource,operationId:e.operationId,grantId:e.grantId,createdAt:e.createdAt,expiresAt:e.expiresAt}}r(nu,"userDataFromAccessToken");function ru(e){let t=new Headers(e.headers);return t.delete("authorization"),new Ro(e,{headers:t,...e.user===void 0?{}:{user:e.user}})}r(ru,"stripDownstreamAuthorizationHeader");function iu(e){let t=Ye(e.error),o={event:"gateway_access_token_rejected",code:t??"authentication_required",operationId:e.operationId};return e.error instanceof Error?(o.errorName=e.error.name,o.errorMessage=e.error.message):e.error!==void 0&&e.error!==null&&(o.errorMessage=String(e.error)),e.context.log.warn(o,"Gateway access token rejected; MCP request denied"),Re(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":tt({operationId:e.operationId,requestUrl:e.request.url,requestHeaders:e.request.headers,error:"invalid_token",errorDescription:"The access token is expired, malformed, or invalid."})}})}r(iu,"gatewayTokenRejectedResponse");async function co(e,t,o){let i=$t(o.operationId,e.url,e.headers),s=Jc(e),u=tt({operationId:o.operationId,requestUrl:e.url,requestHeaders:e.headers,scope:W});if(!s)return t.log.debug({event:"gateway_access_token_missing",code:"authentication_required",operationId:o.operationId,hasAuthorizationHeader:e.headers.get("authorization")!==null},"MCP request did not include a gateway access token"),N(t,{eventType:U.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:o.operationId,httpStatusCode:401,reasonClass:"auth",reasonCode:"missing_token"}),Xc(e,t,u);try{let c=await eu(s,t,o.operationId);return tu({accessToken:c,resource:i,operationId:o.operationId},t),c.scope!==W?(t.log.warn({event:"gateway_access_token_insufficient_scope",code:"forbidden",tokenScope:c.scope,requiredScope:W,operationId:o.operationId,clientId:c.clientId},"Gateway access token does not have the required MCP scope"),N(t,{eventType:U.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:o.operationId,reasonClass:"auth",reasonCode:"insufficient_scope",attributes:{tokenScope:c.scope,requiredScope:W,clientId:c.clientId}}),N(t,{eventType:U.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:o.operationId,httpStatusCode:403,reasonClass:"auth",reasonCode:"insufficient_scope"}),ou(e,t,o.operationId)):(e.user={sub:c.subjectId,data:nu(c)},qt(t,{subjectId:c.subjectId}),N(t,{eventType:U.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED,outcome:"success",virtualServerName:o.operationId,subjectId:c.subjectId,attributes:{clientId:c.clientId}}),ru(e))}catch(c){return iu({request:e,context:t,error:c,operationId:o.operationId})}}r(co,"gatewayTokenInbound");var Ce={OAUTH_PROTECTED_RESOURCE_METADATA:"oauth_metadata",VIRTUAL_MCP_SERVER:"gateway",OTHER:"other"},au="oauth-protected-resource-metadata",su="/.well-known/oauth-protected-resource/";function cu(e){let o=(typeof e.route.raw=="function"?e.route.raw():void 0)?.operationId;return typeof o=="string"?o:void 0}r(cu,"readRouteOperationId");function uu(e){return e.hasGatewayRouteContext?Ce.VIRTUAL_MCP_SERVER:e.routeOperationId===au||e.routeOperationId===void 0&&e.routePath.startsWith(su)?Ce.OAUTH_PROTECTED_RESOURCE_METADATA:Ce.OTHER}r(uu,"classifyAnalyticsRouteSurface");function pu(e){let t=e.route.path;return{routePath:t,routeSurface:uu({routePath:t,routeOperationId:cu(e),hasGatewayRouteContext:Le(e)!==void 0})}}r(pu,"readAnalyticsRequestContext");function du(e){return e.response.status===405&&e.response.headers.has("allow")&&e.routeSurface===Ce.VIRTUAL_MCP_SERVER}r(du,"isIntentionalMethodRejection");function mu(e){return du(e)||e.response.status===401&&e.routeSurface===Ce.OAUTH_PROTECTED_RESOURCE_METADATA?"success":e.response.status>=400?"failure":"success"}r(mu,"classifyRequestCompletedOutcome");function Mr(e){return Pn(e.user,e.url,e.headers)?.subjectId}r(Mr,"readRequestSubjectId");async function uo(e,t){let o=Date.now(),i=pu(t);return N(t,{eventType:U.MCP_REQUEST_RECEIVED,outcome:"success",routeSurface:i.routeSurface,httpMethod:e.method,subjectId:Mr(e)}),pt.getContextExtensions(t).addHandlerResponseHook((s,u)=>{let c=mu({response:s,routeSurface:i.routeSurface});N(t,{eventType:U.MCP_REQUEST_COMPLETED,outcome:c,routeSurface:i.routeSurface,httpStatusCode:s.status,httpMethod:e.method,latencyMs:Date.now()-o,subjectId:Mr(u)})}),e}r(uo,"analyticsContextInbound");function lu(e){return e instanceof Response}r(lu,"isResponse");async function oe(e,t){let o=Ve(t.route.path),i={operationId:o.operationId};_o(t,i),wn(t,i);let s=await uo(e,t);return lu(s)?s:co(s,t,{operationId:o.operationId})}r(oe,"mcpOAuthInboundPolicy");var Hr=class extends de{static{r(this,"McpOAuthInboundPolicy")}constructor(t,o){let i=Ct(t,o);super(i,o)}async handler(t,o){return pe("policy.inbound.mcp-oauth"),le(o,this.options),oe(t,o)}};function Ct(e,t="mcp-oauth-inbound"){return ke(ht,e,`MCP OAuth policy "${t}"`)}r(Ct,"mcpOAuthOptionsToRuntimeConfig");function V(e){return new A({message:e,extensionMembers:{[w]:"invalid_request"}})}r(V,"invalidOutboundUrl");function hu(){let e=me.__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"}r(hu,"isTestOnlyAllowHttpLoopbackIdpEnabled");function fu(){let e=me.__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"}r(fu,"isTestOnlyAllowHttpLoopbackCimdEnabled");var gu=new Set(["undefined","null","nan"]);function mo(e,t){if(!e.hostname)throw V(`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(gu.has(e.hostname.toLowerCase()))throw V(`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.`)}r(mo,"assertSafeOutboundHostname");var Su=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),Ru=[{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 jr(e){if(!/^\d+\.\d+\.\d+\.\d+$/.test(e))return;let t=e.split(".").map(o=>Number(o));if(!(t.length!==4||t.some(o=>Number.isNaN(o)||o<0||o>255)))return t}r(jr,"parseIpv4Octets");function yu([e,t],o){let i=o.firstMax??o.first;return e<o.first||e>i?!1:o.secondMin===void 0||o.secondMax===void 0?!0:t>=o.secondMin&&t<=o.secondMax}r(yu,"ipv4RangeMatches");function qr(e){let t=jr(e);return t!==void 0&&Ru.some(o=>yu(t,o))}r(qr,"isPrivateIpv4");function po(e){if(!e||e.length>4)return;let t=Number.parseInt(e,16);return Number.isNaN(t)||t<0||t>65535?void 0:t}r(po,"parseIpv6Word");function bu(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}r(bu,"formatIpv4FromWords");function Cu(e){let t=e.slice(7),o=jr(t);if(o!==void 0)return o.join(".");let[i,s,u]=t.split(":"),c=po(i),l=po(s);return u===void 0&&c!==void 0&&l!==void 0?bu(c,l):void 0}r(Cu,"parseIpv6MappedIpv4");function wu(e){return po(e.split(":").find(Boolean))}r(wu,"readFirstIpv6Hextet");function Au(e){let t=te(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let i=Cu(t);return i===void 0||qr(i)}let o=wu(t);return o===void 0?!1:(o&65024)===64512||(o&65472)===65152}r(Au,"isPrivateIpv6");function lo(e){let t=te(e);return Su.has(t)||t.endsWith(".internal")||qr(t)||Au(t)}r(lo,"isBlockedOutboundHostname");function Dr(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw V(`Unsupported outbound protocol: ${t.protocol}`);mo(t,e);let o=j(t);if(t.protocol==="http:"&&!o)throw V("Configured outbound HTTP URLs must target loopback hosts.");let i=te(t.hostname);if(!o&&lo(i))throw V(`Blocked outbound host: ${i}`);return t}r(Dr,"validateConfiguredOutboundUrl");function Lr(e){let t=new URL(e),o=j(t),i=o&&hu();if(t.protocol!=="https:"&&!i)throw V("Identity provider URLs must use https.");if(t.username||t.password||t.search||t.hash)throw V("Identity provider URLs must not include credentials, query params, or fragments.");mo(t,e);let s=te(t.hostname);if(!o&&lo(s))throw V(`Blocked identity provider host: ${s}`);return t}r(Lr,"validateIdentityProviderUrl");function Gr(e,t){let o=new URL(e),i=o.protocol==="http:"&&j(o)&&fu();if(o.protocol!=="https:"&&!i||o.pathname==="/"||o.username||o.password||o.search||o.hash)throw V(`CIMD ${t} must be an HTTPS URL with a path and no credentials, query, or fragment.`);if(mo(o,e),!i&&lo(o.hostname))throw V(`CIMD ${t} points at a blocked host.`);return o}r(Gr,"validateCimdUrl");function Nr(e){return Gr(e,"client_id")}r(Nr,"validateCimdClientMetadataUrl");function Br(e){return Gr(e,"jwks_uri")}r(Br,"validateCimdClientJwksUrl");function $r(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let o=r(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",o,{once:!0}),()=>t.removeEventListener("abort",o)}r($r,"mergeAbortSignals");async function _u(e){try{await e.cancel()}catch{}}r(_u,"cancelReader");async function Fr(e,t){if(!e)return new Uint8Array;let o=e.getReader(),i=[],s=0,u=await o.read();for(;!u.done;){let y=u.value;if(s+=y.byteLength,s>t.maxBytes)throw await _u(o),t.createLimitError();i.push(y),u=await o.read()}let c=new Uint8Array(s),l=0;for(let y of i)c.set(y,l),l+=y.byteLength;return c}r(Fr,"readBoundedByteStream");var xu=2,zu=1024*1024,Iu=1e4,Tu=new Set([301,302,303,307,308]),ku=["authorization","proxy-authorization","cookie","cookie2"];function ho(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}r(ho,"readRequestUrl");function we(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}r(we,"readRequestMethod");function Ou(e,t,o){let i=e.headers.get("content-length");if(!i)return;let s=Number.parseInt(i,10);if(Number.isFinite(s)&&s>t)throw new A({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[w]:o}})}r(Ou,"assertContentLengthWithinLimit");async function vu(e,t,o){return Ou(e,t,o),Fr(e.body,{maxBytes:t,createLimitError:r(()=>new A({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[w]:o}}),"createLimitError")})}r(vu,"readBoundedResponseBody");function Pu(e,t){let o=new ArrayBuffer(t.byteLength);return new Uint8Array(o).set(t),new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}r(Pu,"responseFromBufferedBody");function Eu(e,t){if(!Tu.has(e.status))return;let o=e.headers.get("location");if(o)return new URL(o,t).toString()}r(Eu,"resolveRedirectUrl");function Zr(e,t){try{return t.validateUrl(e)}catch(o){throw new A({message:"Outbound URL was not allowed.",extensionMembers:{[w]:t.problemCode}},{cause:o})}}r(Zr,"validateOutboundUrl");function Uu(e,t){throw e instanceof A&&ne(e.extensionMembers?.[w])?e:new A({message:"Outbound fetch failed.",extensionMembers:{[w]:t}},{cause:e})}r(Uu,"normalizeFetchError");function je(e,t){if(e===void 0)return;let o={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(o.host=t.host),t.extra!==void 0)for(let[i,s]of Object.entries(t.extra))s!==void 0&&(o[i]=s);t.error!==void 0&&jt(o,"error",t.error),e.log.warn(o,"Outbound HTTP exchange rejected")}r(je,"logOutboundFailure");async function Mu(e,t,o,i,s,u,c){let l=we(o,i);try{return await t(o,i)}catch(y){let x=y instanceof DOMException&&y.name==="AbortError";je(e,{event:x?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:s,method:l,host:X(u),error:y,extra:{abortReason:c()}}),Uu(y,s)}}r(Mu,"fetchWithNormalizedError");function Hu(e){if(e.redirects>=e.maxRedirects)throw new A({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[w]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new A({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[w]:e.problemCode}})}r(Hu,"assertRedirectAllowed");function ju(e,t){let o=new Headers(e);for(let i of ku)o.delete(i);for(let i of t)o.delete(i);return o}r(ju,"stripCrossOriginHeaders");function qu(e,t,o,i,s){let u={...e,method:t,redirect:"manual",signal:o};return i&&(u.headers=ju(e.headers,s)),u}r(qu,"buildRedirectInit");function Du(e,t,o){let i={...t,redirect:"manual",signal:o};return i.headers===void 0&&e instanceof Request&&(i.headers=e.headers),i}r(Du,"buildInitialRequestInit");function Lu(e){let t=we(e.currentInput,e.currentInit);Hu({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let o=Zr(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),i=new URL(e.currentUrl),s=o.origin!==i.origin,u=o.toString();return{currentInput:u,currentUrl:u,currentInit:qu(e.currentInit,t,e.signal,s,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}r(Lu,"followRedirect");async function fo(e,t,o){let i=o.problemCode??"invalid_request",s=o.maxRedirects??xu,u=o.maxResponseBytes??zu,c=o.timeoutMs??Iu,l=o.fetchImpl??fetch,y=o.additionalCrossOriginStrippedHeaders??[],x=o.context,$=new AbortController,Ae=$r($,t.signal),K=!1,go=setTimeout(()=>{K=!0,$.abort()},c),_e=e,xe=Du(e,t,$.signal),Q;try{Q=Zr(ho(e),{problemCode:i,validateUrl:o.validateUrl}).toString()}catch(ee){throw je(x,{event:"outbound_url_blocked",problemCode:i,method:we(e,t),host:X(ho(e)),error:ee}),clearTimeout(go),Ae?.(),ee}let at=0;try{for(;;){let ee=await Mu(x,l,_e,xe,i,Q,()=>K?`timeout_after_${c}ms`:void 0),st=Eu(ee,Q);if(st!==void 0)try{let F=Lu({currentInput:_e,currentInit:xe,currentUrl:Q,redirectUrl:st,redirects:at,maxRedirects:s,problemCode:i,validateUrl:o.validateUrl,signal:$.signal,additionalCrossOriginStrippedHeaders:y});_e=F.currentInput,xe=F.currentInit,Q=F.currentUrl,at=F.redirects;continue}catch(F){throw je(x,{event:"outbound_redirect_blocked",problemCode:i,method:we(_e,xe),host:X(Q),error:F,extra:{redirects:at,maxRedirects:s,redirectTargetHost:X(st)}}),F}try{return Pu(ee,await vu(ee,u,i))}catch(F){throw je(x,{event:"outbound_response_size_exceeded",problemCode:i,method:we(_e,xe),host:X(Q),error:F,extra:{maxResponseBytes:u,status:ee.status}}),F}}}finally{clearTimeout(go),Ae?.()}}r(fo,"runSafeOutboundExchange");async function it(e,t,o){let i=await fo(e,t,o);try{return{response:i,json:await i.clone().json()}}catch(s){throw je(o.context,{event:"outbound_json_parse_failed",problemCode:o.problemCode??"invalid_request",method:we(e,t),host:X(ho(e)),error:s,extra:{status:i.status,contentType:i.headers.get("content-type")??void 0}}),new A({message:"Outbound JSON response could not be parsed.",extensionMembers:{[w]:o.problemCode??"invalid_request"}},{cause:s})}}r(it,"runSafeOutboundJsonExchange");function Af(e,t={},o={}){return fo(e,t,{...o,validateUrl:Dr})}r(Af,"fetchConfiguredOutbound");function _f(e,t={},o={}){return it(e,t,{...o,validateUrl:Lr})}r(_f,"fetchIdentityProviderJson");function xf(e,t={},o={}){return it(e,t,{...o,validateUrl:Nr})}r(xf,"fetchCimdClientMetadataJson");function zf(e,t={},o={}){return it(e,t,{...o,validateUrl:Br})}r(zf,"fetchCimdClientJwksJson");function vf(e){let t=Ge().browserLogin[e];if(typeof t=="string"&&t.length>0)return t;throw se("internal_server_error",`browserLogin.${e} is required for federated browser login. Set it on the mcp-oauth-inbound policy options.`)}r(vf,"requireBrowserLoginField");export{te as a,j as b,le as c,Ge as d,ke as e,Hr as f,Eo as g,ui as h,di as i,qp as j,w as k,Np as l,Bp as m,$p as n,Fp as o,ne as p,Zp as q,re as r,wt as s,Jp as t,q as u,D as v,B as w,Do as x,Fe as y,yi as z,Be as A,Bo as B,Fa as C,zt as D,hn as E,fn as F,Ad as G,Sn as H,_s as I,Pd as J,Ed as K,Rn as L,Ve as M,Ud as N,yn as O,qd as P,J as Q,Me as R,jt as S,X as T,qt as U,em as V,Ye as W,se as X,Re as Y,rm as Z,cm as _,um as $,Z as aa,Y as ba,Ds as ca,Ls as da,Sm as ea,Rm as fa,ym as ga,bm as ha,W as ia,Em as ja,Um as ka,Bs as la,Mm as ma,kn as na,Zm as oa,$t as pa,Fs as qa,T as ra,ec as sa,Pn as ta,Un as ua,Mn as va,Hn as wa,Zt as xa,bl as ya,Cl as za,wl as Aa,ot as Ba,Wt as Ca,vl as Da,Pl as Ea,El as Fa,Ul as Ga,Pr as Ha,N as Ia,bh as Ja,Ur as Ka,Ch as La,vo as Ma,Dr as Na,Nr as Oa,Br as Pa,Fr as Qa,Af as Ra,_f as Sa,xf as Ta,zf as Ua,vf as Va};
30
- //# sourceMappingURL=chunk-MJ6GX4IA.js.map