@zuplo/runtime 6.70.46 → 6.70.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
3
  "type": "module",
4
- "version": "6.70.46",
4
+ "version": "6.70.47",
5
5
  "repository": "https://github.com/zuplo/zuplo",
6
6
  "author": "Zuplo, Inc.",
7
7
  "exports": {
@@ -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 dt,B as je,K as ho,L as a,N as g,O as I,P as fo,R as x,S as h,T as u,U as E,V as R,W as pt,X as mt,Y as S,Z as M,_ as p,a as Me,aa as go,b as mo,ba as lt,ea as n,fa as O,ga as So,j as we,m as lo,s as He,x as ut}from"./chunk-J7JE2DD5.js";import{d as ue}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 Ue}from"./chunk-ZIKV2LUM.js";O();var Nr=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:"&&(Nr.has(t)||/^127(?:\.\d{1,3}){3}$/.test(t))}r(j,"isLoopbackHttpUrl");var Ro=new je("gateway-route");function yo(e,t){Ro.set(e,t)}r(yo,"setGatewayRouteContext");function qe(e){return Ro.get(e)}r(qe,"readGatewayRouteContext");var bo=new je("mcp-oauth-runtime-config");function De(e,t){bo.set(e,t)}r(De,"setMcpOAuthRuntimeConfig");function Co(e){let t=bo.get(e);if(!t)throw new f("MCP gateway OAuth config has not been set on the request context. An `mcp-oauth-inbound` policy (or `mcp-auth0-oauth-inbound`) must run before this handler, or the internal OAuth route wrapper must have populated the context.");return t}r(Co,"requireMcpOAuthRuntimeConfig");var Ae=n.string().trim().min(1),Fr=60,$r=24*60*60,Zr=15*Fr,Vr=10*365*$r,xe={accessTokenTtlSeconds:Zr,refreshTokenTtlSeconds:Vr,cimdEnabled:!0},Wr=n.object({issuer:n.url(),jwksUrl:n.url(),audience:Ae.optional()}),Kr=n.object({url:n.url(),tokenUrl:n.url().optional(),clientId:Ae.optional(),clientSecret:Ae.optional(),scope:Ae.default("openid profile email"),audience:Ae.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(!Ao(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]})}),Yr=n.object({accessTokenTtlSeconds:n.coerce.number().int().positive().default(xe.accessTokenTtlSeconds),refreshTokenTtlSeconds:n.coerce.number().int().positive().default(xe.refreshTokenTtlSeconds),cimdEnabled:n.boolean().default(xe.cimdEnabled)}).strict().default(xe),ht=n.object({oidc:Wr,browserLogin:Kr,gateway:Yr.optional().default(xe)}).strict();function wo(e){return Ao(e.browserLogin.url)?"local_dev":"federated_oidc"}r(wo,"readBrowserLoginKind");function Ao(e){let t;try{t=new URL(e)}catch{return!1}return j(t)&&t.pathname==="/oauth/dev-login"}r(Ao,"isLoopbackDevLoginUrl");function xo(e){return ht.parse(e)}r(xo,"parseMcpOAuthRuntimeConfig");function Le(){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 Co(e)}r(Le,"getGatewayOAuthConfig");O();function Ge(e,t,o){let i=e.safeParse(t);if(i.success)return i.data;throw new f(`${o} is misconfigured. Validation failed:
26
- ${Jr(i.error)}`,{cause:i.error})}r(Ge,"parseConfigOrThrow");function Jr(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
27
- `)}r(Jr,"formatZodIssues");var Xr=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.'}),Qr=n.object({auth0Domain:Xr,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(),_o=class extends He{static{r(this,"McpAuth0OAuthInboundPolicy")}#t;constructor(t,o){let i=zo(t,o);super(i,o),this.#t=To(i,o)}async handler(t,o){return Me("policy.inbound.mcp-auth0-oauth"),De(o,this.#t),_e(t,o)}};function zo(e,t){return Ge(Qr,e,`MCP Auth0 OAuth policy "${t}"`)}r(zo,"parseAuth0OAuthOptions");function Io(e,t="mcp-auth0-oauth-inbound"){let o=zo(e,t);return To(o,t)}r(Io,"auth0OptionsToMcpOAuthRuntimeConfig");function To(e,t){let o=`https://${e.auth0Domain}/`,i=`https://${e.auth0Domain}/.well-known/jwks.json`,s=`https://${e.auth0Domain}/authorize`,d=`https://${e.auth0Domain}/oauth/token`;try{return xo({oidc:{issuer:o,jwksUrl:i,...e.audience===void 0?{}:{audience:e.audience}},browserLogin:{url:s,tokenUrl:d,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(To,"buildAuth0McpOAuthRuntimeConfig");var ei=["mcp-oauth-inbound","mcp-auth0-oauth-inbound"],ko={"mcp-oauth-inbound":"McpOAuthInboundPolicy","mcp-auth0-oauth-inbound":"McpAuth0OAuthInboundPolicy"};function ti(e,t,o){switch(e){case"mcp-oauth-inbound":return ft(o,t);case"mcp-auth0-oauth-inbound":return Io(o,t);default:return}}r(ti,"parseMcpOAuthPolicyConfig");function vo(e){return e!==void 0&&ei.some(t=>t===e)}r(vo,"isMcpOAuthInboundPolicyType");function oi(e){switch(e.policyType){case"mcp-oauth-inbound":return e.handler.export===ko["mcp-oauth-inbound"];case"mcp-auth0-oauth-inbound":return e.handler.export===ko["mcp-auth0-oauth-inbound"];default:return!1}}r(oi,"isMcpOAuthRuntimeConfigPolicy");function Rd(e){if(!e)return;let t=e.filter(oi);if(t.length>1){let s=t.map(d=>`"${d.name}" (${d.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=ti(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(Rd,"resolveMcpOAuthRuntimeConfigFromPolicies");var w="gatewayCode",wd="upstreamErrorContentType",Ad="upstreamErrorHtml",xd="upstreamErrorStatus",_d="upstreamErrorUrl",de={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={...de.runtime,...de.config,...de.downstream_auth,...de.downstream_oauth,...de.upstream_auth,...de.upstream_mcp};function oe(e){return typeof e=="string"&&Object.hasOwn(Ne,e)}r(oe,"isGatewayProblemCode");function zd(e){return oe(e)&&ne(e).callbackFailure===!0}r(zd,"isGatewayCallbackFailureCode");function ne(e){return Ne[e]}r(ne,"readGatewayProblemDefinition");function Po(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(Po,"readDefaultGatewayProblemCodeForStatus");var ni=/^\$\{env\.([A-Za-z_][A-Za-z0-9_]*)\}$/;function Eo(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(Eo,"assertHttpUrl");function Oo(e){return e.options??{}}r(Oo,"readHandlerOptions");function ri(e){let t=ni.exec(e);if(t){let o=t[1],i=ue[o];if(typeof i!="string"||i==="")throw new f(`MCP route handler rewritePattern references env.${o}, but that environment variable is not set.`);return Eo(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 Eo(e,"MCP route handler rewritePattern")}r(ri,"readRewritePatternUrl");function gt(e){let t=Oo(e);if(typeof t.rewritePattern=="string"&&t.rewritePattern!=="")return ri(t.rewritePattern);throw new f("MCP route must configure handler.options.rewritePattern.")}r(gt,"readMcpRouteUpstreamUrl");function Pd(e){let t=Oo(e.handler),o=new URL(gt(e.handler));if(t.forwardSearch!==!1)for(let[s,d]of new URL(e.request.url).searchParams)o.searchParams.append(s,d);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(Pd,"buildMcpRouteUpstreamFetch");O();var ii=["shared-oauth","user-oauth"],ai=["none","client_secret_basic","client_secret_post"],q=n.string().min(1).brand(),D=n.string().min(1),B=n.string().min(1).brand(),Md=n.string().min(1).brand(),St=n.enum(ii),Rt=n.enum(ai);O();var Uo="2025-11-25";var si="io.modelcontextprotocol/related-task",$e="2.0",z=go(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Mo=R([a(),g().int()]),Ho=a(),qd=E({ttl:g().optional(),pollInterval:g().optional()}),ci=u({ttl:g().optional()}),ui=u({taskId:a()}),Ct=E({progressToken:Mo.optional(),[si]:ui.optional()}),H=u({_meta:Ct.optional()}),Ze=H.extend({task:ci.optional()});var v=u({method:a(),params:H.loose().optional()}),L=u({_meta:Ct.optional()}),G=u({method:a(),params:L.loose().optional()}),P=E({_meta:Ct.optional()}),Ve=R([a(),g().int()]),di=u({jsonrpc:p($e),id:Ve,...v.shape}).strict();var pi=u({jsonrpc:p($e),...G.shape}).strict();var jo=u({jsonrpc:p($e),id:Ve,result:P}).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 qo=u({jsonrpc:p($e),id:Ve.optional(),error:u({code:g().int(),message:a(),data:x().optional()})}).strict();var Dd=R([di,pi,jo,qo]),Ld=R([jo,qo]),Do=P.strict(),mi=L.extend({requestId:Ve.optional(),reason:a().optional()}),Lo=G.extend({method:p("notifications/cancelled"),params:mi}),li=u({src:a(),mimeType:a().optional(),sizes:h(a()).optional(),theme:M(["light","dark"]).optional()}),ze=u({icons:h(li).optional()}),pe=u({name:a(),title:a().optional()}),me=pe.extend({...pe.shape,...ze.shape,version:a(),websiteUrl:a().optional(),description:a().optional()}),hi=mt(u({applyDefaults:I().optional()}),S(a(),x())),fi=lt(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,mt(u({form:hi.optional(),url:z.optional()}),S(a(),x()).optional())),gi=E({list:z.optional(),cancel:z.optional(),requests:E({sampling:E({createMessage:z.optional()}).optional(),elicitation:E({create:z.optional()}).optional()}).optional()}),Si=E({list:z.optional(),cancel:z.optional(),requests:E({tools:E({call:z.optional()}).optional()}).optional()}),Ri=u({experimental:S(a(),z).optional(),sampling:u({context:z.optional(),tools:z.optional()}).optional(),elicitation:fi.optional(),roots:u({listChanged:I().optional()}).optional(),tasks:gi.optional(),extensions:S(a(),z).optional()}),yi=H.extend({protocolVersion:a(),capabilities:Ri,clientInfo:me}),bi=v.extend({method:p("initialize"),params:yi});var Ci=u({experimental:S(a(),z).optional(),logging:z.optional(),completions:z.optional(),prompts:u({listChanged:I().optional()}).optional(),resources:u({subscribe:I().optional(),listChanged:I().optional()}).optional(),tools:u({listChanged:I().optional()}).optional(),tasks:Si.optional(),extensions:S(a(),z).optional()}),wi=P.extend({protocolVersion:a(),capabilities:Ci,serverInfo:me,instructions:a().optional()}),Ai=G.extend({method:p("notifications/initialized"),params:L.optional()});var Go=v.extend({method:p("ping"),params:H.optional()}),xi=u({progress:g(),total:C(g()),message:C(a())}),_i=u({...L.shape,...xi.shape,progressToken:Mo}),No=G.extend({method:p("notifications/progress"),params:_i}),zi=H.extend({cursor:Ho.optional()}),Ie=v.extend({params:zi.optional()}),Te=P.extend({nextCursor:Ho.optional()}),Ii=M(["working","input_required","completed","failed","cancelled"]),ke=u({taskId:a(),status:Ii,ttl:R([g(),fo()]),createdAt:a(),lastUpdatedAt:a(),pollInterval:C(g()),statusMessage:C(a())}),Bo=P.extend({task:ke}),Ti=L.merge(ke),Fo=G.extend({method:p("notifications/tasks/status"),params:Ti}),$o=v.extend({method:p("tasks/get"),params:H.extend({taskId:a()})}),Zo=P.merge(ke),Vo=v.extend({method:p("tasks/result"),params:H.extend({taskId:a()})}),Gd=P.loose(),Wo=Ie.extend({method:p("tasks/list")}),Ko=Te.extend({tasks:h(ke)}),Yo=v.extend({method:p("tasks/cancel"),params:H.extend({taskId:a()})}),Nd=P.merge(ke),Jo=u({uri:a(),mimeType:C(a()),_meta:S(a(),x()).optional()}),Xo=Jo.extend({text:a()}),wt=a().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Qo=Jo.extend({blob:wt}),ve=M(["user","assistant"]),le=u({audience:h(ve).optional(),priority:g().min(0).max(1).optional(),lastModified:ho.datetime({offset:!0}).optional()}),en=u({...pe.shape,...ze.shape,uri:a(),description:C(a()),mimeType:C(a()),size:C(g()),annotations:le.optional(),_meta:C(E({}))}),ki=u({...pe.shape,...ze.shape,uriTemplate:a(),description:C(a()),mimeType:C(a()),annotations:le.optional(),_meta:C(E({}))}),vi=Ie.extend({method:p("resources/list")}),Pi=Te.extend({resources:h(en)}),Ei=Ie.extend({method:p("resources/templates/list")}),Oi=Te.extend({resourceTemplates:h(ki)}),At=H.extend({uri:a()}),Ui=At,Mi=v.extend({method:p("resources/read"),params:Ui}),Hi=P.extend({contents:h(R([Xo,Qo]))}),ji=G.extend({method:p("notifications/resources/list_changed"),params:L.optional()}),qi=At,Di=v.extend({method:p("resources/subscribe"),params:qi}),Li=At,Gi=v.extend({method:p("resources/unsubscribe"),params:Li}),Ni=L.extend({uri:a()}),Bi=G.extend({method:p("notifications/resources/updated"),params:Ni}),Fi=u({name:a(),description:C(a()),required:C(I())}),$i=u({...pe.shape,...ze.shape,description:C(a()),arguments:C(h(Fi)),_meta:C(E({}))}),Zi=Ie.extend({method:p("prompts/list")}),Vi=Te.extend({prompts:h($i)}),Wi=H.extend({name:a(),arguments:S(a(),a()).optional()}),Ki=v.extend({method:p("prompts/get"),params:Wi}),xt=u({type:p("text"),text:a(),annotations:le.optional(),_meta:S(a(),x()).optional()}),_t=u({type:p("image"),data:wt,mimeType:a(),annotations:le.optional(),_meta:S(a(),x()).optional()}),zt=u({type:p("audio"),data:wt,mimeType:a(),annotations:le.optional(),_meta:S(a(),x()).optional()}),Yi=u({type:p("tool_use"),name:a(),id:a(),input:S(a(),x()),_meta:S(a(),x()).optional()}),Ji=u({type:p("resource"),resource:R([Xo,Qo]),annotations:le.optional(),_meta:S(a(),x()).optional()}),Xi=en.extend({type:p("resource_link")}),It=R([xt,_t,zt,Xi,Ji]),Qi=u({role:ve,content:It}),ea=P.extend({description:a().optional(),messages:h(Qi)}),ta=G.extend({method:p("notifications/prompts/list_changed"),params:L.optional()}),oa=u({title:a().optional(),readOnlyHint:I().optional(),destructiveHint:I().optional(),idempotentHint:I().optional(),openWorldHint:I().optional()}),na=u({taskSupport:M(["required","optional","forbidden"]).optional()}),tn=u({...pe.shape,...ze.shape,description:a().optional(),inputSchema:u({type:p("object"),properties:S(a(),z).optional(),required:h(a()).optional()}).catchall(x()),outputSchema:u({type:p("object"),properties:S(a(),z).optional(),required:h(a()).optional()}).catchall(x()).optional(),annotations:oa.optional(),execution:na.optional(),_meta:S(a(),x()).optional()}),ra=Ie.extend({method:p("tools/list")}),ia=Te.extend({tools:h(tn)}),on=P.extend({content:h(It).default([]),structuredContent:S(a(),x()).optional(),isError:I().optional()}),Bd=on.or(P.extend({toolResult:x()})),aa=Ze.extend({name:a(),arguments:S(a(),x()).optional()}),sa=v.extend({method:p("tools/call"),params:aa}),ca=G.extend({method:p("notifications/tools/list_changed"),params:L.optional()}),Fd=u({autoRefresh:I().default(!0),debounceMs:g().int().nonnegative().default(300)}),nn=M(["debug","info","notice","warning","error","critical","alert","emergency"]),ua=H.extend({level:nn}),da=v.extend({method:p("logging/setLevel"),params:ua}),pa=L.extend({level:nn,logger:a().optional(),data:x()}),ma=G.extend({method:p("notifications/message"),params:pa}),la=u({name:a().optional()}),ha=u({hints:h(la).optional(),costPriority:g().min(0).max(1).optional(),speedPriority:g().min(0).max(1).optional(),intelligencePriority:g().min(0).max(1).optional()}),fa=u({mode:M(["auto","required","none"]).optional()}),ga=u({type:p("tool_result"),toolUseId:a().describe("The unique identifier for the corresponding tool call."),content:h(It).default([]),structuredContent:u({}).loose().optional(),isError:I().optional(),_meta:S(a(),x()).optional()}),Sa=pt("type",[xt,_t,zt]),Fe=pt("type",[xt,_t,zt,Yi,ga]),Ra=u({role:ve,content:R([Fe,h(Fe)]),_meta:S(a(),x()).optional()}),ya=Ze.extend({messages:h(Ra),modelPreferences:ha.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(tn).optional(),toolChoice:fa.optional()}),ba=v.extend({method:p("sampling/createMessage"),params:ya}),Ca=P.extend({model:a(),stopReason:C(M(["endTurn","stopSequence","maxTokens"]).or(a())),role:ve,content:Sa}),wa=P.extend({model:a(),stopReason:C(M(["endTurn","stopSequence","maxTokens","toolUse"]).or(a())),role:ve,content:R([Fe,h(Fe)])}),Aa=u({type:p("boolean"),title:a().optional(),description:a().optional(),default:I().optional()}),xa=u({type:p("string"),title:a().optional(),description:a().optional(),minLength:g().optional(),maxLength:g().optional(),format:M(["email","uri","date","date-time"]).optional(),default:a().optional()}),_a=u({type:M(["number","integer"]),title:a().optional(),description:a().optional(),minimum:g().optional(),maximum:g().optional(),default:g().optional()}),za=u({type:p("string"),title:a().optional(),description:a().optional(),enum:h(a()),default:a().optional()}),Ia=u({type:p("string"),title:a().optional(),description:a().optional(),oneOf:h(u({const:a(),title:a()})),default:a().optional()}),Ta=u({type:p("string"),title:a().optional(),description:a().optional(),enum:h(a()),enumNames:h(a()).optional(),default:a().optional()}),ka=R([za,Ia]),va=u({type:p("array"),title:a().optional(),description:a().optional(),minItems:g().optional(),maxItems:g().optional(),items:u({type:p("string"),enum:h(a())}),default:h(a()).optional()}),Pa=u({type:p("array"),title:a().optional(),description:a().optional(),minItems:g().optional(),maxItems:g().optional(),items:u({anyOf:h(u({const:a(),title:a()}))}),default:h(a()).optional()}),Ea=R([va,Pa]),Oa=R([Ta,ka,Ea]),Ua=R([Oa,Aa,xa,_a]),Ma=Ze.extend({mode:p("form").optional(),message:a(),requestedSchema:u({type:p("object"),properties:S(a(),Ua),required:h(a()).optional()})}),Ha=Ze.extend({mode:p("url"),message:a(),elicitationId:a(),url:a().url()}),ja=R([Ma,Ha]),qa=v.extend({method:p("elicitation/create"),params:ja}),Da=L.extend({elicitationId:a()}),La=G.extend({method:p("notifications/elicitation/complete"),params:Da}),Ga=P.extend({action:M(["accept","decline","cancel"]),content:lt(e=>e===null?void 0:e,S(a(),R([a(),g(),I(),h(a())])).optional())}),Na=u({type:p("ref/resource"),uri:a()});var Ba=u({type:p("ref/prompt"),name:a()}),Fa=H.extend({ref:R([Ba,Na]),argument:u({name:a(),value:a()}),context:u({arguments:S(a(),a()).optional()}).optional()}),$a=v.extend({method:p("completion/complete"),params:Fa});var Za=P.extend({completion:E({values:h(a()).max(100),total:C(g().int()),hasMore:C(I())})}),Va=u({uri:a().startsWith("file://"),name:a().optional(),_meta:S(a(),x()).optional()}),Wa=v.extend({method:p("roots/list"),params:H.optional()}),Ka=P.extend({roots:h(Va)}),Ya=G.extend({method:p("notifications/roots/list_changed"),params:L.optional()}),$d=R([Go,bi,$a,da,Ki,Zi,vi,Ei,Mi,Di,Gi,sa,ra,$o,Vo,Wo,Yo]),Zd=R([Lo,No,Ai,Ya,Fo]),Vd=R([Do,Ca,wa,Ga,Ka,Zo,Ko,Bo]),Wd=R([Go,ba,qa,Wa,$o,Vo,Wo,Yo]),Kd=R([Lo,No,ma,Bi,ji,ca,ta,Fo,La]),Yd=R([Do,wi,Za,ea,Vi,Pi,Oi,Hi,on,ia,Zo,Ko,Bo]),yt=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 bt(s.elicitations,o)}return new e(t,o,i)}},bt=class extends yt{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??[]}};O();var an=q,Ja=n.object({mode:n.literal("auto")}).strict(),Xa=n.object({mode:n.literal("manual"),clientId:n.string().trim().min(1),clientSecret:n.string().min(1).optional(),tokenEndpointAuthMethod:Rt.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"]})}),sn=n.discriminatedUnion("mode",[Ja,Xa]),Qa=sn.default({mode:"auto"}),es=n.object({scopes:n.array(n.string().min(1)).default([]),scopeDelimiter:n.string().min(1).default(" "),clientRegistration:Qa}).strict(),rn=es.extend({redirectPath:n.string().startsWith("/auth/connections/")}).strict(),ts=n.discriminatedUnion("mode",[n.object({mode:n.literal("shared-oauth"),oauth:rn}).strict(),n.object({mode:n.literal("user-oauth"),oauth:rn}).strict()]),os=n.object({baseUrl:n.url(),resourceMetadataUrl:n.url()}).strict(),np=n.object({displayName:n.string().min(1),description:n.string().min(1).optional(),serverInfo:me.optional(),transport:os}).strict(),ns=n.object({id:an,displayName:n.string().min(1),description:n.string().min(1).optional(),serverInfo:me.optional(),protectedResourceMetadataUrl:n.url().optional(),authMode:St,authConfig:ts}).strict().refine(e=>e.authMode===e.authConfig.mode,{message:"authMode must match authConfig.mode",path:["authConfig","mode"]}),rs={id:an.optional(),displayName:n.string().min(1),summary:n.string().min(1).optional(),serverInfo:me.optional(),protectedResourceMetadataUrl:n.url().optional()},is=n.object({...rs,authMode:St,scopes:n.array(n.string().min(1)).default([]),scopeDelimiter:n.string().min(1).default(" "),clientRegistration:sn.optional(),clientId:n.string().trim().min(1).optional(),clientSecret:n.string().min(1).optional(),tokenEndpointAuthMethod:Rt.optional()}).strict();function as(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
28
- `)}r(as,"formatZodIssues");function ss(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(ss,"inferUpstreamConnectionIdFromPolicyName");function cn(e){let t=new URL(e),o=t.pathname==="/"?"":t.pathname;return`${t.origin}/.well-known/oauth-protected-resource${o}`}r(cn,"buildDefaultProtectedResourceMetadataUrl");function un(e,t){return B.parse(`${e}:${t}`)}r(un,"buildUpstreamAuthProfileId");function cs(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(cs,"resolveAuthConfig");function dn(e,t){try{let o=is.parse(e),i=o.id??(t===void 0?void 0:ss(t));if(i===void 0)throw new f("MCP token exchange policy options must include id when policy name is unavailable.");return ns.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:cs(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
- ${as(o)}`,{cause:o})}throw o}}r(dn,"parseUpstreamTokenExchangePolicyOptions");function rp(e){return e.mode==="shared-oauth"||e.mode==="user-oauth"}r(rp,"isUpstreamOAuthAuthConfig");var us="mcp-token-exchange-inbound";function pn(e,t,o){let i=new f(t,o===void 0?void 0:{cause:o});return i.extensionMembers={[w]:e},i}r(pn,"configurationProblem");function mn(e){return e===us}r(mn,"isMcpTokenExchangePolicyType");function ds(e){let t=un(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??cn(e.mcpUrl),authMode:e.connection.authMode,authProfileId:t,authConfig:e.connection.authConfig}}r(ds,"buildRegisteredConnection");function ps(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(ps,"buildPolicyMap");function ms(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(ms,"readOperationId");function ls(e){let t=[];for(let o of e.route.policies?.inbound??[]){let i=e.policyByName.get(o);i&&mn(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],gt(e.route.handler))}r(ls,"readRouteUpstreamConnection");function hs(e){let t=new Map,o=new Map,i=new Map,s=new Set;function d(c,l){let y=i.get(c.name);if(y)return y;let _=dn(c.handler.options,c.name);if(s.has(_.id))throw new f(`Duplicate upstream MCP connection id ${_.id} in policies.json.`);s.add(_.id);let F=ds({policyName:c.name,connection:_,mcpUrl:l});return i.set(c.name,F),F}r(d,"readConnectionForPolicy");for(let c of e.routes){let l=c.policies?.inbound??[];if(l.length===0||!l.map(Y=>e.policyByName.get(Y)).filter(Y=>Y!==void 0).some(Y=>vo(Y.policyType)||mn(Y.policyType)))continue;let _=ms(c);if(t.has(_))throw new f(`Duplicate MCP route operationId ${_} across routes.`);if(o.has(c.path))throw new f(`Duplicate MCP route path ${c.path} across routes.`);let F=ls({route:c,policyByName:e.policyByName,readConnectionForPolicy:d}),ye={operationId:_,routePath:c.path,...F===void 0?{}:{connection:F}};t.set(_,ye),o.set(c.path,ye)}return{byOperationId:t,byRoutePath:o,connectionsByPolicyName:i}}r(hs,"buildMcpRoutes");function fs(e){let t=ps(e.policies),{byOperationId:o,byRoutePath:i,connectionsByPolicyName:s}=hs({routes:e.routes,policyByName:t}),d=new Map;for(let c of s.values())d.set(c.upstreamServerId,c);return{byOperationId:o,byRoutePath:i,connectionsById:d}}r(fs,"buildGatewayConnectionRegistry");var re,Tt;function lp(e){Tt=e,re=void 0}r(lp,"configureGatewayConnectionRegistrySource");function hp(e){re=e}r(hp,"setGatewayConnectionRegistry");function ln(){if(!re&&Tt&&(re=fs(Tt)),!re)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 re}r(ln,"getGatewayConnectionRegistry");function ie(e){let o=ln().byOperationId.get(e);if(!o)throw pn("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(ie,"getRegisteredMcpRoute");function We(e){let o=ln().byRoutePath.get(e);if(!o)throw pn("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(We,"getRegisteredMcpRouteByRoutePath");function fp(){return re}r(fp,"tryGetGatewayConnectionRegistry");O();var m=n.string().datetime({offset:!0}).brand();function hn(e){return m.parse(e.toISOString())}r(hn,"toIsoTimestamp");function yp(e,t){return new Date(e.getTime()+t*1e3)}r(yp,"addSeconds");O();function Ke(e,t){return e?.get(t)?.split(",",1)[0]?.trim()??""}r(Ke,"readHeaderValue");function gs(e){if(e===void 0)return"";let t=e.trim();return t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}r(gs,"unquoteForwardedValue");function Ss(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(),gs(y)])),d=s.proto,c=s.host;if(d||c)return{...d===void 0?{}:{proto:d},...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(Ss,"readForwardedOriginHints");function kt(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(kt,"parseHttpOrigin");function Rs(e,t){let o=Ke(t,"host");if(!o)return;let i=Ss(t);if(i.host!==void 0){let s=kt(i.proto??e.protocol.replace(/:$/u,""),i.host),d=kt(i.proto??e.protocol.replace(/:$/u,""),o);if(s!==void 0&&d!==void 0&&new URL(s).host!==new URL(d).host)return}return kt(i.proto??e.protocol.replace(/:$/u,""),o)}r(Rs,"readHostOrigin");function J(e,t){let o=new URL(e),i=Rs(o,t);return i!==void 0?i:o.origin}r(J,"readGatewayRequestOrigin");function Pe(e,t){return J(e,t)}r(Pe,"readGatewayOAuthIssuer");function vt(e){return e.length>512?`${e.slice(0,512)}\u2026`:e}r(vt,"truncate");function fn(e){return"cause"in e?e.cause:void 0}r(fn,"readCause");function Pt(e,t,o){if(!(o instanceof Error)){o!=null&&(e[`${t}Message`]=vt(String(o)));return}e[`${t}Name`]=o.name,e[`${t}Message`]=vt(o.message);let i=fn(o);for(let s=1;s<=4&&i instanceof Error;s+=1){let d=s===1?"cause":`cause${s}`;e[`${d}Name`]=i.name,e[`${d}Message`]=vt(i.message),i=fn(i)}}r(Pt,"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 gn(e,t){let o=Object.entries(t).filter(i=>i[1]!==void 0);o.length!==0&&e.log.setLogProperties?.(Object.fromEntries(o))}r(gn,"setLogProperties");function Et(e,t){gn(e,{subjectId:t.subjectId})}r(Et,"applyGatewayUserLogProperties");function Sn(e,t){gn(e,{upstreamServerId:t.upstreamServerId,operationId:t.operationId})}r(Sn,"applyGatewayRouteLogProperties");function Mp(e){let t=ne(e);return{title:t.title,body:t.publicDetail}}r(Mp,"readGatewayCallbackFailureContent");function Ye(e){if(!(e instanceof A))return;let t=e.extensionMembers?.[w];return oe(t)?t:void 0}r(Ye,"readGatewayProblemCode");function ae(e,t,o){let i=typeof e=="string"?{code:e,...t===void 0?{}:{publicDetail:t,privateDetail:t},...o===void 0?{}:{cause:o}}:e,s=ne(i.code),d=i.privateDetail??(Je(i.code)?i.publicDetail??s.publicDetail:s.publicDetail),c=ys(i);return new A({message:d,extensionMembers:{[w]:i.code}},c===void 0?void 0:{cause:c})}r(ae,"createGatewayRuntimeError");async function he(e,t,o){let i=ne(o.code),s=bs(o.code,o.detail),d=Je(o.code)?o.title??i.title:i.title,l={problem:{...we.getProblemFromStatus(i.status,{detail:s,instance:o.instance,type:o.type}),...o.extensions??{},status:i.status,title:d,detail:s,code:o.code}};return o.headers!==void 0&&(l.additionalHeaders=o.headers),we.format(l,e,t)}r(he,"gatewayProblemResponse");function Je(e){return ne(e).status<500}r(Je,"canExposeGatewayProblemDetail");function ys(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(ys,"readRuntimeErrorCause");function bs(e,t){let o=ne(e);return Je(e)&&t||o.publicDetail}r(bs,"readSafeGatewayProblemDetail");var Cs=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function ws(e){return e.protocol.replace(/:$/u,"").toLowerCase()}r(ws,"readScheme");function As(e){return e.protocol==="https:"}r(As,"isSpecCompliantRedirectUri");function xs(e){let t=ws(e);return t.length>0&&t!=="http"&&t!=="https"&&!Cs.has(t)}r(xs,"isNativeAppCustomSchemeRedirectUri");var yn=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:r(e=>As(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=>xs(e),"accepts")}];function Dp(e){let t=yn.find(o=>o.accepts(e.url,e.context));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}r(Dp,"evaluateBuiltInRedirectUriCompatibility");function Rn(e){try{return new URL(e)}catch{return}}r(Rn,"parseUrl");function bn(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=Rn(e.registeredRedirectUri),o=Rn(e.requestedRedirectUri);if(t===void 0||o===void 0)return!1;let i=e.context??{source:"registration_match"};return yn.some(s=>s.matches?.(t,o,i))}r(bn,"redirectUriMatchesBuiltInCompatibility");O();var _s=43,zs=128,Is=/^[A-Za-z0-9._~-]+$/,Ot="S256",Cn=n.literal(Ot),Bp=n.string().min(_s).max(zs).regex(Is);function Xe(e){return e.replace(/^\/+/,"").split("/").map(t=>encodeURIComponent(t)).join("/")}r(Xe,"encodeMcpRoutePathForScopedOAuthRoute");function wn(e){let t=typeof e=="string"?e:"";return t===""?"":`/${t.replace(/^\/+/,"")}`}r(wn,"decodeMcpRoutePathFromScopedOAuthParam");O();var An=["none","client_secret_post","client_secret_basic","private_key_jwt"],Ut=[...An],Ts=["awaiting_login","awaiting_setup"],ks=n.string().min(1).brand(),Z=n.string().min(1).brand(),Ee=n.uuid().brand(),V=n.uuid().brand(),vs=n.uuid().brand(),Ps=n.enum(An),Es=n.enum(Ut),Jp=n.enum(Ts),Xp=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:Es}).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."})}),Mt=n.object({clientId:Z,clientName:n.string().min(1),redirectUris:n.array(n.string().min(1)),tokenEndpointAuthMethod:Ps,jwksUri:n.string().min(1).optional(),hashedClientSecret:n.string().optional(),clientSecretExpiresAt:m.optional(),clientExpiresAt:m,revokedAt:m.optional(),createdAt:m}),Ht=n.object({clientId:Z,resource:n.string(),operationId:D,subjectId:ks,scope:n.string(),roles:n.array(n.string()),createdAt:m,expiresAt:m}),Qp=Ht.extend({id:V,redirectUri:n.string(),clientState:n.string().optional(),codeChallenge:n.string(),codeChallengeMethod:Cn}),jt=Ht.extend({id:Ee,currentRefreshTokenHash:n.string().optional(),previousRefreshTokenHash:n.string().optional(),previousRefreshTokenRotatedAt:m.optional(),revokedAt:m.optional(),revokedReason:n.string().optional()}),Qe=Ht.extend({tokenHash:n.string(),grantId:Ee,revokedAt:m.optional()});function em(){return V.parse(crypto.randomUUID())}r(em,"createDownstreamAuthorizationTransactionId");function tm(){return vs.parse(crypto.randomUUID())}r(tm,"createDownstreamBrowserLoginStateId");function om(){return Ee.parse(crypto.randomUUID())}r(om,"createDownstreamGrantId");var W="mcp:tools";function fm(e,t){return bn({registeredRedirectUri:e,requestedRedirectUri:t,context:{source:"registration_match"}})}r(fm,"redirectUriMatchesRegistration");function gm(e){return j(e)&&e.pathname==="/oauth/dev-login"}r(gm,"isLoopbackDevLoginUrl");function et(e,t,o){return new URL(e,Pe(t,o)).toString()}r(et,"buildGatewayOAuthUrl");function qt(e){let t=ie(D.parse(e.operationId));return new URL(t.routePath,J(e.requestUrl,e.requestHeaders)).toString()}r(qt,"buildScopedAuthorizationServerIssuer");function Os(e){let t=ie(D.parse(e.operationId));return new URL(`/oauth/authorize/${Xe(t.routePath)}`,J(e.requestUrl,e.requestHeaders)).toString()}r(Os,"buildScopedAuthorizationEndpoint");function Us(e,t){let o=Le();return{issuer:Pe(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:[Ot],token_endpoint_auth_methods_supported:Ut,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":wo(o)}}r(Us,"buildAuthorizationServerMetadata");function Sm(e){let t=qt(e);return{...Us(e.requestUrl,e.requestHeaders),issuer:t,authorization_endpoint:Os(e)}}r(Sm,"buildScopedAuthorizationServerMetadata");var xn=Uo;async function Tm(e,t){try{let o=Hs(e.params.routePath);return Response.json(Ms(o.operationId,e.url,e.headers))}catch(o){let i=Ye(o);return he(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(Tm,"protectedResourceMetadataHandler");function Ms(e,t,o){let i=ie(e);return{resource:Dt(i.operationId,t,o),resource_name:i.routePath,authorization_servers:[qt({operationId:i.operationId,requestUrl:t,requestHeaders:o})],bearer_methods_supported:["header"],scopes_supported:[W],mcp_protocol_version:xn}}r(Ms,"buildProtectedResourceMetadataResponseBody");function Dt(e,t,o){let i=ie(e);return new URL(i.routePath,J(t,o)).toString()}r(Dt,"buildCanonicalMcpResourceForRoute");function _n(e,t,o){let i=ie(e);return new URL(`/.well-known/oauth-protected-resource/${Xe(i.routePath)}`,J(t,o)).toString()}r(_n,"buildProtectedResourceMetadataUrlForRoute");function Hs(e){return We(wn(e))}r(Hs,"getRegisteredMcpRouteByExternalPathParam");O();var T=n.string().min(1).brand();var js=n.record(n.string(),n.unknown()),zn=n.string().min(1),qs=n.union([zn.transform(e=>[e]),n.array(zn)]);var Ds=["zuploSubjectId","zuplo_subject_id","gatewaySubjectId","gateway_subject_id","subjectId","subject_id","https://zuplo.com/subject_id"],Ls=["https://zuplo.com/roles","roles","role","permissions","groups"];function Gs(e){let t=js.safeParse(e);return t.success?t.data:{}}r(Gs,"toClaimRecord");function Ns(e){return e.issues[0]?.message??"Gateway request user is invalid"}r(Ns,"readValidationFailureDetail");function Bs(e,t,o,i){for(let c of Ds){let l=T.safeParse(t[c]);if(l.success)return l.data}let s=T.safeParse(e?.sub);if(!s.success)throw ae("identity_context_missing",Ns(s.error));let d=typeof t.iss=="string"?t.iss:void 0;return!d||d===Pe(o,i)?s.data:T.parse(`${d}|${s.data}`)}r(Bs,"readNormalizedSubjectId");function Fs(e){let t=new Set;for(let o of Ls){let i=qs.safeParse(e[o]);if(i.success)for(let s of i.data)t.add(s)}return t.size>0?[...t]:void 0}r(Fs,"readRoles");function $s(e,t,o){let i=Gs(e?.data),s={subjectId:Bs(e,i,t,o)},d=Fs(i);return d&&(s.roles=d),s}r($s,"parseGatewayRequestUser");function In(e,t,o){try{return $s(e,t,o)}catch{return}}r(In,"tryParseGatewayRequestUser");function tt(e){let o=['realm="OAuth"',`resource_metadata="${Lt(_n(e.operationId,e.requestUrl,e.requestHeaders))}"`];return e.error!==void 0&&o.push(`error="${e.error}"`),e.errorDescription!==void 0&&o.push(`error_description="${Lt(e.errorDescription)}"`),e.scope!==void 0&&o.push(`scope="${Lt(e.scope)}"`),`Bearer ${o.join(", ")}`}r(tt,"buildGatewayBearerChallenge");function Lt(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(Lt,"sanitizeQuotedHeaderParameter");O();O();function Tn(e){return new A({message:e,extensionMembers:{[w]:"invalid_request"}})}r(Tn,"invalidReturnTo");function kn(e){if(e===void 0||e.length===0)return;if(!e.startsWith("/")||e.startsWith("//"))throw Tn("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 Tn("returnTo must be a same-origin relative path without credentials or fragments.");return`${t.pathname}${t.search}`}r(kn,"parseSafeRelativeReturnTo");O();var Zs=["user","shared"],fe=n.enum(Zs);function vn(e){return{mode:"user",subjectId:e}}r(vn,"buildUserUpstreamConnectionOwner");function Pn(){return{mode:"shared"}}r(Pn,"buildSharedUpstreamConnectionOwner");var En=n.object({ownerMode:fe,initiatedBySubjectId:T,ownerSubjectId:T.optional(),upstreamServerId:q,authProfileId:B,operationId:D,returnTo:n.string().min(1).transform(e=>kn(e)).optional()});function On(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(On,"validateUpstreamOwnerState");var Gt=En.superRefine(On),ol=En.omit({returnTo:!0}).superRefine(On);function nl(e){return Gt.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(nl,"buildUpstreamOwnerState");function rl(e){if(e.ownerMode==="shared")return Pn();if(!e.ownerSubjectId)throw new A({message:"User-owned upstream state is missing the owner subject.",extensionMembers:{[w]:"oauth_state_invalid"}});return vn(e.ownerSubjectId)}r(rl,"resolveUpstreamConnectionOwnerFromState");var Vs=["active","not_connected","reconsent_required"],Ws=["basic_auth_app_password","bearer_token"],Un=n.string().trim().min(1).brand(),ot=n.uuid().brand(),Nt=n.uuid().brand(),Bt=n.enum(Vs),Ks=n.enum(Ws),Mn=n.object({encryptedClientInformation:n.string().optional(),encryptedDiscoveryState:n.string().optional(),connectedBySubjectId:T.optional()}),Ys=Mn.extend({encryptedStaticSecret:n.string().optional(),staticSecretKind:Ks.optional(),staticSecretLabel:n.string().min(1).optional(),staticSecretUsername:n.string().min(1).optional()}).strict(),Js=n.object({id:Un,subjectId:T.optional(),ownerMode:fe,upstreamServerId:q,authProfileId:B,status:Bt,encryptedAccessToken:n.string().min(1).optional(),encryptedRefreshToken:n.string().min(1).optional(),scopes:n.array(n.string()),expiresAt:m.optional(),metadata:Ys.optional(),createdAt:m,updatedAt:m});function Ft(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(Ft,"validateUpstreamConnectionOwnerShape");var ge=Js.superRefine(Ft);function Hn(e){return JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId])}r(Hn,"readUpstreamConnectionLookupKey");var $t=Gt.extend({id:ot,callbackPath:n.string().min(1),expiresAt:m,codeVerifier:n.string().optional(),redirectUri:n.url(),returnOrigin:n.url().optional()}).extend(Mn.shape);function ll(e){let t=e?.status??"not_connected",o={connected:t==="active",status:t};return e?.updatedAt!==void 0&&(o.updatedAt=e.updatedAt),o}r(ll,"readUpstreamConnectionStatus");function hl(){return Un.parse(`mcpgw2uc_${crypto.randomUUID()}`)}r(hl,"createUpstreamConnectionId");function fl(){return ot.parse(crypto.randomUUID())}r(fl,"createOAuthStateId");function gl(){return Nt.parse(crypto.randomUUID())}r(gl,"createBrowserConnectTicketId");O();var Vt=n.discriminatedUnion("mode",[n.object({mode:n.literal("user"),subjectId:T}).strict(),n.object({mode:n.literal("shared")}).strict()]),qn=n.object({owner:Vt,upstreamServerId:q,authProfileId:B}).strict(),Dn=n.object({items:n.array(qn).min(1).max(100)}).strict(),Wt=n.object({items:n.array(n.object({key:n.object({ownerMode:fe,subjectId:T.optional(),upstreamServerId:q,authProfileId:B}).strict(),connection:ge.strict().optional()}).strict())}).strict(),Ln=ge.omit({createdAt:!0,updatedAt:!0}).strict().superRefine(Ft),Gn=ge.strict(),Nn=n.object({owner:Vt,upstreamServerId:q,authProfileId:B}).strict(),Bn=n.object({owner:Vt,upstreamServerId:q,authProfileId:B,connection:ge.strict().optional(),connectionStatus:n.object({connected:n.boolean(),status:Bt,updatedAt:ge.shape.updatedAt.optional()}).strict()}).strict(),Xs=n.enum(["none","client_secret_basic","client_secret_post","private_key_jwt"]),se=n.object({clientId:Z,clientName:n.string().min(1),tokenEndpointAuthMethod:Xs}).strict(),Kt=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()]),Yt=n.object({id:V,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(),jn=Yt.omit({id:!0,consumedAt:!0}).extend({transactionId:V,client:se.optional()}).strict(),Jt=n.object({subjectId:T,roles:n.array(n.string()).optional()}).strict(),Qs=Yt.extend({phase:n.literal("awaiting_login")}).strict(),Zt=Yt.extend({phase:n.literal("awaiting_setup"),principal:Jt}).strict(),ec=n.discriminatedUnion("phase",[Qs,Zt]),nt=n.object({transaction:ec,client:se}).strict(),Fn=Mt.omit({revokedAt:!0}).strict(),$n=n.discriminatedUnion("kind",[n.object({kind:n.literal("registered"),client:se}).strict(),n.object({kind:n.literal("already_exists")}).strict()]),Zn=n.object({clientId:Z}).strict(),Vn=n.discriminatedUnion("kind",[n.object({kind:n.literal("found"),client:Mt.strict()}).strict(),n.object({kind:n.literal("missing")}).strict()]),Wn=n.discriminatedUnion("phase",[jn.extend({phase:n.literal("awaiting_login")}).strict(),jn.extend({phase:n.literal("awaiting_setup"),principal:Jt}).strict()]),Kn=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()]),Yn=n.object({transactionId:V,currentStateHash:n.string().min(1),now:m}).strict(),Jn=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()]),Xn=n.object({transactionId:V,expectedPhase:n.literal("awaiting_login"),currentStateHash:n.string().min(1),nextStateHash:n.string().min(1),nextPhase:n.literal("awaiting_setup"),principal:Jt,now:m}).strict(),Qn=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()]),er=n.object({transactionId:V,currentStateHash:n.string().min(1),currentPrincipal:n.object({subjectId:T}).strict(),now:m}).strict(),tr=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()]),or=n.discriminatedUnion("decision",[n.object({decision:n.literal("approve"),transactionId:V,currentStateHash:n.string().min(1),currentPrincipal:n.object({subjectId:T}).strict(),authorizationCodeHash:n.string().min(1),authorizationCodeExpiresAt:m,grantId:Ee,now:m}).strict(),n.object({decision:n.literal("cancel"),transactionId:V,currentStateHash:n.string().min(1),currentPrincipal:n.object({subjectId:T}).strict(),now:m}).strict()]),nr=n.discriminatedUnion("kind",[n.object({kind:n.literal("approved"),transaction:Zt,client:se}).strict(),n.object({kind:n.literal("cancelled"),transaction:Zt,client:se}).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()]),rr=n.object({clientAuth:Kt,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(),ir=n.discriminatedUnion("kind",[n.object({kind:n.literal("exchanged"),client:se,grant:jt.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()]),ar=n.object({clientAuth:Kt,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(),sr=n.discriminatedUnion("kind",[n.object({kind:n.literal("rotated"),client:se,grant:jt.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()]),cr=n.object({clientAuth:Kt,tokenHash:n.string().min(1),now:m}).strict(),ur=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()]),dr=n.object({tokenHash:n.string().min(1),now:m}).strict(),pr=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()]),mr=n.object({accessTokenHash:n.string().min(1),resource:n.string().min(1),operationId:D,upstreamConnectionKeys:n.array(qn).max(100),now:m}).strict(),lr=n.discriminatedUnion("kind",[n.object({kind:n.literal("authorized"),principal:n.object({subjectId:T,roles:n.array(n.string())}).strict(),accessToken:Qe.strict(),upstreamConnections:Wt.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()]),hr=n.object({record:$t}).strict(),fr=n.object({kind:n.literal("saved")}).strict(),gr=n.object({id:ot,now:m}).strict(),Sr=n.discriminatedUnion("kind",[n.object({kind:n.literal("available"),record:$t}).strict(),n.object({kind:n.literal("consumed")}).strict(),n.object({kind:n.literal("missing")}).strict()]),Rr=n.object({id:Nt,expiresAt:m,now:m}).strict(),yr=n.discriminatedUnion("kind",[n.object({kind:n.literal("available")}).strict(),n.object({kind:n.literal("consumed")}).strict()]);var br=100,tc=new Set(["undefined","null","nan"]);function Cr(e){return e!==null&&typeof e=="object"}r(Cr,"isProblemDetailsShape");var wr="bckt_";function k(e){let t=Ue.instance.runtime.ZUPLO_SERVICE_BUCKET_ID;if(!t)throw ce("internal_server_error","MCP Gateway runtime storage requires ZUPLO_SERVICE_BUCKET_ID.");if(!t.startsWith(wr))throw ce("internal_server_error",`MCP Gateway runtime storage bucket ID must start with "${wr}".`);return`/zups/v2/buckets/${encodeURIComponent(t)}/mcp/storage/${e}`}r(k,"buildStoragePath");function oc(){return k("upstream-connections/batch-get")}r(oc,"buildBatchGetUpstreamConnectionsPath");function nc(){return k("upstream-connections/upsert")}r(nc,"buildUpsertUpstreamConnectionPath");function rc(){return k("authorization/read-setup")}r(rc,"buildReadAuthorizationSetupPath");function ic(){return k("oauth/register-client")}r(ic,"buildRegisterClientPath");function ac(){return k("oauth/read-client")}r(ac,"buildReadClientPath");function sc(){return k("authorization/start")}r(sc,"buildStartAuthorizationPath");function cc(){return k("authorization/read-pending")}r(cc,"buildReadPendingAuthorizationPath");function uc(){return k("authorization/advance-pending")}r(uc,"buildAdvancePendingAuthorizationPath");function dc(){return k("authorization/mark-setup-approved")}r(dc,"buildMarkAuthorizationSetupApprovedPath");function pc(){return k("authorization/decide-setup")}r(pc,"buildDecideAuthorizationSetupPath");function mc(){return k("token/exchange-authorization-code")}r(mc,"buildExchangeAuthorizationCodePath");function lc(){return k("token/refresh")}r(lc,"buildRefreshTokenPath");function hc(){return k("token/revoke")}r(hc,"buildRevokeOAuthTokenPath");function fc(){return k("token/validate-access-token")}r(fc,"buildValidateAccessTokenPath");function gc(){return k("mcp/authorize-and-load-connections")}r(gc,"buildAuthorizeAndLoadConnectionsPath");function Sc(){return k("upstream-oauth-state/save")}r(Sc,"buildSaveUpstreamOAuthStatePath");function Rc(){return k("upstream-oauth-state/consume")}r(Rc,"buildConsumeUpstreamOAuthStatePath");function yc(){return k("browser-connect-ticket/consume")}r(yc,"buildConsumeBrowserConnectTicketPath");function bc(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(bc,"responseKeyMatchesLookup");function Cc(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(Cc,"authorizationSetupMatchesLookup");function _r(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(_r,"connectionMatchesLookup");function wc(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??"")&&eo(e.scopes,t.scopes)&&Qt(e.expiresAt,t.expiresAt)&&Ac(e.metadata,t.metadata)}r(wc,"connectionMatchesUpsertRecord");function Qt(e,t){return e===void 0||t===void 0?e===t:Date.parse(e)===Date.parse(t)}r(Qt,"optionalTimestampInstantsMatch");function Ar(e,t){return Date.parse(e)<=Date.parse(t)}r(Ar,"timestampInstantIsAtOrBefore");function eo(e,t){return e.length===t.length&&e.every((o,i)=>o===t[i])}r(eo,"stringArraysMatch");function Ac(e,t){let o=xr(e),i=xr(t),s=Object.fromEntries(i);return o.length===i.length&&o.every(([d,c])=>s[d]===c)}r(Ac,"metadataMatches");function xr(e){return Object.entries(e??{}).filter(t=>t[1]!==void 0)}r(xr,"definedMetadataEntries");function b(e,t){throw ce("internal_server_error",e,t)}r(b,"throwInvalidStorageResponse");function ce(e,t,o){let i=Ne[e],s=i.status<500,d=s?o:new Error(t,o===void 0?void 0:{cause:o});return new A({message:s?t:i.publicDetail,extensionMembers:{[w]:e}},d===void 0?void 0:{cause:d})}r(ce,"storageRuntimeError");async function xc(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(xc,"parseRuntimeHttpStorageResponse");function zr(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];bc(i.key,s)||b("Gateway Service storage response key did not match the request."),i.connection!==void 0&&!_r(i.connection,s)&&b("Gateway Service storage response connection did not match the response key.")}}r(zr,"validateUpstreamConnectionItemsMatchLookups");function _c(e,t){Cc(e,t)||b("Gateway Service storage response authorization setup did not match the request."),e.connection!==void 0&&!_r(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||!Qt(e.connectionStatus.updatedAt,s))&&b("Gateway Service storage response authorization setup status did not match the connection.")}r(_c,"validateAuthorizationSetupResponseMatchesLookup");function zc(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(zc,"validateRegisterClientResponseMatchesRequest");function Ic(e,t){e.kind==="found"&&e.client.clientId!==t.clientId&&b("Gateway Service storage response client did not match the request.")}r(Ic,"validateReadClientResponseMatchesRequest");function Tc(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(Tc,"validateStartAuthorizationResponseMatchesRequest");function Xt(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(Xt,"validatePendingAuthorizationResponseMatchesRequest");function kc(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(kc,"validateAuthorizationSetupDecisionResponseMatchesRequest");function vc(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||!Qt(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(vc,"validateExchangeAuthorizationCodeResponseMatchesRequest");function Pc(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||!Ar(e.accessToken.expiresAt,t.accessTokenExpiresAt)||!Ar(e.accessToken.expiresAt,e.grant.expiresAt)||!Uc(e.accessToken,e.grant))&&b("Gateway Service storage response token refresh access token did not match the request."))}r(Pc,"validateRefreshTokenResponseMatchesRequest");function Ec(e,t){e.kind==="valid"&&e.record.tokenHash!==t.tokenHash&&b("Gateway Service storage response access token did not match the request.")}r(Ec,"validateAccessTokenValidationResponseMatchesRequest");function Oc(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||!eo(e.principal.roles,e.accessToken.roles))&&b("Gateway Service storage response MCP authorization did not match the request."),zr(e.upstreamConnections,t.upstreamConnectionKeys))}r(Oc,"validateAuthorizeAndLoadConnectionsResponseMatchesRequest");function Uc(e,t){return e.clientId===t.clientId&&e.resource===t.resource&&e.operationId===t.operationId&&e.subjectId===t.subjectId&&e.scope===t.scope&&eo(e.roles,t.roles)}r(Uc,"accessTokenMatchesGrant");async function Mc(e){try{return await e.clone().json()}catch{return}}r(Mc,"readProblemDetails");async function Hc(e){let t=await Mc(e),o=Cr(t)&&typeof t.status=="number"?t.status:e.status,i=Cr(t)&&oe(t.code)?t.code:Po(o);throw ce(i,`Gateway Service storage request failed with HTTP ${o}.`)}r(Hc,"throwRuntimeHttpStorageError");var rt=class{static{r(this,"RuntimeHttpStorageClient")}#t;#o;constructor(t){this.#t=t.baseUrl??Ue.instance.zuploEdgeApiUrl,this.#o=t.fetch??fetch}#n(t){let o;try{o=new URL(t,this.#t)}catch(i){throw ce("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 ce("internal_server_error",`Gateway Service storage base URL must use http(s); got protocol "${o.protocol}" from ${JSON.stringify(this.#t)}.`);if(!o.hostname||tc.has(o.hostname))throw ce("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"});mo(s);let d=await this.#o(i,{method:"POST",headers:s,body:JSON.stringify(o)});return d.ok||await Hc(d),{request:o,response:await xc(d,t.responseSchema)}}async batchGetUpstreamConnections(t){if(t.length===0)return[];let o=[],i=new Map,s=t.map(c=>{let l=Hn(c),y=i.get(l);if(y!==void 0)return y;let _=o.length;return o.push(c),i.set(l,_),_}),d=[];for(let c=0;c<o.length;c+=br){let l=o.slice(c,c+br);d.push(...await this.#r(l))}return s.map(c=>d[c])}async upsertUpstreamConnection(t){let{request:o,response:i}=await this.#e({input:t,path:nc(),requestSchema:Ln,responseSchema:Gn});return wc(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:rc(),requestSchema:Nn,responseSchema:Bn});return _c(i,o),i}async registerClient(t){let{request:o,response:i}=await this.#e({input:t,path:ic(),requestSchema:Fn,responseSchema:$n});return zc(i,o),i}async readClient(t){let{request:o,response:i}=await this.#e({input:t,path:ac(),requestSchema:Zn,responseSchema:Vn});return Ic(i,o),i}async startAuthorization(t){let{request:o,response:i}=await this.#e({input:t,path:sc(),requestSchema:Wn,responseSchema:Kn});return Tc(i,o),i}async readPendingAuthorization(t){let{request:o,response:i}=await this.#e({input:t,path:cc(),requestSchema:Yn,responseSchema:Jn});return Xt(i,o),i}async advancePendingAuthorization(t){let{request:o,response:i}=await this.#e({input:t,path:uc(),requestSchema:Xn,responseSchema:Qn});return Xt(i,o),i}async markAuthorizationSetupApproved(t){let{request:o,response:i}=await this.#e({input:t,path:dc(),requestSchema:er,responseSchema:tr});return Xt(i,o),i}async decideAuthorizationSetup(t){let{request:o,response:i}=await this.#e({input:t,path:pc(),requestSchema:or,responseSchema:nr});return kc(i,o),i}async saveUpstreamOAuthState(t){let{response:o}=await this.#e({input:t,path:Sc(),requestSchema:hr,responseSchema:fr});return o}async consumeUpstreamOAuthState(t){let{request:o,response:i}=await this.#e({input:t,path:Rc(),requestSchema:gr,responseSchema:Sr});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:yc(),requestSchema:Rr,responseSchema:yr});return o}async exchangeAuthorizationCode(t){let{request:o,response:i}=await this.#e({input:t,path:mc(),requestSchema:rr,responseSchema:ir});return vc(i,o),i}async refreshToken(t){let{request:o,response:i}=await this.#e({input:t,path:lc(),requestSchema:ar,responseSchema:sr});return Pc(i,o),i}async revokeOAuthToken(t){let{response:o}=await this.#e({input:t,path:hc(),requestSchema:cr,responseSchema:ur});return o}async validateAccessToken(t){let{request:o,response:i}=await this.#e({input:t,path:fc(),requestSchema:dr,responseSchema:pr});return Ec(i,o),i}async authorizeAndLoadConnections(t){let{request:o,response:i}=await this.#e({input:t,path:gc(),requestSchema:mr,responseSchema:lr});return Oc(i,o),i}async#r(t){let o={items:[...t]},{response:i}=await this.#e({input:o,path:oc(),requestSchema:Dn,responseSchema:Wt});return zr(i.items,t),i.items.map(s=>s.connection)}};var jc="__zuploMcpGatewayStorageBackend",to;function qc(){return new rt({})}r(qc,"buildProductionStorageBackend");function Ir(){let e=globalThis[jc];return e||(to||(to=qc()),to)}r(Ir,"getStorage");function Dc(e,t){let o=qe(e),i=t.ownerMode??t.routeBinding?.ownerMode,s=t.upstreamAuthMode??t.routeBinding?.authMode,d=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 So(e,{...t,subjectId:t.subjectId??t.routeBinding?.initiatedBySubjectId,ownerMode:i,upstreamAuthMode:s,virtualServerName:d,upstreamServerName:c,upstreamServerTitle:l,authProfileId:y})}r(Dc,"buildMcpAnalyticsMetadata");function N(e,t){try{e.analyticsContext.addAnalyticsEvent(t.value??1,t.eventType,Dc(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 oo}from"jose";var Lc="sha256:",Gc=32;function Tr(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}r(Tr,"copyToArrayBuffer");function oh(){let e=crypto.getRandomValues(new Uint8Array(Gc));return oo.encode(e)}r(oh,"createOpaqueToken");async function kr(e){let t=await crypto.subtle.digest("SHA-256",Tr(new TextEncoder().encode(e)));return`${Lc}${oo.encode(new Uint8Array(t))}`}r(kr,"hashOpaqueValue");async function nh(e){let t=await crypto.subtle.digest("SHA-256",Tr(new TextEncoder().encode(e)));return oo.encode(new Uint8Array(t))}r(nh,"calculatePkceS256Challenge");function Nc(e){let t=e.headers.get("authorization"),[o,i]=t?.split(/\s+/,2)??[];if(!(o?.toLowerCase()!=="bearer"||!i))return i}r(Nc,"readBearerToken");function Bc(e,t,o){return he(e,t,{code:"authentication_required",detail:"Gateway access token is required.",headers:{"WWW-Authenticate":o}})}r(Bc,"gatewayAuthenticationRequiredResponse");function Fc(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(Fc,"tokenValidationReasonCode");async function $c(e,t,o){let i=await Ir().validateAccessToken({tokenHash:await kr(e),now:hn(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=Fc(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}),ae("authentication_required","Gateway access token is expired, revoked, or invalid.")}return i.record}r($c,"validateGatewayAccessToken");function Zc(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"}),ae("authentication_required","Gateway access token was not issued for this MCP resource.")}r(Zc,"assertAccessTokenResource");function Vc(e,t,o){return he(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(Vc,"insufficientScopeResponse");function Wc(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(Wc,"userDataFromAccessToken");function Kc(e){let t=new Headers(e.headers);return t.delete("authorization"),new lo(e,{headers:t,...e.user===void 0?{}:{user:e.user}})}r(Kc,"stripDownstreamAuthorizationHeader");function Yc(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"),he(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(Yc,"gatewayTokenRejectedResponse");async function no(e,t,o){let i=Dt(o.operationId,e.url,e.headers),s=Nc(e),d=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"}),Bc(e,t,d);try{let c=await $c(s,t,o.operationId);return Zc({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"}),Vc(e,t,o.operationId)):(e.user={sub:c.subjectId,data:Wc(c)},Et(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}}),Kc(e))}catch(c){return Yc({request:e,context:t,error:c,operationId:o.operationId})}}r(no,"gatewayTokenInbound");var Se={OAUTH_PROTECTED_RESOURCE_METADATA:"oauth_metadata",VIRTUAL_MCP_SERVER:"gateway",OTHER:"other"},Jc="oauth-protected-resource-metadata",Xc="/.well-known/oauth-protected-resource/";function Qc(e){let o=(typeof e.route.raw=="function"?e.route.raw():void 0)?.operationId;return typeof o=="string"?o:void 0}r(Qc,"readRouteOperationId");function eu(e){return e.hasGatewayRouteContext?Se.VIRTUAL_MCP_SERVER:e.routeOperationId===Jc||e.routeOperationId===void 0&&e.routePath.startsWith(Xc)?Se.OAUTH_PROTECTED_RESOURCE_METADATA:Se.OTHER}r(eu,"classifyAnalyticsRouteSurface");function tu(e){let t=e.route.path;return{routePath:t,routeSurface:eu({routePath:t,routeOperationId:Qc(e),hasGatewayRouteContext:qe(e)!==void 0})}}r(tu,"readAnalyticsRequestContext");function ou(e){return e.response.status===405&&e.response.headers.has("allow")&&e.routeSurface===Se.VIRTUAL_MCP_SERVER}r(ou,"isIntentionalMethodRejection");function nu(e){return ou(e)||e.response.status===401&&e.routeSurface===Se.OAUTH_PROTECTED_RESOURCE_METADATA?"success":e.response.status>=400?"failure":"success"}r(nu,"classifyRequestCompletedOutcome");function vr(e){return In(e.user,e.url,e.headers)?.subjectId}r(vr,"readRequestSubjectId");async function ro(e,t){let o=Date.now(),i=tu(t);return N(t,{eventType:U.MCP_REQUEST_RECEIVED,outcome:"success",routeSurface:i.routeSurface,httpMethod:e.method,subjectId:vr(e)}),dt.getContextExtensions(t).addHandlerResponseHook((s,d)=>{let c=nu({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:vr(d)})}),e}r(ro,"analyticsContextInbound");function ru(e){return e instanceof Response}r(ru,"isResponse");async function _e(e,t){let o=We(t.route.path),i={operationId:o.operationId};yo(t,i),Sn(t,i);let s=await ro(e,t);return ru(s)?s:no(s,t,{operationId:o.operationId})}r(_e,"mcpOAuthInboundPolicy");var Pr=class extends He{static{r(this,"McpOAuthInboundPolicy")}constructor(t,o){let i=ft(t,o);super(i,o)}async handler(t,o){return Me("policy.inbound.mcp-oauth"),De(o,this.options),_e(t,o)}};function ft(e,t="mcp-oauth-inbound"){return Ge(ht,e,`MCP OAuth policy "${t}"`)}r(ft,"mcpOAuthOptionsToRuntimeConfig");function K(e){return new A({message:e,extensionMembers:{[w]:"invalid_request"}})}r(K,"invalidOutboundUrl");function iu(){let e=ue.__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(iu,"isTestOnlyAllowHttpLoopbackIdpEnabled");function au(){let e=ue.__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(au,"isTestOnlyAllowHttpLoopbackCimdEnabled");var su=new Set(["undefined","null","nan"]);function ao(e,t){if(!e.hostname)throw K(`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(su.has(e.hostname.toLowerCase()))throw K(`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(ao,"assertSafeOutboundHostname");var cu=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),uu=[{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 Er(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(Er,"parseIpv4Octets");function du([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(du,"ipv4RangeMatches");function Or(e){let t=Er(e);return t!==void 0&&uu.some(o=>du(t,o))}r(Or,"isPrivateIpv4");function io(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(io,"parseIpv6Word");function pu(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}r(pu,"formatIpv4FromWords");function mu(e){let t=e.slice(7),o=Er(t);if(o!==void 0)return o.join(".");let[i,s,d]=t.split(":"),c=io(i),l=io(s);return d===void 0&&c!==void 0&&l!==void 0?pu(c,l):void 0}r(mu,"parseIpv6MappedIpv4");function lu(e){return io(e.split(":").find(Boolean))}r(lu,"readFirstIpv6Hextet");function hu(e){let t=te(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let i=mu(t);return i===void 0||Or(i)}let o=lu(t);return o===void 0?!1:(o&65024)===64512||(o&65472)===65152}r(hu,"isPrivateIpv6");function so(e){let t=te(e);return cu.has(t)||t.endsWith(".internal")||Or(t)||hu(t)}r(so,"isBlockedOutboundHostname");function Ur(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw K(`Unsupported outbound protocol: ${t.protocol}`);ao(t,e);let o=j(t);if(t.protocol==="http:"&&!o)throw K("Configured outbound HTTP URLs must target loopback hosts.");let i=te(t.hostname);if(!o&&so(i))throw K(`Blocked outbound host: ${i}`);return t}r(Ur,"validateConfiguredOutboundUrl");function Mr(e){let t=new URL(e),o=j(t),i=o&&iu();if(t.protocol!=="https:"&&!i)throw K("Identity provider URLs must use https.");if(t.username||t.password||t.search||t.hash)throw K("Identity provider URLs must not include credentials, query params, or fragments.");ao(t,e);let s=te(t.hostname);if(!o&&so(s))throw K(`Blocked identity provider host: ${s}`);return t}r(Mr,"validateIdentityProviderUrl");function Hr(e,t){let o=new URL(e),i=o.protocol==="http:"&&j(o)&&au();if(o.protocol!=="https:"&&!i||o.pathname==="/"||o.username||o.password||o.search||o.hash)throw K(`CIMD ${t} must be an HTTPS URL with a path and no credentials, query, or fragment.`);if(ao(o,e),!i&&so(o.hostname))throw K(`CIMD ${t} points at a blocked host.`);return o}r(Hr,"validateCimdUrl");function jr(e){return Hr(e,"client_id")}r(jr,"validateCimdClientMetadataUrl");function qr(e){return Hr(e,"jwks_uri")}r(qr,"validateCimdClientJwksUrl");function Dr(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(Dr,"mergeAbortSignals");async function fu(e){try{await e.cancel()}catch{}}r(fu,"cancelReader");async function Lr(e,t){if(!e)return new Uint8Array;let o=e.getReader(),i=[],s=0,d=await o.read();for(;!d.done;){let y=d.value;if(s+=y.byteLength,s>t.maxBytes)throw await fu(o),t.createLimitError();i.push(y),d=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(Lr,"readBoundedByteStream");var gu=2,Su=1024*1024,Ru=1e4,yu=new Set([301,302,303,307,308]),bu=["authorization","proxy-authorization","cookie","cookie2"];function co(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}r(co,"readRequestUrl");function Re(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}r(Re,"readRequestMethod");function Cu(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(Cu,"assertContentLengthWithinLimit");async function wu(e,t,o){return Cu(e,t,o),Lr(e.body,{maxBytes:t,createLimitError:r(()=>new A({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[w]:o}}),"createLimitError")})}r(wu,"readBoundedResponseBody");function Au(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(Au,"responseFromBufferedBody");function xu(e,t){if(!yu.has(e.status))return;let o=e.headers.get("location");if(o)return new URL(o,t).toString()}r(xu,"resolveRedirectUrl");function Gr(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(Gr,"validateOutboundUrl");function _u(e,t){throw e instanceof A&&oe(e.extensionMembers?.[w])?e:new A({message:"Outbound fetch failed.",extensionMembers:{[w]:t}},{cause:e})}r(_u,"normalizeFetchError");function Oe(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&&Pt(o,"error",t.error),e.log.warn(o,"Outbound HTTP exchange rejected")}r(Oe,"logOutboundFailure");async function zu(e,t,o,i,s,d,c){let l=Re(o,i);try{return await t(o,i)}catch(y){let _=y instanceof DOMException&&y.name==="AbortError";Oe(e,{event:_?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:s,method:l,host:X(d),error:y,extra:{abortReason:c()}}),_u(y,s)}}r(zu,"fetchWithNormalizedError");function Iu(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(Iu,"assertRedirectAllowed");function Tu(e,t){let o=new Headers(e);for(let i of bu)o.delete(i);for(let i of t)o.delete(i);return o}r(Tu,"stripCrossOriginHeaders");function ku(e,t,o,i,s){let d={...e,method:t,redirect:"manual",signal:o};return i&&(d.headers=Tu(e.headers,s)),d}r(ku,"buildRedirectInit");function vu(e,t,o){let i={...t,redirect:"manual",signal:o};return i.headers===void 0&&e instanceof Request&&(i.headers=e.headers),i}r(vu,"buildInitialRequestInit");function Pu(e){let t=Re(e.currentInput,e.currentInit);Iu({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let o=Gr(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),i=new URL(e.currentUrl),s=o.origin!==i.origin,d=o.toString();return{currentInput:d,currentUrl:d,currentInit:ku(e.currentInit,t,e.signal,s,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}r(Pu,"followRedirect");async function uo(e,t,o){let i=o.problemCode??"invalid_request",s=o.maxRedirects??gu,d=o.maxResponseBytes??Su,c=o.timeoutMs??Ru,l=o.fetchImpl??fetch,y=o.additionalCrossOriginStrippedHeaders??[],_=o.context,F=new AbortController,ye=Dr(F,t.signal),Y=!1,po=setTimeout(()=>{Y=!0,F.abort()},c),be=e,Ce=vu(e,t,F.signal),Q;try{Q=Gr(co(e),{problemCode:i,validateUrl:o.validateUrl}).toString()}catch(ee){throw Oe(_,{event:"outbound_url_blocked",problemCode:i,method:Re(e,t),host:X(co(e)),error:ee}),clearTimeout(po),ye?.(),ee}let at=0;try{for(;;){let ee=await zu(_,l,be,Ce,i,Q,()=>Y?`timeout_after_${c}ms`:void 0),st=xu(ee,Q);if(st!==void 0)try{let $=Pu({currentInput:be,currentInit:Ce,currentUrl:Q,redirectUrl:st,redirects:at,maxRedirects:s,problemCode:i,validateUrl:o.validateUrl,signal:F.signal,additionalCrossOriginStrippedHeaders:y});be=$.currentInput,Ce=$.currentInit,Q=$.currentUrl,at=$.redirects;continue}catch($){throw Oe(_,{event:"outbound_redirect_blocked",problemCode:i,method:Re(be,Ce),host:X(Q),error:$,extra:{redirects:at,maxRedirects:s,redirectTargetHost:X(st)}}),$}try{return Au(ee,await wu(ee,d,i))}catch($){throw Oe(_,{event:"outbound_response_size_exceeded",problemCode:i,method:Re(be,Ce),host:X(Q),error:$,extra:{maxResponseBytes:d,status:ee.status}}),$}}}finally{clearTimeout(po),ye?.()}}r(uo,"runSafeOutboundExchange");async function it(e,t,o){let i=await uo(e,t,o);try{return{response:i,json:await i.clone().json()}}catch(s){throw Oe(o.context,{event:"outbound_json_parse_failed",problemCode:o.problemCode??"invalid_request",method:Re(e,t),host:X(co(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 rf(e,t={},o={}){return uo(e,t,{...o,validateUrl:Ur})}r(rf,"fetchConfiguredOutbound");function af(e,t={},o={}){return it(e,t,{...o,validateUrl:Mr})}r(af,"fetchIdentityProviderJson");function sf(e,t={},o={}){return it(e,t,{...o,validateUrl:jr})}r(sf,"fetchCimdClientMetadataJson");function cf(e,t={},o={}){return it(e,t,{...o,validateUrl:qr})}r(cf,"fetchCimdClientJwksJson");function lf(e){let t=Le().browserLogin[e];if(typeof t=="string"&&t.length>0)return t;throw ae("internal_server_error",`browserLogin.${e} is required for federated browser login. Set it on the mcp-oauth-inbound policy options.`)}r(lf,"requireBrowserLoginField");export{te as a,j as b,De as c,Le as d,Ge as e,Pr as f,ei as g,oi as h,Rd as i,w as j,wd as k,Ad as l,xd as m,_d as n,oe as o,zd as p,ne as q,gt as r,Pd as s,q as t,D as u,B as v,Uo as w,$e as x,di as y,Be as z,qo as A,Ha as B,bt as C,un as D,dn as E,rp as F,mn as G,fs as H,lp as I,hp as J,ln as K,We as L,fp as M,hn as N,yp as O,J as P,Pe as Q,Pt as R,X as S,Et as T,Mp as U,Ye as V,ae as W,he as X,Dp as Y,Cn as Z,Bp as _,Z as $,V as aa,vs as ba,Ps as ca,Xp as da,em as ea,tm as fa,om as ga,W as ha,fm as ia,gm as ja,Us as ka,Sm as la,xn as ma,Tm as na,Dt as oa,Hs as pa,T as qa,$s as ra,In as sa,kn as ta,vn as ua,Pn as va,Gt as wa,ol as xa,nl as ya,rl as za,ot as Aa,Nt as Ba,ll as Ca,hl as Da,fl as Ea,gl as Fa,Ir as Ga,N as Ha,oh as Ia,kr as Ja,nh as Ka,_o as La,Ur as Ma,jr as Na,qr as Oa,Lr as Pa,rf as Qa,af as Ra,sf as Sa,cf as Ta,lf as Ua};
30
- //# sourceMappingURL=chunk-LU6CEICL.js.map