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