@zuplo/runtime 6.71.2 → 6.71.6
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/{chunk-AZIRK6TC.js → chunk-2Y72LML3.js} +2 -2
- package/out/esm/{chunk-JRXZBVXH.js → chunk-DQ4ANJLR.js} +2 -2
- package/out/esm/{chunk-ZIKV2LUM.js → chunk-L3MZGNQA.js} +4 -4
- package/out/esm/chunk-L3MZGNQA.js.map +1 -0
- package/out/esm/chunk-LM6CZZF3.js +357 -0
- package/out/esm/chunk-LM6CZZF3.js.map +1 -0
- package/out/esm/index.js +1 -1
- package/out/esm/internal/index.js +1 -1
- package/out/esm/mcp-gateway/index.js +13 -13
- package/out/esm/mcp-gateway/index.js.map +1 -1
- package/out/esm/mocks/index.js +1 -1
- package/out/types/index.d.ts +52 -0
- package/out/types/mcp-gateway/index.d.ts +52 -0
- package/package.json +1 -1
- package/out/esm/chunk-E7U425SB.js +0 -357
- package/out/esm/chunk-E7U425SB.js.map +0 -1
- package/out/esm/chunk-ZIKV2LUM.js.map +0 -1
- /package/out/esm/{chunk-AZIRK6TC.js.map → chunk-2Y72LML3.js.map} +0 -0
- /package/out/esm/{chunk-JRXZBVXH.js.map → chunk-DQ4ANJLR.js.map} +0 -0
- /package/out/esm/{chunk-ZIKV2LUM.js.LEGAL.txt → chunk-L3MZGNQA.js.LEGAL.txt} +0 -0
- /package/out/esm/{chunk-E7U425SB.js.LEGAL.txt → chunk-LM6CZZF3.js.LEGAL.txt} +0 -0
|
@@ -22,29 +22,29 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{$b as ro,$c as vo,Ab as Mt,Ac as Le,Bb as B,Bc as mo,Cb as we,Cc as Nt,Db as uc,Dc as fo,Eb as lc,Ec as de,Fb as pc,Fc as Ir,G as Dn,Gb as mc,Gc as Cr,H as l,Hb as fc,Hc as ho,I as zn,Ib as hc,Ic as Jt,J as yr,Jb as gc,Jc as Sr,K as ae,Kb as yc,Kc as vr,L as jn,Lb as _c,Lc as go,M as _,Mb as wc,Mc as E,N as ge,Nb as Wn,Nc as yo,O as Ot,Ob as Vn,Oc as _o,P as Hn,Pb as Yn,Pc as Ar,Q as Bn,Qb as Dt,Qc as wo,R as Ln,Rb as _r,Rc as Ro,S as d,Sb as zt,Sc as xr,T as F,Tb as jt,Tc as bo,Ub as nt,Uc as ke,Vb as Xn,Vc as Io,Wb as Qn,Wc as st,Xb as eo,Xc as Co,Yb as ot,Yc as Gt,Z as Nn,Zb as to,Zc as ct,_b as He,_c as So,a as G,ac as wr,ad as Ao,bc as no,bd as xo,cc as at,cd as ko,dc as Ht,dd as Uo,ec as oo,ed as To,fc as ao,fd as Ft,gc as io,gd as Po,hc as so,hd as Eo,i as xe,ic as Y,id as b,j as On,jb as Jn,jc as j,jd as v,kb as $,kc as co,kd as ue,l as qn,lb as Gn,lc as uo,ld as x,mb as Fn,mc as I,md as Oo,nb as P,nc as se,nd as Rc,ob as $n,oc as Be,od as bc,p as Mn,pb as g,pc as L,qb as ze,qc as U,r as Et,rb as je,rc as lo,sb as ye,sc as ce,tb as _e,tc as po,ub as qt,uc as Re,vb as Zn,vc as Rr,wb as Q,wc as Bt,xb as Kn,xc as br,yb as ie,yc as Lt,zb as w,zc as it}from"../chunk-E7U425SB.js";import"../chunk-JRXZBVXH.js";import{a as C}from"../chunk-AZIRK6TC.js";import{$ as V,a as n,aa as f,ba as H,ca as En,da as Pt}from"../chunk-ZIKV2LUM.js";F();function Ic(e){let t=jt.safeParse(e);return t.success?t.data.id:void 0}n(Ic,"parseJsonRpcRequestId");function qo(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Ic(t)}catch{return}}n(qo,"readJsonRpcRequestIdFromBody");function $t(e){return Xn.parse({jsonrpc:zt,...e.id===void 0?{}:{id:e.id},error:{code:e.error.code,message:e.error.message,...e.error.data===void 0?{}:{data:e.error.data}}})}n($t,"jsonRpcErrorResponse");function Mo(e){return new eo([Qn.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Mo,"urlElicitationRequiredError");var Zt=d.record(d.string(),d.unknown()),Cc=d.record(d.string(),d.unknown()),Sc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),annotations:Cc.optional(),_meta:Zt.optional()}).strict(),vc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),_meta:Zt.optional()}).strict(),Ac=d.object({uri:d.string().min(1),name:d.string().min(1).optional(),description:d.string().min(1).optional(),mimeType:d.string().min(1).optional(),_meta:Zt.optional()}).strict(),xc=d.object({uriTemplate:d.string().min(1),name:d.string().min(1).optional(),description:d.string().min(1).optional(),mimeType:d.string().min(1).optional(),_meta:Zt.optional()}).strict(),kc=d.array(d.union([d.string(),Sc])),Uc=d.array(d.union([d.string(),vc])),Tc=d.array(d.union([d.string(),Ac])),Pc=d.array(d.union([d.string(),xc])),Ec=d.object({tools:kc.optional(),prompts:Uc.optional(),resources:Tc.optional(),resourceTemplates:Pc.optional()}).strict(),Ur=[{option:"tools",listMethod:"tools/list",resultProperty:"tools",itemProperty:"name",directMethods:[{method:"tools/call",paramProperty:"name"}]},{option:"prompts",listMethod:"prompts/list",resultProperty:"prompts",itemProperty:"name",directMethods:[{method:"prompts/get",paramProperty:"name"}]},{option:"resources",listMethod:"resources/list",resultProperty:"resources",itemProperty:"uri",directMethods:[{method:"resources/read",paramProperty:"uri"}]},{option:"resourceTemplates",listMethod:"resources/templates/list",resultProperty:"resourceTemplates",itemProperty:"uriTemplate",directMethods:[]}];function Oc(e,t){return Gn(Ec,e,`MCP capability filter policy "${t}"`)}n(Oc,"parseMcpCapabilityFilterOptions");function N(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(N,"isRecord");function qc(e,t){if(!N(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(qc,"readParamString");function Tr(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(Tr,"readRequestId");function Ho(e){return e===void 0?void 0:JSON.stringify(e)}n(Ho,"requestIdKey");function Mc(e){let t={};for(let r of Ur){let o=e[r.option];if(o===void 0)continue;let a=new Map;for(let i of o){let c=Hc(i,r.itemProperty);c!==void 0&&a.set(c.key,c)}t[r.option]=a}return t}n(Mc,"buildProjectionMaps");function Pr(e){return Ur.find(t=>t.listMethod===e)}n(Pr,"findListRule");function Dc(e){return e.requests.some(t=>{if(!N(t))return!1;let r=Pr(t.method);return r!==void 0&&e.projectionMaps[r.option]!==void 0})}n(Dc,"shouldFilterListResponses");function zc(e){for(let t of Ur){let r=e.projectionMaps[t.option];if(r!==void 0)for(let o of t.directMethods){if(e.request.method!==o.method)continue;let a=qc(e.request.params,o.paramProperty);if(a!==void 0&&!r.has(a))return{id:Tr(e.request)}}}}n(zc,"findDisallowedDirectAccess");function jc(e){return Response.json($t({id:e,error:{code:nt.MethodNotFound,message:"Method not found"}}))}n(jc,"methodNotFoundResponse");function Hc(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!N(e))return;let r=e[t];if(typeof r=="string")return{key:r,overlay:e}}n(Hc,"buildProjection");function Do(e){let t=e.base[e.property],r=e.overlay[e.property];return N(r)?N(t)?{...t,...r}:r:t}n(Do,"mergeRecordProperty");function Bc(e,t){let r={...e,...t.overlay},o=Do({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let a=Do({base:e,overlay:t.overlay,property:"_meta"});return a!==void 0&&(r._meta=a),r}n(Bc,"applyProjection");function zo(e,t,r){if(!N(e))return e;let o=e.result;if(!N(o))return e;let a=o[t.resultProperty];return!Array.isArray(a)||!a.every(i=>N(i)&&typeof i[t.itemProperty]=="string")?e:{...e,result:{...o,[t.resultProperty]:a.flatMap(i=>{if(!N(i))return[];let c=i[t.itemProperty];if(typeof c!="string")return[];let s=r.get(c);return s===void 0?[]:[Bc(i,s)]})}}}n(zo,"filterAndProjectItems");function Lc(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!N(r))continue;let o=Pr(r.method),a=Tr(r),i=Ho(a);o!==void 0&&i!==void 0&&t.set(i,o)}return t}n(Lc,"buildListRulesByResponseId");function Nc(e){if(Array.isArray(e.responseBody)){let o=Lc(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(a=>{if(!N(a)||"error"in a)return a;let i=Ho(Tr(a)),c=i===void 0?void 0:o.get(i),s=c===void 0?void 0:e.projectionMaps[c.option];return c===void 0||s===void 0?a:zo(a,c,s)})}if(!N(e.requestBody)||!N(e.responseBody)||"error"in e.responseBody)return e.responseBody;let t=Pr(e.requestBody.method),r=t===void 0?void 0:e.projectionMaps[t.option];return t===void 0||r===void 0?e.responseBody:zo(e.responseBody,t,r)}n(Nc,"filterJsonRpcResponse");async function jo(e){return e.clone().json()}n(jo,"readJson");function Jc(e){return e.headers.get("content-type")?.includes("json")??!1}n(Jc,"isJsonResponse");var kr=class extends Et{static{n(this,"McpCapabilityFilterInboundPolicy")}#e;constructor(t,r){let o=Oc(t,r);super(o,r),this.#e=Mc(o)}async handler(t,r){G("policy.inbound.mcp-capability-filter");let o;try{o=await jo(t)}catch{return t}let a=Array.isArray(o)?o:[o];for(let i of a){if(!N(i))continue;let c=zc({request:i,projectionMaps:this.#e});if(c!==void 0)return jc(c.id)}return Dc({requests:a,projectionMaps:this.#e})&&r.addResponseSendingHook(async i=>{if(!Jc(i))return i;let c;try{c=await jo(i)}catch{return i}let s=Nc({requestBody:o,responseBody:c,projectionMaps:this.#e});if(s===c)return i;let u=new Headers(i.headers);return u.delete("content-length"),new Response(JSON.stringify(s),{status:i.status,statusText:i.statusText,headers:u})}),t}};var Er;Er=globalThis.crypto;async function Gc(e){return(await Er).getRandomValues(new Uint8Array(e))}n(Gc,"getRandomValues");async function Fc(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let a=await Gc(e-o.length);for(let i of a)i<r&&(o+=t[i%t.length])}return o}n(Fc,"random");async function $c(e){return await Fc(e)}n($c,"generateVerifier");async function Zc(e){let t=await(await Er).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(Zc,"generateChallenge");async function Or(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await $c(e),r=await Zc(t);return{code_verifier:t,code_challenge:r}}n(Or,"pkceChallenge");F();var D=zn().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Bn.custom,message:"URL must be parseable",fatal:!0}),Dn}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Kt=Ot({resource:l().url(),authorization_servers:_(D).optional(),jwks_uri:l().url().optional(),scopes_supported:_(l()).optional(),bearer_methods_supported:_(l()).optional(),resource_signing_alg_values_supported:_(l()).optional(),resource_name:l().optional(),resource_documentation:l().optional(),resource_policy_uri:l().url().optional(),resource_tos_uri:l().url().optional(),tls_client_certificate_bound_access_tokens:ae().optional(),authorization_details_types_supported:_(l()).optional(),dpop_signing_alg_values_supported:_(l()).optional(),dpop_bound_access_tokens_required:ae().optional()}),dt=Ot({issuer:l(),authorization_endpoint:D,token_endpoint:D,registration_endpoint:D.optional(),scopes_supported:_(l()).optional(),response_types_supported:_(l()),response_modes_supported:_(l()).optional(),grant_types_supported:_(l()).optional(),token_endpoint_auth_methods_supported:_(l()).optional(),token_endpoint_auth_signing_alg_values_supported:_(l()).optional(),service_documentation:D.optional(),revocation_endpoint:D.optional(),revocation_endpoint_auth_methods_supported:_(l()).optional(),revocation_endpoint_auth_signing_alg_values_supported:_(l()).optional(),introspection_endpoint:l().optional(),introspection_endpoint_auth_methods_supported:_(l()).optional(),introspection_endpoint_auth_signing_alg_values_supported:_(l()).optional(),code_challenge_methods_supported:_(l()).optional(),client_id_metadata_document_supported:ae().optional()}),Kc=Ot({issuer:l(),authorization_endpoint:D,token_endpoint:D,userinfo_endpoint:D.optional(),jwks_uri:D,registration_endpoint:D.optional(),scopes_supported:_(l()).optional(),response_types_supported:_(l()),response_modes_supported:_(l()).optional(),grant_types_supported:_(l()).optional(),acr_values_supported:_(l()).optional(),subject_types_supported:_(l()),id_token_signing_alg_values_supported:_(l()),id_token_encryption_alg_values_supported:_(l()).optional(),id_token_encryption_enc_values_supported:_(l()).optional(),userinfo_signing_alg_values_supported:_(l()).optional(),userinfo_encryption_alg_values_supported:_(l()).optional(),userinfo_encryption_enc_values_supported:_(l()).optional(),request_object_signing_alg_values_supported:_(l()).optional(),request_object_encryption_alg_values_supported:_(l()).optional(),request_object_encryption_enc_values_supported:_(l()).optional(),token_endpoint_auth_methods_supported:_(l()).optional(),token_endpoint_auth_signing_alg_values_supported:_(l()).optional(),display_values_supported:_(l()).optional(),claim_types_supported:_(l()).optional(),claims_supported:_(l()).optional(),service_documentation:l().optional(),claims_locales_supported:_(l()).optional(),ui_locales_supported:_(l()).optional(),claims_parameter_supported:ae().optional(),request_parameter_supported:ae().optional(),request_uri_parameter_supported:ae().optional(),require_request_uri_registration:ae().optional(),op_policy_uri:D.optional(),op_tos_uri:D.optional(),client_id_metadata_document_supported:ae().optional()}),Wt=ge({...Kc.shape,...dt.pick({code_challenge_methods_supported:!0}).shape}),Ne=ge({access_token:l(),id_token:l().optional(),token_type:l(),expires_in:Ln.number().optional(),scope:l().optional(),refresh_token:l().optional()}).strip(),Lo=ge({error:l(),error_description:l().optional(),error_uri:l().optional()}),Bo=D.optional().or(Hn("").transform(()=>{})),Wc=ge({redirect_uris:_(D),token_endpoint_auth_method:l().optional(),grant_types:_(l()).optional(),response_types:_(l()).optional(),client_name:l().optional(),client_uri:D.optional(),logo_uri:Bo,scope:l().optional(),contacts:_(l()).optional(),tos_uri:Bo,policy_uri:l().optional(),jwks_uri:D.optional(),jwks:jn().optional(),software_id:l().optional(),software_version:l().optional(),software_statement:l().optional()}).strip(),Vt=ge({client_id:l(),client_secret:l().optional(),client_id_issued_at:yr().optional(),client_secret_expires_at:yr().optional()}).strip(),ut=Wc.merge(Vt),Dh=ge({error:l(),error_description:l().optional()}).strip(),zh=ge({token:l(),token_type_hint:l().optional()}).strip();function No(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(No,"resourceUrlFromServerUrl");function Jo({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let a=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return a.startsWith(i)}n(Jo,"checkResourceAllowed");var A=class extends Error{static{n(this,"OAuthError")}constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},lt=class extends A{static{n(this,"InvalidRequestError")}};lt.errorCode="invalid_request";var Ue=class extends A{static{n(this,"InvalidClientError")}};Ue.errorCode="invalid_client";var Te=class extends A{static{n(this,"InvalidGrantError")}};Te.errorCode="invalid_grant";var Pe=class extends A{static{n(this,"UnauthorizedClientError")}};Pe.errorCode="unauthorized_client";var pt=class extends A{static{n(this,"UnsupportedGrantTypeError")}};pt.errorCode="unsupported_grant_type";var mt=class extends A{static{n(this,"InvalidScopeError")}};mt.errorCode="invalid_scope";var ft=class extends A{static{n(this,"AccessDeniedError")}};ft.errorCode="access_denied";var le=class extends A{static{n(this,"ServerError")}};le.errorCode="server_error";var ht=class extends A{static{n(this,"TemporarilyUnavailableError")}};ht.errorCode="temporarily_unavailable";var gt=class extends A{static{n(this,"UnsupportedResponseTypeError")}};gt.errorCode="unsupported_response_type";var yt=class extends A{static{n(this,"UnsupportedTokenTypeError")}};yt.errorCode="unsupported_token_type";var _t=class extends A{static{n(this,"InvalidTokenError")}};_t.errorCode="invalid_token";var wt=class extends A{static{n(this,"MethodNotAllowedError")}};wt.errorCode="method_not_allowed";var Rt=class extends A{static{n(this,"TooManyRequestsError")}};Rt.errorCode="too_many_requests";var Ee=class extends A{static{n(this,"InvalidClientMetadataError")}};Ee.errorCode="invalid_client_metadata";var bt=class extends A{static{n(this,"InsufficientScopeError")}};bt.errorCode="insufficient_scope";var It=class extends A{static{n(this,"InvalidTargetError")}};It.errorCode="invalid_target";var Go={[lt.errorCode]:lt,[Ue.errorCode]:Ue,[Te.errorCode]:Te,[Pe.errorCode]:Pe,[pt.errorCode]:pt,[mt.errorCode]:mt,[ft.errorCode]:ft,[le.errorCode]:le,[ht.errorCode]:ht,[gt.errorCode]:gt,[yt.errorCode]:yt,[_t.errorCode]:_t,[wt.errorCode]:wt,[Rt.errorCode]:Rt,[Ee.errorCode]:Ee,[bt.errorCode]:bt,[It.errorCode]:It};function Vc(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(Vc,"isClientAuthMethod");var qr="code",Mr="S256";function Yc(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Vc(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}n(Yc,"selectClientAuthMethod");function Xc(e,t,r,o){let{client_id:a,client_secret:i}=t;switch(e){case"client_secret_basic":Qc(a,i,r);return;case"client_secret_post":ed(a,i,o);return;case"none":td(a,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(Xc,"applyClientAuthentication");function Qc(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}n(Qc,"applyBasicAuth");function ed(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(ed,"applyPostAuth");function td(e,t){t.set("client_id",e)}n(td,"applyPublicAuth");async function $o(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Lo.parse(JSON.parse(r)),{error:a,error_description:i,error_uri:c}=o,s=Go[a]||le;return new s(i||"",c)}catch(o){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new le(a)}}n($o,"parseErrorResponse");async function jr(e,t){try{return await Dr(e,t)}catch(r){if(r instanceof Ue||r instanceof Pe)return await e.invalidateCredentials?.("all"),await Dr(e,t);if(r instanceof Te)return await e.invalidateCredentials?.("tokens"),await Dr(e,t);throw r}}n(jr,"auth");async function Dr(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:a,fetchFn:i}){let c=await e.discoveryState?.(),s,u,p,h=a;if(!h&&c?.resourceMetadataUrl&&(h=new URL(c.resourceMetadataUrl)),c?.authorizationServerUrl){if(u=c.authorizationServerUrl,s=c.resourceMetadata,p=c.authorizationServerMetadata??await Wo(u,{fetchFn:i}),!s)try{s=await Ko(t,{resourceMetadataUrl:h},i)}catch{}(p!==c.authorizationServerMetadata||s!==c.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:h?.toString(),resourceMetadata:s,authorizationServerMetadata:p})}else{let M=await sd(t,{resourceMetadataUrl:h,fetchFn:i});u=M.authorizationServerUrl,p=M.authorizationServerMetadata,s=M.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:h?.toString(),resourceMetadata:s,authorizationServerMetadata:p})}let y=await rd(t,e,s),T=o||s?.scopes_supported?.join(" ")||e.clientMetadata.scope,R=await Promise.resolve(e.clientInformation());if(!R){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let M=p?.client_id_metadata_document_supported===!0,z=e.clientMetadataUrl;if(z&&!Hr(z))throw new Ee(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${z}`);if(M&&z)R={client_id:z},await e.saveClientInformation?.(R);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Pn=await pd(u,{metadata:p,clientMetadata:e.clientMetadata,scope:T,fetchFn:i});await e.saveClientInformation(Pn),R=Pn}}let q=!e.redirectUrl;if(r!==void 0||q){let M=await ld(e,u,{metadata:p,resource:y,authorizationCode:r,fetchFn:i});return await e.saveTokens(M),"AUTHORIZED"}let O=await e.tokens();if(O?.refresh_token)try{let M=await ud(u,{metadata:p,clientInformation:R,refreshToken:O.refresh_token,resource:y,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(M),"AUTHORIZED"}catch(M){if(!(!(M instanceof A)||M instanceof le))throw M}let ne=e.state?await e.state():void 0,{authorizationUrl:rt,codeVerifier:oe}=await cd(u,{metadata:p,clientInformation:R,state:ne,redirectUrl:e.redirectUrl,scope:T,resource:y});return await e.saveCodeVerifier(oe),await e.redirectToAuthorization(rt),"REDIRECT"}n(Dr,"authInternal");function Hr(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(Hr,"isHttpsUrl");async function rd(e,t,r){let o=No(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!Jo({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}n(rd,"selectResourceURL");function Zo(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let a=zr(e,"resource_metadata")||void 0,i;if(a)try{i=new URL(a)}catch{}let c=zr(e,"scope")||void 0,s=zr(e,"error")||void 0;return{resourceMetadataUrl:i,scope:c,error:s}}n(Zo,"extractWWWAuthenticateParams");function zr(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),a=r.match(o);return a?a[1]||a[2]:null}n(zr,"extractFieldFromWwwAuth");async function Ko(e,t,r=fetch){let o=await ad(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.body?.cancel(),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Kt.parse(await o.json())}n(Ko,"discoverOAuthProtectedResourceMetadata");async function Br(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Br(e,void 0,r):void 0;throw o}}n(Br,"fetchWithCorsRetry");function nd(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(nd,"buildWellKnownPath");async function Fo(e,t,r=fetch){return await Br(e,{"MCP-Protocol-Version":t},r)}n(Fo,"tryMetadataDiscovery");function od(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(od,"shouldAttemptFallback");async function ad(e,t,r,o){let a=new URL(e),i=o?.protocolVersion??_r,c;if(o?.metadataUrl)c=new URL(o.metadataUrl);else{let u=nd(t,a.pathname);c=new URL(u,o?.metadataServerUrl??a),c.search=a.search}let s=await Fo(c,i,r);if(!o?.metadataUrl&&od(s,a.pathname)){let u=new URL(`/.well-known/${t}`,a);s=await Fo(u,i,r)}return s}n(ad,"discoverMetadataWithFallback");function id(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let a=t.pathname;return a.endsWith("/")&&(a=a.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:"oidc"}),o.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(id,"buildDiscoveryUrls");async function Wo(e,{fetchFn:t=fetch,protocolVersion:r=_r}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},a=id(e);for(let{url:i,type:c}of a){let s=await Br(i,o,t);if(s){if(!s.ok){if(await s.body?.cancel(),s.status>=400&&s.status<500)continue;throw new Error(`HTTP ${s.status} trying to load ${c==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return c==="oauth"?dt.parse(await s.json()):Wt.parse(await s.json())}}}n(Wo,"discoverAuthorizationServerMetadata");async function sd(e,t){let r,o;try{r=await Ko(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch{}o||(o=String(new URL("/",e)));let a=await Wo(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:a,resourceMetadata:r}}n(sd,"discoverOAuthServerInfo");async function cd(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:a,state:i,resource:c}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(qr))throw new Error(`Incompatible auth server: does not support response type ${qr}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Mr))throw new Error(`Incompatible auth server: does not support code challenge method ${Mr}`)}else s=new URL("/authorize",e);let u=await Or(),p=u.code_verifier,h=u.code_challenge;return s.searchParams.set("response_type",qr),s.searchParams.set("client_id",r.client_id),s.searchParams.set("code_challenge",h),s.searchParams.set("code_challenge_method",Mr),s.searchParams.set("redirect_uri",String(o)),i&&s.searchParams.set("state",i),a&&s.searchParams.set("scope",a),a?.includes("offline_access")&&s.searchParams.append("prompt","consent"),c&&s.searchParams.set("resource",c.href),{authorizationUrl:s,codeVerifier:p}}n(cd,"startAuthorization");function dd(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(dd,"prepareAuthorizationCodeRequest");async function Vo(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:a,resource:i,fetchFn:c}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",i.href),a)await a(u,r,s,t);else if(o){let h=t?.token_endpoint_auth_methods_supported??[],y=Yc(o,h);Xc(y,o,u,r)}let p=await(c??fetch)(s,{method:"POST",headers:u,body:r});if(!p.ok)throw await $o(p);return Ne.parse(await p.json())}n(Vo,"executeTokenRequest");async function ud(e,{metadata:t,clientInformation:r,refreshToken:o,resource:a,addClientAuthentication:i,fetchFn:c}){let s=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),u=await Vo(e,{metadata:t,tokenRequestParams:s,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:c});return{refresh_token:o,...u}}n(ud,"refreshAuthorization");async function ld(e,t,{metadata:r,resource:o,authorizationCode:a,fetchFn:i}={}){let c=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(c)),!s){if(!a)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let p=await e.codeVerifier();s=dd(a,p,e.redirectUrl)}let u=await e.clientInformation();return Vo(t,{metadata:r,tokenRequestParams:s,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:i})}n(ld,"fetchToken");async function pd(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:a}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let c=await(a??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!c.ok)throw await $o(c);return ut.parse(await c.json())}n(pd,"registerClient");var Lr="zuplo.com",md=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),fd=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Yo(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(Yo,"s2FaviconHref");function hd(e){return`https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&drop_404_icon=true&fallback_opts=TYPE,SIZE,URL&url=http://${e}&size=128`}n(hd,"strictFaviconHref");var Yt=Yo(Lr);function Nr(e){let t=e.toLowerCase();return t===Lr||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?Yo(Lr):hd(e)}n(Nr,"resolveIconHref");function gd(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(gd,"hostnameFromHost");function yd(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(yd,"isLocalOrAddressHost");function _d(e){let t=gd(e).toLowerCase().replace(/\.$/,"");if(yd(t)||fd.some(i=>t===i.slice(1)||t.endsWith(i)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let o=r.slice(-2).join("."),a=md.has(o)?3:2;return r.slice(-a).join(".")}n(_d,"inferFaviconDomain");function Jr(e){return{src:Nr(_d(e)),mimeType:"image/png",sizes:["128x128"]}}n(Jr,"resolveMcpFaviconIcon");function Xt(e){try{return Jr(new URL(e).host)}catch{return}}n(Xt,"resolveMcpFaviconIconFromUrl");function be(e){let t=Y().connectionsById.get(e);if(!t)throw new H(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,description:t.description,serverInfo:t.serverInfo,transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}n(be,"getUpstreamServerConfig");function Qt(e){let t=Y().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new H(`Unknown auth profile "${String(e.authProfileId)}" for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares a matching auth mode for that upstream connection.`);return t.authConfig}n(Qt,"getUpstreamAuthConfig");function Je(e,t){let r=Qt({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new H(`Upstream server "${e}" does not use upstream OAuth. Select authMode "shared-oauth" or "user-oauth" before starting an upstream OAuth connection flow.`);return r.oauth}n(Je,"requireUpstreamOAuthConfig");function Xo(e,t){let r=Qt({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new H(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(Xo,"requireUpstreamIdJagConfig");function Qo(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let r=n(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}n(Qo,"mergeAbortSignals");async function wd(e){try{await e.cancel()}catch{}}n(wd,"cancelReader");async function er(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],a=0,i=await r.read();for(;!i.done;){let u=i.value;if(a+=u.byteLength,a>t.maxBytes)throw await wd(r),t.createLimitError();o.push(u),i=await r.read()}let c=new Uint8Array(a),s=0;for(let u of o)c.set(u,s),s+=u.byteLength;return c}n(er,"readBoundedByteStream");var Rd=2,bd=1024*1024,Id=1e4,Cd=new Set([301,302,303,307,308]),Sd=["authorization","proxy-authorization","cookie","cookie2"];function Gr(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Gr,"readRequestUrl");function Ge(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(Ge,"readRequestMethod");function vd(e,t,r){let o=e.headers.get("content-length");if(!o)return;let a=Number.parseInt(o,10);if(Number.isFinite(a)&&a>t)throw new f({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}})}n(vd,"assertContentLengthWithinLimit");async function Ad(e,t,r){return vd(e,t,r),er(e.body,{maxBytes:t,createLimitError:n(()=>new f({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}}),"createLimitError")})}n(Ad,"readBoundedResponseBody");function xd(e,t){let r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}n(xd,"responseFromBufferedBody");function kd(e,t){if(!Cd.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(kd,"resolveRedirectUrl");function ea(e,t){try{return t.validateUrl(e)}catch(r){throw new f({message:"Outbound URL was not allowed.",extensionMembers:{[g]:t.problemCode}},{cause:r})}}n(ea,"validateOutboundUrl");function Ud(e,t){throw e instanceof f&&qt(e.extensionMembers?.[g])?e:new f({message:"Outbound fetch failed.",extensionMembers:{[g]:t}},{cause:e})}n(Ud,"normalizeFetchError");function Ct(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[o,a]of Object.entries(t.extra))a!==void 0&&(r[o]=a);t.error!==void 0&&L(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(Ct,"logOutboundFailure");async function Td(e,t,r,o,a,i,c){let s=Ge(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";Ct(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:s,host:U(i),error:u,extra:{abortReason:c()}}),Ud(u,a)}}n(Td,"fetchWithNormalizedError");function Pd(e){if(e.redirects>=e.maxRedirects)throw new f({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[g]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new f({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[g]:e.problemCode}})}n(Pd,"assertRedirectAllowed");function Ed(e,t){let r=new Headers(e);for(let o of Sd)r.delete(o);for(let o of t)r.delete(o);return r}n(Ed,"stripCrossOriginHeaders");function Od(e,t,r,o,a){let i={...e,method:t,redirect:"manual",signal:r};return o&&(i.headers=Ed(e.headers,a)),i}n(Od,"buildRedirectInit");function qd(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(qd,"buildInitialRequestInit");function Md(e){let t=Ge(e.currentInput,e.currentInit);Pd({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=ea(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),a=r.origin!==o.origin,i=r.toString();return{currentInput:i,currentUrl:i,currentInit:Od(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(Md,"followRedirect");async function Fr(e,t,r){let o=r.problemCode??"invalid_request",a=r.maxRedirects??Rd,i=r.maxResponseBytes??bd,c=r.timeoutMs??Id,s=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,h=new AbortController,y=Qo(h,t.signal),T=!1,R=setTimeout(()=>{T=!0,h.abort()},c),q=e,O=qd(e,t,h.signal),ne;try{ne=ea(Gr(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(oe){throw Ct(p,{event:"outbound_url_blocked",problemCode:o,method:Ge(e,t),host:U(Gr(e)),error:oe}),clearTimeout(R),y?.(),oe}let rt=0;try{for(;;){let oe=await Td(p,s,q,O,o,ne,()=>T?`timeout_after_${c}ms`:void 0),M=kd(oe,ne);if(M!==void 0)try{let z=Md({currentInput:q,currentInit:O,currentUrl:ne,redirectUrl:M,redirects:rt,maxRedirects:a,problemCode:o,validateUrl:r.validateUrl,signal:h.signal,additionalCrossOriginStrippedHeaders:u});q=z.currentInput,O=z.currentInit,ne=z.currentUrl,rt=z.redirects;continue}catch(z){throw Ct(p,{event:"outbound_redirect_blocked",problemCode:o,method:Ge(q,O),host:U(ne),error:z,extra:{redirects:rt,maxRedirects:a,redirectTargetHost:U(M)}}),z}try{return xd(oe,await Ad(oe,i,o))}catch(z){throw Ct(p,{event:"outbound_response_size_exceeded",problemCode:o,method:Ge(q,O),host:U(ne),error:z,extra:{maxResponseBytes:i,status:oe.status}}),z}}}finally{clearTimeout(R),y?.()}}n(Fr,"runSafeOutboundExchange");async function St(e,t,r){let o=await Fr(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(a){throw Ct(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Ge(e,t),host:U(Gr(e)),error:a,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new f({message:"Outbound JSON response could not be parsed.",extensionMembers:{[g]:r.problemCode??"invalid_request"}},{cause:a})}}n(St,"runSafeOutboundJsonExchange");function ta(e,t={},r={}){return Fr(e,t,{...r,validateUrl:st})}n(ta,"fetchConfiguredOutbound");function ra(e,t={},r={}){return St(e,t,{...r,validateUrl:st})}n(ra,"fetchConfiguredOutboundJson");function tr(e,t={},r={}){return St(e,t,{...r,validateUrl:Co})}n(tr,"fetchIdentityProviderJson");function na(e,t={},r={}){return St(e,t,{...r,validateUrl:Gt})}n(na,"fetchCimdClientMetadataJson");function oa(e,t={},r={}){return St(e,t,{...r,validateUrl:ct})}n(oa,"fetchCimdClientJwksJson");F();import{errors as la,jwtVerify as pa,SignJWT as ma}from"jose";var J="zuplo-mcp-gateway",Z=J,K="HS256";import{base64url as Dd}from"jose";var zd=new TextEncoder,jd="MCP gateway could not initialize secure key material.",Hd=32,aa=new Map,ia=new Map,Bd;function Ld(){return Bd??En.instance.authPrivateKey}n(Ld,"readAuthPrivateKey");function sa(e){return new V(jd,e===void 0?void 0:{cause:e})}n(sa,"createGeneratedKeyMaterialError");function ca(e,t){let r=Dd.decode(t);if(r.byteLength!==Hd)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(ca,"decodeJwkKeyField");function Nd(e){let t=Ld();if(!t)throw sa();try{let r=JSON.parse(t);if(r.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.d!="string"||typeof r.x!="string")throw new Error("Generated deployment auth key is not an Ed25519 JWK.");let o=ca("d",r.d);ca("x",r.x);let a=zd.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),i=new Uint8Array(a.byteLength+o.byteLength);return i.set(a),i.set(o,a.byteLength),i}catch(r){throw sa(r)}}n(Nd,"decodeGeneratedKeyMaterial");function Jd(e){let t=aa.get(e);return t||(t=Nd(e),aa.set(e,t)),t}n(Jd,"getMasterKeyMaterial");async function te(e){let t=ia.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Jd(e.keyMaterialPurpose));return ia.set(e.purpose,r),r}n(te,"readCachedDerivedKey");var Gd="SHA-256";var Fd="zuplo-mcp-gateway:",$d=new TextEncoder,da=new WeakMap;async function Ie(e,t){let r=da.get(e);r||(r=new Map,da.set(e,r));let o=r.get(t);if(o)return o;let a=await Zd(e,t);return r.set(t,a),a}n(Ie,"deriveGatewaySigningKey");async function Zd(e,t){let r=ua(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=$d.encode(`${Fd}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:Gd,salt:new Uint8Array,info:ua(a)},o,32*8);return new Uint8Array(i)}n(Zd,"hkdfExpand");function ua(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(ua,"copyToArrayBuffer");var fa=15*60,Kd=15*60,Wd=no.extend({id:ko}),Vd=Wd.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ha=wr.extend({id:Uo,purpose:d.literal("browser_connect")}),Yd=wr.extend({purpose:d.literal("browser_connect")}),Xd=ha.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ga=fa*1e3;async function ya(){return te({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ie(e,"oauth-state"),"derive")})}n(ya,"getOAuthStateKey");async function _a(){return te({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ie(e,"browser-connect"),"derive")})}n(_a,"getBrowserConnectKey");async function wa(e){let t=Math.floor(Date.now()/1e3)+fa;return new ma(e).setProtectedHeader({alg:K,typ:"JWT"}).setIssuer(J).setAudience(Z).setIssuedAt().setExpirationTime(t).sign(await ya())}n(wa,"signOAuthState");async function rr(e){try{let{payload:t}=await pa(e,await ya(),{algorithms:[K],issuer:J,audience:Z});return Vd.parse(t)}catch(t){throw t instanceof la.JWTExpired?new f({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new f({message:"OAuth state could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(rr,"verifyOAuthState");async function Ra(e){let t=Math.floor(Date.now()/1e3)+Kd,r=Yd.parse(e),o=ha.parse({...r,id:Eo()});return new ma(o).setProtectedHeader({alg:K,typ:"JWT"}).setIssuer(J).setAudience(Z).setIssuedAt().setExpirationTime(t).sign(await _a())}n(Ra,"signBrowserConnectTicket");async function ba(e){try{let{payload:t}=await pa(e,await _a(),{algorithms:[K],issuer:J,audience:Z});return Xd.parse(t)}catch(t){throw t instanceof la.JWTExpired?new f({message:"Browser connect ticket has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new f({message:"Browser connect ticket could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(ba,"verifyBrowserConnectTicket");async function Ia(e){if((await b().consumeBrowserConnectTicket({id:e.id,expiresAt:I(new Date(e.exp*1e3)),now:I(new Date)})).kind==="consumed")throw new f({message:"Browser connect ticket has already been used",extensionMembers:{[g]:"oauth_state_reused"}})}n(Ia,"consumeBrowserConnectTicket");function Qd(e,t,r=!1){return r?`${e} authorization must be renewed before this ${t} can be used.`:`${e} authorization is required before this ${t} can be used.`}n(Qd,"buildConnectRequiredMessage");async function eu(e){let t=P(e.requestUrl,e.requestHeaders),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("operationId",e.operationId),r.searchParams.set("browserTicket",await Ra({...at(e),purpose:"browser_connect"})),r.toString()}n(eu,"buildGatewayBrowserTicketUrl");function tu(e){return j().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(tu,"buildGatewayConnectPath");async function $r(e){return eu({...e,path:tu(e.upstreamServerId),redirect:!0})}n($r,"buildGatewayConnectUrl");async function nr(e){let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await $r(t),message:Qd(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(nr,"buildRedirectConnectRequiredResponse");function Ca(e){return ru({...e,message:e.requiresReconsent?`An administrator must reconnect ${e.upstreamDisplayName} before this tool can be used.`:`An administrator must connect ${e.upstreamDisplayName} before this tool can be used.`})}n(Ca,"buildAdminConnectRequiredResponse");function ru(e){return{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},message:e.message,nextAction:"admin_setup_required"}}n(ru,"buildAdminSetupRequiredResponse");F();var Sa=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function nu(e,t){return e&&e.length>0?e.join(t):void 0}n(nu,"joinOAuthScopes");function ou(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of Sa)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(ou,"sanitizeAuthorizationServerMetadata");function va(e){let t=ou(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(va,"sanitizeOAuthDiscoveryState");function Aa(e){let t=new URL(e);for(let r of Sa){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(Aa,"dedupeSingletonAuthorizationRequestParams");function or(e){let t=new URL(e);return $(t)&&Jn(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(or,"normalizeLoopbackOAuthRedirectUri");function xa(e){return nu(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(xa,"readProtectedResourceMetadataScope");function au(e){return`Zuplo MCP Gateway - ${e}`}n(au,"buildGatewayOAuthClientName");function iu(e,t){return e&&e.length>0?e.join(t):void 0}n(iu,"joinOAuthScopeList");function su(e){if(e.clientRegistration.mode!=="auto")return iu(e.scopes,e.scopeDelimiter)}n(su,"readPublicClientMetadataScope");function Zr(e){return new URL(j().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Zr,"buildOAuthClientMetadataDocumentUrl");function Kr(e){let t=be(e.upstreamServerId);return{client_name:au(t.displayName),client_uri:new URL("/",e.origin).toString(),redirect_uris:[e.redirectUri],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",...e.scope===void 0?{}:{scope:e.scope},token_endpoint_auth_method:"none"}}n(Kr,"buildGatewayOAuthClientMetadata");function ka(e,t,r){let o=Je(t,r),a=su(o);return{client_id:Zr({origin:e,upstreamServerId:t}),...Kr({origin:e,upstreamServerId:t,redirectUri:or(new URL(o.redirectPath,e)).toString(),scope:a})}}n(ka,"buildOAuthClientMetadataDocument");F();import{base64url as Ce}from"jose";var cu="SHA-256",$e="AES-GCM",du=12,Vr="zuplo-secret",Yr=1,Ua="generated:auth_private_key:token-encryption",uu=d.object({version:d.literal(Yr),keyId:d.literal(Ua),algorithm:d.literal($e),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();function Fe(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(Fe,"copyToArrayBuffer");async function Wr(){return te({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(cu,Fe(e));return crypto.subtle.importKey("raw",t,{name:$e},!1,["encrypt","decrypt"])},"derive")})}n(Wr,"getEncryptionKey");function Ta(e){return Fe(new TextEncoder().encode(`${Vr}:v${e.version}:${e.keyId}`))}n(Ta,"getAssociatedData");function lu(e){return`${Vr}:v${e.version}:${Ce.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(lu,"encodeEnvelope");function pu(e){let t=`${Vr}:v${Yr}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(Ce.decode(r));return uu.parse(JSON.parse(o))}n(pu,"decodeEnvelope");async function pe(e){let t=await Wr(),r=crypto.getRandomValues(new Uint8Array(du)),o={version:Yr,keyId:Ua},a=await crypto.subtle.encrypt({name:$e,iv:r,additionalData:Ta(o)},t,new TextEncoder().encode(e));return lu({...o,algorithm:$e,iv:Ce.encode(r),ciphertext:Ce.encode(new Uint8Array(a))})}n(pe,"encryptSecret");async function Se(e){let t=pu(e);if(t){let c=await Wr(),s=await crypto.subtle.decrypt({name:$e,iv:Fe(Ce.decode(t.iv)),additionalData:Ta(t)},c,Fe(Ce.decode(t.ciphertext)));return new TextDecoder().decode(s)}let[r,o]=e.split(".");if(!r||!o)throw new V("Encrypted payload is malformed");let a=await Wr(),i=await crypto.subtle.decrypt({name:$e,iv:Fe(Ce.decode(r))},a,Fe(Ce.decode(o)));return new TextDecoder().decode(i)}n(Se,"decryptSecret");var mu=d.union([ut,Vt]),fu=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:Kt.optional(),authorizationServerMetadata:d.union([dt,Wt]).optional()}).passthrough(),hu="Bearer",gu="__zuplo_refresh_only_upstream_access_token__";function yu(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(yu,"splitScopes");function _u(e){return Nt.parse(e)}n(_u,"parsePkceCodeVerifier");function wu(e){if(typeof e.expires_in=="number")return I(new Date(Date.now()+e.expires_in*1e3))}n(wu,"readTokenExpiry");async function Ru(e){if(e!==void 0)return pe(JSON.stringify(e))}n(Ru,"encryptJson");async function bu(e,t){if(!e)return;let r=await Se(e);try{return t.parse(JSON.parse(r))}catch(o){throw new f({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:o})}}n(bu,"decryptJson");function Iu(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(Iu,"clientInformationAllowsRedirectUri");function Cu(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(Cu,"clientInformationMatchesCurrentClientMetadataUrl");function Su(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(Su,"isUrlBasedClientInformation");function vu(e,t){return t===void 0?e:{...e,scope:t}}n(vu,"applyOAuthClientMetadataScope");function Au(e,t){return xa({state:e,delimiter:t})}n(Au,"readResourceMetadataScope");function xu(e,t){return e&&e.length>0?e.join(t):void 0}n(xu,"joinOAuthScopeList");function ku(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new H(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return ut.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(ku,"buildManualOAuthClientInformation");function Uu(e,t){let r=Zr({origin:new URL(t).origin,upstreamServerId:e});return Hr(r)?r:void 0}n(Uu,"buildClientMetadataUrl");function Tu(e){for(let t of e)if(t!==void 0)return t}n(Tu,"firstDefined");function Pu(e){let t=Je(e.target.upstreamServerId,e.target.authProfileId),r=xu(t.scopes,t.scopeDelimiter),o=Kr({origin:new URL(e.redirectUri).origin,upstreamServerId:e.target.upstreamServerId,redirectUri:e.redirectUri,scope:r});if(t.clientRegistration.mode==="manual")return{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,configuredClientInformation:ku({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let a=Uu(e.target.upstreamServerId,e.redirectUri);return a===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,clientMetadataUrl:a}}n(Pu,"buildInitialOAuthClientSetup");function Eu(e,t){if(t===void 0)return Tu([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(Eu,"readEncryptedClientInformation");var Oe=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredScope;scopeDelimiter;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;connection;pendingState;encryptedClientInformation;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;constructor(t){let r=Pu({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.clientMetadataValue=r.clientMetadata,this.configuredScope=r.configuredScope,this.scopeDelimiter=r.scopeDelimiter,this.configuredClientInformation=r.configuredClientInformation,r.clientMetadataUrl!==void 0&&(this.clientMetadataUrl=r.clientMetadataUrl),this.connection=t.connection,this.pendingState=t.pendingState?{...t.pendingState}:void 0,this.encryptedClientInformation=Eu(t,this.configuredClientInformation)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return vu(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return wa({id:t.id,...at({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId})})}async clientInformation(){return this.configuredClientInformation?this.configuredClientInformation:this.loadPersistedClientInformation()}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,ce()?.info({event:"upstream_oauth_client_registered",upstreamServerId:this.target.upstreamServerId,clientId:"client_id"in t?t.client_id:void 0,redirectUriCount:"redirect_uris"in t?t.redirect_uris.length:void 0},"Upstream OAuth client registered for the gateway"),!Su({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Ru(t),await this.syncPendingState(!1)))}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=va(fu.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,ce()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:U(r.authorizationServerUrl),resourceMetadataHost:U(r.resourceMetadataUrl),resource:r.resourceMetadata?.resource,scopesSupportedCount:r.resourceMetadata?.scopes_supported?.length,hasResourceMetadata:r.resourceMetadata!==void 0},"Upstream OAuth discovery resolved authorization server and resource"),this.inferredScope=Au(r,this.scopeDelimiter)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Ne.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,a=r.refresh_token?await pe(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:Ne.parse({...r,refresh_token:await Se(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let i={id:this.connection?.id??Ft(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await pe(r.access_token),encryptedRefreshToken:a,scopes:yu(r.scope??this.readEffectiveScope()),expiresAt:wu(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await b().upsertUpstreamConnection(i),ce()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionId:this.connection.id,hasRefreshToken:!!a,scopeCount:i.scopes.length,expiresAt:i.expiresAt},"Upstream OAuth tokens persisted; upstream connection is active")}async redirectToAuthorization(t){let r=Aa(t);this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:_u(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new f({message:"OAuth code verifier is missing",extensionMembers:{[g]:"oauth_state_invalid"}});return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",o=t==="all"||t==="client",a=t==="all"||t==="discovery",i=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),a&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.challengeScope=void 0,this.inferredScope=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(i),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:Po(),...at({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,operationId:this.target.operationId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:I(new Date(Date.now()+ga)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await b().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await bu(this.encryptedClientInformation,mu)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&(!Iu(t,this.redirectUriValue)||!Cu({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl}))){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}return t===void 0&&this.pendingState?.codeVerifier!==void 0&&this.clientMetadataUrl!==void 0&&(t=Vt.parse({client_id:this.clientMetadataUrl})),this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async readCachedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;this.discoveryStateLoaded=!0}readEffectiveScope(){return this.configuredScope??this.challengeScope??this.inferredScope}async loadStoredTokens(){if(this.tokensLoaded)return this.cachedTokens;if(this.tokensLoaded=!0,!this.connection||this.connection.status!=="active")return;let t=this.connection.encryptedAccessToken?await Se(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await Se(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=Ne.parse({access_token:t??gu,token_type:hu,refresh_token:r,scope:this.connection.scopes.length>0?this.connection.scopes.join(" "):void 0});return this.cachedTokens=o,o}async persistCredentialInvalidation(t){if(!this.connection)return;let r={id:this.connection.id,ownerMode:this.connection.ownerMode,subjectId:this.connection.subjectId,upstreamServerId:this.connection.upstreamServerId,authProfileId:this.connection.authProfileId,status:this.connection.status,encryptedAccessToken:this.connection.encryptedAccessToken,encryptedRefreshToken:this.connection.encryptedRefreshToken,scopes:[...this.connection.scopes],expiresAt:this.connection.expiresAt,metadata:this.connection.metadata?{...this.connection.metadata}:void 0};t&&(r.status="reconsent_required",r.encryptedAccessToken=void 0,r.encryptedRefreshToken=void 0,r.scopes=[],r.expiresAt=void 0),r.metadata=this.readStoredOAuthPersistence(this.connection.metadata?.connectedBySubjectId),this.connection=await b().upsertUpstreamConnection(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var Ou=3e4,qu=256*1024,Mu=2;function Du(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(Du,"hasUsableAccessToken");var zu="does not support dynamic client registration",ju=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],Hu=["HTTP 403 Forbidden","Access Denied","permission to access"],Bu=new Set(["access_denied","invalid_client","invalid_grant","invalid_request","invalid_scope","invalid_target","unauthorized_client","unsupported_grant_type"]);function Lu(e){return e instanceof Error&&e.message.includes(zu)}n(Lu,"isDynamicClientRegistrationUnsupported");function Nu(e){return e instanceof Error&&ju.some(t=>e.message.includes(t))}n(Nu,"isProtectedResourceMetadataUnavailable");function Ju(e){return e instanceof Error&&Hu.some(t=>e.message.includes(t))}n(Ju,"isUpstreamProviderAccessDenied");function Gu(e){return e instanceof A&&Bu.has(e.errorCode)}n(Gu,"isStoredConnectionReconsentError");function Fu(e){if(e.error instanceof f&&e.error.extensionMembers?.[g]!==void 0)return e.error;if(Lu(e.error))return new f({message:`The authorization server for ${e.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register an OAuth client for the gateway manually before retrying.`,extensionMembers:{[g]:"upstream_client_registration_required"}},{cause:e.error});if(Nu(e.error))return new f({message:`The upstream MCP server "${e.upstreamServerId}" does not publish OAuth protected resource metadata at "${e.resourceMetadataUrl}". Configure protectedResourceMetadataUrl to a working metadata document, use a provider-supported legacy client, or contact the provider to approve/allowlist this gateway OAuth client before retrying.`,extensionMembers:{[g]:"upstream_oauth_discovery_unavailable"}},{cause:e.error});if(Ju(e.error))return new f({message:`The upstream provider denied access while connecting ${e.upstreamServerId}. Confirm the provider allows this gateway and its OAuth client, then retry.`,extensionMembers:{[g]:"upstream_provider_access_denied"}},{cause:e.error})}n(Fu,"mapUpstreamOAuthSetupError");function $u(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n($u,"readOAuthFetchRequest");function Zu(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(Zu,"responseLooksJson");function Ku(e,t){let r=e.headers.get("content-type")??"",o=t.trimStart().toLowerCase();return r.includes("html")||o.startsWith("<!doctype html")||o.startsWith("<html")}n(Ku,"responseLooksHtml");function Wu(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new f({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[g]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[ye]:e.response.status,[ze]:r,[_e]:e.request.url.toString(),[je]:e.body}})}n(Wu,"throwUpstreamHtmlError");function Vu(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return{};let r=t;return{error:typeof r.error=="string"?r.error:void 0,errorDescription:typeof r.error_description=="string"?r.error_description:void 0}}catch{return{}}}n(Vu,"readUpstreamOAuthErrorBody");function Yu(e){let{error:t,errorDescription:r}=Vu(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.request.method??"GET",host:U(e.request.url),path:e.request.url.pathname,status:e.response.status,oauthError:t,oauthErrorDescription:r?.slice(0,256)},"Upstream OAuth HTTP request returned an error response")}n(Yu,"logUpstreamOAuthHttpError");function Ea(e){return async(t,r)=>{let o=$u(t),a=ce(),i=Date.now(),c=await ta(t,r,{maxRedirects:Mu,maxResponseBytes:qu,problemCode:"upstream_token_exchange_failed",timeoutMs:Ou}),s=await c.clone().text();if(a?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:o.method??"GET",host:U(o.url),path:o.url.pathname,status:c.status,durationMs:Date.now()-i,responseChars:s.length},"Upstream OAuth HTTP request completed"),c.ok||Yu({log:a,upstreamServerId:e,request:o,response:c,body:s}),!c.ok&&Ku(c,s)&&Wu({upstreamServerId:e,request:o,response:c,body:s}),!Zu(c,s))return c;try{JSON.parse(s)}catch(u){throw new f({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[g]:"upstream_token_exchange_failed"}},{cause:u})}return c}}n(Ea,"createUpstreamOAuthFetch");function Oa(e){ce()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:U(e.serverUrl),resourceMetadataHost:U(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}n(Oa,"logUpstreamOAuthFlowStarted");function qa(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=U(e.serverUrl);r!==void 0&&(t.serverHost=r);let o=e.error instanceof f?e.error.extensionMembers?.[g]:void 0;typeof o=="string"&&(t.code=o),L(t,"error",e.error),ce()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(qa,"logUpstreamOAuthFlowFailed");async function Ma(e,t){e.applyChallengeScope(t.requestedScope),Oa({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Ea(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),await jr(e,r)}catch(r){qa({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=Fu({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(Ma,"runUpstreamOAuth");async function Xu(e,t){e.applyChallengeScope(t.requestedScope),Oa({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Ea(t.upstreamServerId)};t.requestedScope!==void 0&&(r.scope=t.requestedScope);try{return await jr(e,r)}catch(o){throw qa({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:o}),o}}n(Xu,"exchangeUpstreamAuthorizationCode");async function Da(e,t){let r=await Ma(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new f({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new f({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Da,"requireUpstreamAuthorizationRedirect");async function za(e){if(!e.forceRefresh&&Du(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t;try{t=await Ma(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(r){if(e.connection===void 0||!Gu(r))throw r;return ce()?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:r.errorCode},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),{kind:"connect_required",payload:await Pa({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}if(t==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(t!=="REDIRECT")throw new f({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new f({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}});return{kind:"connect_required",payload:await Pa({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}n(za,"authorizeUpstreamOAuthSession");async function Qu(e){let t=await rr(e.stateToken),r=await b().consumeUpstreamOAuthState({id:t.id,now:I(new Date)}),o=el(r);return tl({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),rl(o),o}n(Qu,"consumeStoredCallbackState");function el(e){switch(e.kind){case"consumed":throw new f({message:"OAuth state has already been used",extensionMembers:{[g]:"oauth_state_reused"}});case"missing":throw new f({message:"OAuth state is missing or expired",extensionMembers:{[g]:"oauth_state_expired"}});case"available":return e.record}}n(el,"readConsumedCallbackState");function tl(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.operationId===e.signedState.operationId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw new f({message:"OAuth callback did not match the initiating request",extensionMembers:{[g]:"oauth_callback_mismatch"}})}n(tl,"assertStoredCallbackStateMatches");function rl(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new f({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}})}n(rl,"assertStoredCallbackStateFresh");async function Pa(e){if(e.owner.mode==="shared"){let r={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,requiresReconsent:!!e.connection};return e.connection!==void 0&&(r.connectionId=e.connection.id),Ca(r)}let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,subject:"tool",requiresReconsent:!!e.connection,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return e.connection!==void 0&&(t.connectionId=e.connection.id),nr(t)}n(Pa,"buildOAuthConnectRequiredResponse");async function ja(e){let t=await Qu({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Ht(t),[o]=await b().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),a={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};o!==void 0&&(a.connection=o);let i=new Oe(a),c=await Xu(i,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(c==="AUTHORIZED")return t;throw c!=="REDIRECT"?new f({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${c}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new f({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(ja,"finishUpstreamOAuthCallback");F();import{importPKCS8 as nl,SignJWT as ol}from"jose";var Ba=1e4,La=64*1024,Na=2,al=300,ee=d.string().min(1),il=d.object({access_token:ee,issued_token_type:d.literal(br),token_type:d.string().optional(),expires_in:d.number().int().positive().optional(),scope:ee.optional()}).passthrough(),sl=d.object({id_token:ee,token_type:ee.optional(),expires_in:d.number().int().positive().optional(),refresh_token:ee.optional(),scope:ee.optional()}).passthrough(),cl=d.object({access_token:ee,token_type:ee,expires_in:d.number().int().positive().optional(),scope:ee.optional(),resource:ee.optional(),refresh_token:ee.optional()}).passthrough();function Ha(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(Ha,"formEncodeClientCredential");function dl(e){return e.replaceAll("\\n",`
|
|
26
|
-
`)}n(dl,"normalizePem");async function ul(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??al,o=await nl(dl(e.clientAuth.privateKeyPem),t),a={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new ol({jti:crypto.randomUUID()}).setProtectedHeader(a).setIssuer(e.clientAuth.clientId).setSubject(e.clientAuth.clientId).setAudience(e.clientAuth.audience??e.tokenUrl).setIssuedAt().setExpirationTime(`${r}s`).sign(o)}n(ul,"createPrivateKeyJwtClientAssertion");async function ll(e){switch(e.clientAuth.method){case"client_secret_post":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_secret",e.clientAuth.clientSecret);return;case"client_secret_basic":{let t=Ha(e.clientAuth.clientId),r=Ha(e.clientAuth.clientSecret);e.headers.authorization=`Basic ${btoa(`${t}:${r}`)}`;return}case"private_key_jwt":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_assertion_type",Lt),e.form.set("client_assertion",await ul({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}n(ll,"appendClientAuthentication");async function Xr(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await ll({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}n(Xr,"buildFormRequest");function Ja(e){return(t,r)=>tr(t,r,{context:e,maxRedirects:Na,maxResponseBytes:La,problemCode:"upstream_token_exchange_failed",timeoutMs:Ba})}n(Ja,"defaultIdpFetchJson");function pl(e){return(t,r)=>ra(t,r,{context:e,maxRedirects:Na,maxResponseBytes:La,problemCode:"upstream_token_exchange_failed",timeoutMs:Ba})}n(pl,"defaultResourceAsFetchJson");function ar(e){let t={[g]:e.code,[_e]:e.tokenUrl};return e.response!==void 0&&(t[ye]=e.response.status),new f({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}n(ar,"runtimeError");function Qr(e){if(!e.response.ok)throw ar({code:"upstream_token_exchange_failed",message:(()=>{switch(e.stage){case"idp_refresh_token":return"IdP refresh-token grant failed while renewing the upstream ID-JAG subject token.";case"idp_token_exchange":return"IdP token exchange failed while requesting an upstream ID-JAG.";case"resource_as_jwt_bearer":return"Upstream Resource AS rejected the ID-JAG JWT-bearer exchange."}})(),tokenUrl:e.tokenUrl,response:e.response})}n(Qr,"assertTokenEndpointSucceeded");function ml(e){let t=sl.safeParse(e.json);if(!t.success)throw ar({code:"upstream_token_response_invalid",message:"IdP refresh-token grant returned an invalid subject-token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={idToken:t.data.id_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),t.data.scope!==void 0&&(r.scope=t.data.scope),r}n(ml,"parseIdpRefreshTokenResponse");function fl(e){let t=il.safeParse(e.json);if(!t.success)throw ar({code:"upstream_token_response_invalid",message:"IdP token exchange returned an invalid ID-JAG response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={assertion:t.data.access_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),r}n(fl,"parseIdJagTokenExchangeResponse");function hl(e){let t=cl.safeParse(e.json);if(!t.success)throw ar({code:"upstream_token_response_invalid",message:"Upstream Resource AS returned an invalid JWT-bearer token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={accessToken:t.data.access_token,tokenType:t.data.token_type};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),t.data.resource!==void 0&&(r.resource=t.data.resource),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),r}n(hl,"parseAccessTokenResponse");async function Ga(e){let t=new URLSearchParams({grant_type:Bt,requested_token_type:br,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,audience:e.audience});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope),e.authorizationDetails!==void 0&&t.set("authorization_details",JSON.stringify(e.authorizationDetails));let r=e.fetchJson??Ja(e.context),{response:o,json:a}=await r(e.idp.tokenUrl,await Xr({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return Qr({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),fl({json:a,response:o,tokenUrl:e.idp.tokenUrl})}n(Ga,"requestIdJag");async function Fa(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??Ja(e.context),{response:o,json:a}=await r(e.idp.tokenUrl,await Xr({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return Qr({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),ml({json:a,response:o,tokenUrl:e.idp.tokenUrl})}n(Fa,"refreshIdpSubjectToken");async function $a(e){let t=new URLSearchParams({grant_type:Re,assertion:e.assertion});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope);let r=e.fetchJson??pl(e.context),{response:o,json:a}=await r(e.resourceAs.tokenUrl,await Xr({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return Qr({response:o,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),hl({json:a,response:o,tokenUrl:e.resourceAs.tokenUrl})}n($a,"exchangeIdJagForAccessToken");function gl(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(gl,"hasUsableAccessToken");function yl(e){if(e.tokenType.toLowerCase()!=="bearer")throw new f({message:"Upstream Resource AS returned a token type the MCP gateway cannot send as a bearer token.",extensionMembers:{[g]:"upstream_token_response_invalid"}})}n(yl,"assertBearerToken");function _l(e,t){if(t===Le)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}n(_l,"hasExpiredSubjectToken");async function wl(e){let t=await Se(e.encryptedSubjectToken);if(e.subjectTokenType!==Le)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await Fa({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});return r.refreshToken===void 0?{connection:e.connection,subjectToken:r.idToken,subjectTokenType:it}:{connection:await b().upsertUpstreamConnection({id:e.connection.id,ownerMode:e.connection.ownerMode,subjectId:e.connection.subjectId,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,status:"active",encryptedAccessToken:e.connection.encryptedAccessToken,encryptedRefreshToken:e.connection.encryptedRefreshToken,scopes:e.connection.scopes,expiresAt:e.connection.expiresAt,metadata:{...e.connection.metadata??{},encryptedIdpSubjectToken:await pe(r.refreshToken),idpSubjectTokenType:Le,idpSubjectTokenExpiresAt:void 0}}),subjectToken:r.idToken,subjectTokenType:it}}n(wl,"resolveIdJagSubjectToken");async function Za(e){let t="preloadedConnection"in e?e.preloadedConnection:(await b().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(!e.forceRefresh&&gl(t))return{kind:"authorized",credential:{type:"bearer_token",token:await Se(t.encryptedAccessToken)}};let r=t?.metadata?.encryptedIdpSubjectToken,o=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||r===void 0||o===void 0||_l(t,o))return{kind:"connect_required",payload:{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,message:`An IdP subject-token binding is required for ${e.upstreamDisplayName} before this tool can use XAA / ID-JAG.`,nextAction:"admin_setup_required"}};let a=be(e.upstreamServerId),i=Xo(e.upstreamServerId,e.authProfileId),c=i.resourceAs.resource??a.transport.baseUrl,s=e.requestedScope??(i.scopes.length===0?void 0:i.scopes.join(i.scopeDelimiter)),u=await wl({connection:t,encryptedSubjectToken:r,subjectTokenType:o,idp:{tokenUrl:i.idp.tokenUrl},clientAuth:i.idp.clientAuth,context:e.context}),p=await Ga({idp:{tokenUrl:i.idp.tokenUrl},subjectToken:u.subjectToken,subjectTokenType:u.subjectTokenType,audience:i.resourceAs.audience,resource:c,scope:s,clientAuth:i.idp.clientAuth,context:e.context}),h=p.scope??s,y=await $a({resourceAs:{tokenUrl:i.resourceAs.tokenUrl},assertion:p.assertion,resource:c,scope:h,clientAuth:i.resourceAs.clientAuth,context:e.context});if(yl(y),t!==void 0){let T=y.scope??h;await b().upsertUpstreamConnection({id:u.connection.id,ownerMode:u.connection.ownerMode,subjectId:u.connection.subjectId,upstreamServerId:u.connection.upstreamServerId,authProfileId:u.connection.authProfileId,status:"active",encryptedAccessToken:await pe(y.accessToken),encryptedRefreshToken:u.connection.encryptedRefreshToken,scopes:T?.split(/[,\s]+/).filter(Boolean)??[],expiresAt:y.expiresIn===void 0?void 0:I(new Date(Date.now()+y.expiresIn*1e3)),metadata:u.connection.metadata})}return{kind:"authorized",credential:{type:"bearer_token",token:y.accessToken}}}n(Za,"authorizeUpstreamIdJagRequest");function Rl(e){return or(new URL(e.callbackPath,P(e.requestUrl,e.requestHeaders))).toString()}n(Rl,"buildGatewayOAuthRedirectUri");async function Ka(e){let t=be(e.upstreamServerId),r=Je(e.upstreamServerId,e.authProfileId),o=Rl({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),a="preloadedConnection"in e?e.preloadedConnection:(await b().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:a,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,returnTo:e.returnTo},redirectUri:o,returnOrigin:P(e.request.url,e.request.headers)}}}n(Ka,"prepareUpstreamOAuthRequest");async function Wa(e){let t=await Ka(e),r=new Oe({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Da(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Wa,"startUpstreamConnect");async function Va(e){let t=await Ka(e),r=new Oe({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return za({target:e,provider:r,connection:t.connection,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Va,"authorizeUpstreamRequest");async function Ze(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return Va({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo});case"id-jag":return Za({request:e.request,context:e.context,authMode:t.authMode,ownerMode:t.ownerMode,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,upstreamDisplayName:t.upstreamDisplayName,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo})}let r=t;throw new V(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(Ze,"resolveUpstreamCredentialForRoute");async function Ya(e){if(e.connectRequest.authMode==="id-jag")throw new V(`Upstream server ${e.connectRequest.upstreamServerId} uses XAA / ID-JAG and does not support browser OAuth connection flows.`);let t=await Wa({request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,operationId:e.connectRequest.operationId,returnTo:e.connectRequest.returnTo});return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}n(Ya,"startUpstreamConnectForRequest");async function Xa(e){let r=(await rr(e.callbackRequest.state)).authProfileId;if(Qt({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}).mode==="id-jag")throw new V(`Upstream server ${e.callbackRequest.upstreamServerId} uses XAA / ID-JAG and does not support OAuth callbacks.`);return ja({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:be(e.callbackRequest.upstreamServerId)})}n(Xa,"finishUpstreamCallbackForRequest");function bl(e){return{upstreamServerId:e.connection.upstreamServerId,operationId:e.operationId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(bl,"buildRouteAuthBaseFromConnection");function Qa(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:oo(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(Qa,"buildRouteAuthBaseFromPolicyOptions");function ir(e,t){let o=Y().byOperationId.get(t);if(!o)throw new H(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new H(`MCP route "${t}" does not declare an MCP token exchange policy. Add one before starting an upstream connection flow.`);if(o.connection.upstreamServerId!==e)throw new H(`MCP route "${t}" does not bind upstream "${e}". Check the route's MCP upstream policies and bind the upstream before starting an upstream connection flow.`);return bl({connection:o.connection,operationId:t})}n(ir,"resolveRouteAuthBase");function en(e,t){switch(e){case"user":return He(t);case"shared":return ro()}}n(en,"buildOwnerForSubject");function Ke(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:en("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:en("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:en("user",t),initiatedBySubjectId:t}}}n(Ke,"resolveRouteAuthForSubject");var Il=nt.InvalidRequest,Cl=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function Sl(e,t){return{credentialType:e.type,forceRefresh:t}}n(Sl,"buildCredentialResolvedAttributes");function vl(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(vl,"connectRequiredReasonCode");function ei(e){v(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:Sl(e.credential,e.forceRefresh===!0)})}n(ei,"emitCredentialResolvedAnalyticsEvent");function ti(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(v(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"connect_required",reasonClass:"auth",attributes:t}),e.payload.state==="reconsent_required"){v(e.context,{eventType:C.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}v(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:vl(e.payload.state),reasonClass:"auth",attributes:t})}n(ti,"emitCredentialMissingAnalyticsEvents");function Al(e){let t=e.route.raw();return Dt.parse(t?.operationId)}n(Al,"readOperationId");async function xl(e,t,r,o){let a=await Ze({request:e,context:o,routeAuth:t});if(a.kind==="connect_required")return ti({context:o,payload:a.payload,routeBinding:t}),o.log.info({event:"mcp_upstream_connect_required",upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId},"MCP upstream proxy: upstream connection required"),{kind:"connect_required",payload:a.payload};let i=a.credential;if(ei({context:o,credential:i,routeBinding:t}),i.type==="bearer_token")return{kind:"headers",headers:[["authorization",`Bearer ${i.token}`]]};let c=await i.provider.tokens();return c?{kind:"headers",headers:[["authorization",`${c.token_type??"Bearer"} ${c.access_token}`]]}:(o.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:t.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),Response.json({error:"no_upstream_tokens"},{status:401}))}n(xl,"buildCredentialHeaders");var kl=new Set(["authorization","cookie","cookie2"]);function Ul(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return t&&typeof t=="object"&&!Array.isArray(t)&&"method"in t&&typeof t.method=="string"?t.method:void 0}catch{return}}n(Ul,"readJsonRequestMethod");function Tl(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(Tl,"isJsonResponse");function tn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(tn,"isRecord");function Pl(e){return Array.isArray(e)&&e.length>0}n(Pl,"hasIconList");function El(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=Xt(Wn(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(El,"readFallbackServerIcons");function Ol(e){if(!tn(e.body))return e.body;let t=e.body.result;if(!tn(t))return e.body;let r=t.serverInfo;return!tn(r)||Pl(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n(Ol,"addMissingServerIcons");function ql(e,t){let r=new Headers(e.headers);for(let o of kl)r.delete(o);for(let[o,a]of t)r.set(o,a);return new qn(e,{headers:r})}n(ql,"applyUpstreamHeaders");function Ml(e){let t=new Headers(e.headers);for(let r of Cl)t.delete(r);return t}n(Ml,"buildProxyHeaders");async function Dl(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(Dl,"readRetryBody");function ri(e,t){let r=t.authUrl===void 0?void 0:Mo({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json($t({id:qo(e),error:{code:r?.code??Il,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(ri,"connectRequiredJsonRpcResponse");async function zl(e){let{scope:t}=Zo(e.upstreamResponse),r=await Ze({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="connect_required")return ti({context:e.context,payload:r.payload,routeBinding:e.routeAuth,forceRefresh:!0}),{kind:"connect_required",payload:r.payload};let o=new Headers(e.headers),a=r.credential;if(ei({context:e.context,credential:a,routeBinding:e.routeAuth,forceRefresh:!0}),a.type==="bearer_token")return o.set("authorization",`Bearer ${a.token}`),{kind:"headers",headers:o};let i=await a.provider.tokens();return i?(o.set("authorization",`${i.token_type??"Bearer"} ${i.access_token}`),{kind:"headers",headers:o}):(e.context.log.warn({event:"mcp_upstream_no_tokens_after_refresh",upstreamServerId:e.routeAuth.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens after refresh"),{kind:"response",response:Response.json({error:"no_upstream_tokens"},{status:401})})}n(zl,"applyRefreshedCredentialHeaders");function jl(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await zl({request:e.request,context:e.context,headers:Ml(r),routeAuth:e.routeAuth,upstreamResponse:t});if(o.kind==="connect_required")return ri(e.requestBody,o.payload);if(o.kind==="response")return o.response;let a=Vn({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return Pt.fetch(a.url,a.init)})}n(jl,"installUpstreamAuthRetryHook");function Hl(e){if(Ul(e.requestBody)!=="initialize")return;let t=El({connection:e.connection,context:e.context});t===void 0||t.length===0||e.context.addResponseSendingHook(async r=>{if(!Tl(r))return r;let o;try{o=await r.clone().json()}catch{return r}let a=Ol({body:o,icons:t});if(a===o)return r;let i=new Headers(r.headers);return i.delete("content-length"),new Response(JSON.stringify(a),{status:r.status,statusText:r.statusText,headers:i})})}n(Hl,"installInitializeIconHook");async function rn(e,t,r){let o=Al(t),a=await Dl(e),i=Qa({connection:r,operationId:o}),c=ke(e.user,e.url,e.headers);t.log.setLogProperties?.({requestId:t.requestId}),lo(t,c);let s=Ke(i,c.subjectId),u=await xl(e,s,r,t);if(!(u instanceof Response)&&u.kind==="connect_required")return ri(a,u.payload);if(u instanceof Response)return u;let p=ql(e,u.headers);return jl({request:p,context:t,requestBody:a,routeAuth:s}),Hl({context:t,requestBody:a,connection:r}),p}n(rn,"mcpTokenExchangePolicy");var nn=class extends Et{static{n(this,"McpTokenExchangeInboundPolicy")}constructor(t,r){let o=ao(t,r);super(o,r)}async handler(t,r){return G("policy.inbound.mcp-token-exchange"),rn(t,r,this.options)}};F();var ni=Symbol("Html");function Bl(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}n(Bl,"escapeHtml");function Ll(e){return e===null||typeof e!="object"?!1:e[ni]===!0}n(Ll,"isHtml");function oi(e){return e==null||e===!1?"":Array.isArray(e)?e.map(oi).join(""):Ll(e)?e.value:Bl(String(e))}n(oi,"renderValue");function me(e){return{[ni]:!0,value:e}}n(me,"trustedHtml");var X=me("");function S(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=oi(t[o]),r+=e[o+1]??"";return me(r)}n(S,"html");function We(e){return e.value}n(We,"renderHtml");function ai(e){return S`<p class="card__description">${e.detail}</p>${e.guidance} ${e.technicalDetails} ${e.action}`}n(ai,"renderBrowserErrorPage");var Ve=me('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;justify-content:center;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;min-height:40px;padding:8px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.reconnect-action{align-items:center;margin-right:auto;display:inline-flex;position:relative}.reconnect-button{gap:7px}.tooltip{width:16px;height:16px;color:var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);cursor:help;border:1.5px solid;border-radius:50%;justify-content:center;align-items:center;font-size:10.5px;font-weight:700;line-height:1;display:inline-flex;position:relative}.tooltip:after{content:attr(aria-label);z-index:10;border-radius:var(--radius-sm);background:var(--accent);width:280px;max-width:min(280px,100vw - 48px);color:var(--accent-text);box-shadow:var(--shadow);text-align:left;white-space:normal;opacity:0;pointer-events:none;padding:12px 14px;font-size:13px;font-weight:600;line-height:1.45;transition:opacity .12s;position:absolute;bottom:calc(100% + 12px);left:50%;transform:translate(-50%)}.tooltip:before{content:"";z-index:11;border-left:7px solid #0000;border-right:7px solid #0000;border-top:8px solid var(--accent);opacity:0;pointer-events:none;transition:opacity .12s;position:absolute;bottom:calc(100% + 5px);left:50%;transform:translate(-50%)}.tooltip:hover:after,.tooltip:hover:before,.tooltip:focus-visible:after,.tooltip:focus-visible:before{opacity:1}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}.reconnect-action{justify-content:center;width:100%;margin-right:0}.reconnect-action .button{flex:1}.tooltip:after{left:auto;right:0;transform:none}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function Ye(e){return S`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" href="${e.iconHref}" /><style>
|
|
25
|
+
import{$b as it,$c as ko,Ab as Qn,Ac as Sr,Bb as se,Bc as Gt,Cb as w,Cc as ct,Db as Ht,Dc as Ge,Eb as B,Ec as _o,Fb as Re,Fc as ue,G as Bn,Gb as pc,Gc as vr,H as l,Hb as mc,Hc as Ar,I as Ln,Ib as fc,Ic as wo,J as Rr,Jb as hc,Jc as Ft,K as ie,Kb as gc,Kc as xr,L as Nn,Lb as yc,Lc as kr,M as _,Mb as _c,Mc as Ro,N as ye,Nb as wc,Nc as E,O as Dt,Ob as Rc,Oc as bo,P as Jn,Pb as bc,Pc as Io,Q as Gn,Qb as eo,Qc as Tr,R as Fn,Rb as to,Rc as Co,S as d,Sb as ro,Sc as So,T as F,Tb as jt,Tc as Ur,Ub as br,Uc as vo,Vb as Bt,Vc as Te,Wb as Lt,Wc as Ao,Xb as at,Xc as dt,Yb as no,Yc as xo,Z as $n,Zb as oo,Zc as $t,_b as ao,_c as ut,a as G,ac as io,ad as To,bc as Ne,bd as Uo,cc as so,cd as Po,dc as Ir,dd as Eo,ec as co,ed as Oo,fc as st,fd as qo,gc as Nt,gd as Zt,hc as uo,hd as Mo,i as ke,ic as lo,id as Do,j as zn,jb as Zn,jc as po,jd as b,kb as $,kc as mo,kd as v,l as Hn,lb as Kn,lc as X,ld as Z,mb as Wn,mc as H,md as le,nb as P,nc as fo,nd as x,ob as Vn,oc as ho,od as Kt,p as jn,pb as He,pc as I,pd as Ic,qb as Yn,qc as ce,qd as Cc,r as Mt,rb as je,rc as Je,sb as g,sc as L,tb as Be,tc as T,ub as Le,uc as go,vb as _e,vc as de,wb as we,wc as yo,xb as zt,xc as be,yb as Xn,yc as Cr,zb as ee,zc as Jt}from"../chunk-LM6CZZF3.js";import"../chunk-DQ4ANJLR.js";import{a as C}from"../chunk-2Y72LML3.js";import{$ as Y,a as n,aa as f,ba as j,ca as Dn,da as qt}from"../chunk-L3MZGNQA.js";F();function Sc(e){let t=Lt.safeParse(e);return t.success?t.data.id:void 0}n(Sc,"parseJsonRpcRequestId");function zo(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Sc(t)}catch{return}}n(zo,"readJsonRpcRequestIdFromBody");function Wt(e){return no.parse({jsonrpc:Bt,...e.id===void 0?{}:{id:e.id},error:{code:e.error.code,message:e.error.message,...e.error.data===void 0?{}:{data:e.error.data}}})}n(Wt,"jsonRpcErrorResponse");function Ho(e){return new ao([oo.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Ho,"urlElicitationRequiredError");var Vt=d.record(d.string(),d.unknown()),vc=d.record(d.string(),d.unknown()),Ac=d.object({name:d.string().min(1),description:d.string().min(1).optional(),annotations:vc.optional(),_meta:Vt.optional()}).strict(),xc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),_meta:Vt.optional()}).strict(),kc=d.object({uri:d.string().min(1),name:d.string().min(1).optional(),description:d.string().min(1).optional(),mimeType:d.string().min(1).optional(),_meta:Vt.optional()}).strict(),Tc=d.object({uriTemplate:d.string().min(1),name:d.string().min(1).optional(),description:d.string().min(1).optional(),mimeType:d.string().min(1).optional(),_meta:Vt.optional()}).strict(),Uc=d.array(d.union([d.string(),Ac])),Pc=d.array(d.union([d.string(),xc])),Ec=d.array(d.union([d.string(),kc])),Oc=d.array(d.union([d.string(),Tc])),qc=d.object({tools:Uc.optional(),prompts:Pc.optional(),resources:Ec.optional(),resourceTemplates:Oc.optional()}).strict(),Er=[{option:"tools",listMethod:"tools/list",resultProperty:"tools",itemProperty:"name",directMethods:[{method:"tools/call",paramProperty:"name"}]},{option:"prompts",listMethod:"prompts/list",resultProperty:"prompts",itemProperty:"name",directMethods:[{method:"prompts/get",paramProperty:"name"}]},{option:"resources",listMethod:"resources/list",resultProperty:"resources",itemProperty:"uri",directMethods:[{method:"resources/read",paramProperty:"uri"}]},{option:"resourceTemplates",listMethod:"resources/templates/list",resultProperty:"resourceTemplates",itemProperty:"uriTemplate",directMethods:[]}];function Mc(e,t){return Kn(qc,e,`MCP capability filter policy "${t}"`)}n(Mc,"parseMcpCapabilityFilterOptions");function N(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(N,"isRecord");function Dc(e,t){if(!N(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(Dc,"readParamString");function Or(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(Or,"readRequestId");function No(e){return e===void 0?void 0:JSON.stringify(e)}n(No,"requestIdKey");function zc(e){let t={};for(let r of Er){let o=e[r.option];if(o===void 0)continue;let a=new Map;for(let i of o){let c=Lc(i,r.itemProperty);c!==void 0&&a.set(c.key,c)}t[r.option]=a}return t}n(zc,"buildProjectionMaps");function qr(e){return Er.find(t=>t.listMethod===e)}n(qr,"findListRule");function Hc(e){return e.requests.some(t=>{if(!N(t))return!1;let r=qr(t.method);return r!==void 0&&e.projectionMaps[r.option]!==void 0})}n(Hc,"shouldFilterListResponses");function jc(e){for(let t of Er){let r=e.projectionMaps[t.option];if(r!==void 0)for(let o of t.directMethods){if(e.request.method!==o.method)continue;let a=Dc(e.request.params,o.paramProperty);if(a!==void 0&&!r.has(a))return{id:Or(e.request)}}}}n(jc,"findDisallowedDirectAccess");function Bc(e){return Response.json(Wt({id:e,error:{code:at.MethodNotFound,message:"Method not found"}}))}n(Bc,"methodNotFoundResponse");function Lc(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!N(e))return;let r=e[t];if(typeof r=="string")return{key:r,overlay:e}}n(Lc,"buildProjection");function jo(e){let t=e.base[e.property],r=e.overlay[e.property];return N(r)?N(t)?{...t,...r}:r:t}n(jo,"mergeRecordProperty");function Nc(e,t){let r={...e,...t.overlay},o=jo({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let a=jo({base:e,overlay:t.overlay,property:"_meta"});return a!==void 0&&(r._meta=a),r}n(Nc,"applyProjection");function Bo(e,t,r){if(!N(e))return e;let o=e.result;if(!N(o))return e;let a=o[t.resultProperty];return!Array.isArray(a)||!a.every(i=>N(i)&&typeof i[t.itemProperty]=="string")?e:{...e,result:{...o,[t.resultProperty]:a.flatMap(i=>{if(!N(i))return[];let c=i[t.itemProperty];if(typeof c!="string")return[];let s=r.get(c);return s===void 0?[]:[Nc(i,s)]})}}}n(Bo,"filterAndProjectItems");function Jc(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!N(r))continue;let o=qr(r.method),a=Or(r),i=No(a);o!==void 0&&i!==void 0&&t.set(i,o)}return t}n(Jc,"buildListRulesByResponseId");function Gc(e){if(Array.isArray(e.responseBody)){let o=Jc(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(a=>{if(!N(a)||"error"in a)return a;let i=No(Or(a)),c=i===void 0?void 0:o.get(i),s=c===void 0?void 0:e.projectionMaps[c.option];return c===void 0||s===void 0?a:Bo(a,c,s)})}if(!N(e.requestBody)||!N(e.responseBody)||"error"in e.responseBody)return e.responseBody;let t=qr(e.requestBody.method),r=t===void 0?void 0:e.projectionMaps[t.option];return t===void 0||r===void 0?e.responseBody:Bo(e.responseBody,t,r)}n(Gc,"filterJsonRpcResponse");async function Lo(e){return e.clone().json()}n(Lo,"readJson");function Fc(e){return e.headers.get("content-type")?.includes("json")??!1}n(Fc,"isJsonResponse");var Pr=class extends Mt{static{n(this,"McpCapabilityFilterInboundPolicy")}#e;constructor(t,r){let o=Mc(t,r);super(o,r),this.#e=zc(o)}async handler(t,r){G("policy.inbound.mcp-capability-filter");let o;try{o=await Lo(t)}catch{return t}let a=Array.isArray(o)?o:[o];for(let i of a){if(!N(i))continue;let c=jc({request:i,projectionMaps:this.#e});if(c!==void 0)return Bc(c.id)}return Hc({requests:a,projectionMaps:this.#e})&&r.addResponseSendingHook(async i=>{if(!Fc(i))return i;let c;try{c=await Lo(i)}catch{return i}let s=Gc({requestBody:o,responseBody:c,projectionMaps:this.#e});if(s===c)return i;let u=new Headers(i.headers);return u.delete("content-length"),new Response(JSON.stringify(s),{status:i.status,statusText:i.statusText,headers:u})}),t}};var Mr;Mr=globalThis.crypto;async function $c(e){return(await Mr).getRandomValues(new Uint8Array(e))}n($c,"getRandomValues");async function Zc(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let a=await $c(e-o.length);for(let i of a)i<r&&(o+=t[i%t.length])}return o}n(Zc,"random");async function Kc(e){return await Zc(e)}n(Kc,"generateVerifier");async function Wc(e){let t=await(await Mr).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(Wc,"generateChallenge");async function Dr(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await Kc(e),r=await Wc(t);return{code_verifier:t,code_challenge:r}}n(Dr,"pkceChallenge");F();var D=Ln().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Gn.custom,message:"URL must be parseable",fatal:!0}),Bn}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Yt=Dt({resource:l().url(),authorization_servers:_(D).optional(),jwks_uri:l().url().optional(),scopes_supported:_(l()).optional(),bearer_methods_supported:_(l()).optional(),resource_signing_alg_values_supported:_(l()).optional(),resource_name:l().optional(),resource_documentation:l().optional(),resource_policy_uri:l().url().optional(),resource_tos_uri:l().url().optional(),tls_client_certificate_bound_access_tokens:ie().optional(),authorization_details_types_supported:_(l()).optional(),dpop_signing_alg_values_supported:_(l()).optional(),dpop_bound_access_tokens_required:ie().optional()}),lt=Dt({issuer:l(),authorization_endpoint:D,token_endpoint:D,registration_endpoint:D.optional(),scopes_supported:_(l()).optional(),response_types_supported:_(l()),response_modes_supported:_(l()).optional(),grant_types_supported:_(l()).optional(),token_endpoint_auth_methods_supported:_(l()).optional(),token_endpoint_auth_signing_alg_values_supported:_(l()).optional(),service_documentation:D.optional(),revocation_endpoint:D.optional(),revocation_endpoint_auth_methods_supported:_(l()).optional(),revocation_endpoint_auth_signing_alg_values_supported:_(l()).optional(),introspection_endpoint:l().optional(),introspection_endpoint_auth_methods_supported:_(l()).optional(),introspection_endpoint_auth_signing_alg_values_supported:_(l()).optional(),code_challenge_methods_supported:_(l()).optional(),client_id_metadata_document_supported:ie().optional()}),Vc=Dt({issuer:l(),authorization_endpoint:D,token_endpoint:D,userinfo_endpoint:D.optional(),jwks_uri:D,registration_endpoint:D.optional(),scopes_supported:_(l()).optional(),response_types_supported:_(l()),response_modes_supported:_(l()).optional(),grant_types_supported:_(l()).optional(),acr_values_supported:_(l()).optional(),subject_types_supported:_(l()),id_token_signing_alg_values_supported:_(l()),id_token_encryption_alg_values_supported:_(l()).optional(),id_token_encryption_enc_values_supported:_(l()).optional(),userinfo_signing_alg_values_supported:_(l()).optional(),userinfo_encryption_alg_values_supported:_(l()).optional(),userinfo_encryption_enc_values_supported:_(l()).optional(),request_object_signing_alg_values_supported:_(l()).optional(),request_object_encryption_alg_values_supported:_(l()).optional(),request_object_encryption_enc_values_supported:_(l()).optional(),token_endpoint_auth_methods_supported:_(l()).optional(),token_endpoint_auth_signing_alg_values_supported:_(l()).optional(),display_values_supported:_(l()).optional(),claim_types_supported:_(l()).optional(),claims_supported:_(l()).optional(),service_documentation:l().optional(),claims_locales_supported:_(l()).optional(),ui_locales_supported:_(l()).optional(),claims_parameter_supported:ie().optional(),request_parameter_supported:ie().optional(),request_uri_parameter_supported:ie().optional(),require_request_uri_registration:ie().optional(),op_policy_uri:D.optional(),op_tos_uri:D.optional(),client_id_metadata_document_supported:ie().optional()}),Xt=ye({...Vc.shape,...lt.pick({code_challenge_methods_supported:!0}).shape}),Fe=ye({access_token:l(),id_token:l().optional(),token_type:l(),expires_in:Fn.number().optional(),scope:l().optional(),refresh_token:l().optional()}).strip(),Go=ye({error:l(),error_description:l().optional(),error_uri:l().optional()}),Jo=D.optional().or(Jn("").transform(()=>{})),Yc=ye({redirect_uris:_(D),token_endpoint_auth_method:l().optional(),grant_types:_(l()).optional(),response_types:_(l()).optional(),client_name:l().optional(),client_uri:D.optional(),logo_uri:Jo,scope:l().optional(),contacts:_(l()).optional(),tos_uri:Jo,policy_uri:l().optional(),jwks_uri:D.optional(),jwks:Nn().optional(),software_id:l().optional(),software_version:l().optional(),software_statement:l().optional()}).strip(),Qt=ye({client_id:l(),client_secret:l().optional(),client_id_issued_at:Rr().optional(),client_secret_expires_at:Rr().optional()}).strip(),pt=Yc.merge(Qt),Jh=ye({error:l(),error_description:l().optional()}).strip(),Gh=ye({token:l(),token_type_hint:l().optional()}).strip();function Fo(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(Fo,"resourceUrlFromServerUrl");function $o({requestedResource:e,configuredResource:t}){let r=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(r.origin!==o.origin||r.pathname.length<o.pathname.length)return!1;let a=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return a.startsWith(i)}n($o,"checkResourceAllowed");var A=class extends Error{static{n(this,"OAuthError")}constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},mt=class extends A{static{n(this,"InvalidRequestError")}};mt.errorCode="invalid_request";var Ue=class extends A{static{n(this,"InvalidClientError")}};Ue.errorCode="invalid_client";var Pe=class extends A{static{n(this,"InvalidGrantError")}};Pe.errorCode="invalid_grant";var Ee=class extends A{static{n(this,"UnauthorizedClientError")}};Ee.errorCode="unauthorized_client";var ft=class extends A{static{n(this,"UnsupportedGrantTypeError")}};ft.errorCode="unsupported_grant_type";var ht=class extends A{static{n(this,"InvalidScopeError")}};ht.errorCode="invalid_scope";var gt=class extends A{static{n(this,"AccessDeniedError")}};gt.errorCode="access_denied";var pe=class extends A{static{n(this,"ServerError")}};pe.errorCode="server_error";var yt=class extends A{static{n(this,"TemporarilyUnavailableError")}};yt.errorCode="temporarily_unavailable";var _t=class extends A{static{n(this,"UnsupportedResponseTypeError")}};_t.errorCode="unsupported_response_type";var wt=class extends A{static{n(this,"UnsupportedTokenTypeError")}};wt.errorCode="unsupported_token_type";var Rt=class extends A{static{n(this,"InvalidTokenError")}};Rt.errorCode="invalid_token";var bt=class extends A{static{n(this,"MethodNotAllowedError")}};bt.errorCode="method_not_allowed";var It=class extends A{static{n(this,"TooManyRequestsError")}};It.errorCode="too_many_requests";var Oe=class extends A{static{n(this,"InvalidClientMetadataError")}};Oe.errorCode="invalid_client_metadata";var Ct=class extends A{static{n(this,"InsufficientScopeError")}};Ct.errorCode="insufficient_scope";var St=class extends A{static{n(this,"InvalidTargetError")}};St.errorCode="invalid_target";var Zo={[mt.errorCode]:mt,[Ue.errorCode]:Ue,[Pe.errorCode]:Pe,[Ee.errorCode]:Ee,[ft.errorCode]:ft,[ht.errorCode]:ht,[gt.errorCode]:gt,[pe.errorCode]:pe,[yt.errorCode]:yt,[_t.errorCode]:_t,[wt.errorCode]:wt,[Rt.errorCode]:Rt,[bt.errorCode]:bt,[It.errorCode]:It,[Oe.errorCode]:Oe,[Ct.errorCode]:Ct,[St.errorCode]:St};function Xc(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(Xc,"isClientAuthMethod");var zr="code",Hr="S256";function Qc(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&Xc(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}n(Qc,"selectClientAuthMethod");function ed(e,t,r,o){let{client_id:a,client_secret:i}=t;switch(e){case"client_secret_basic":td(a,i,r);return;case"client_secret_post":rd(a,i,o);return;case"none":nd(a,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(ed,"applyClientAuthentication");function td(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${o}`)}n(td,"applyBasicAuth");function rd(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(rd,"applyPostAuth");function nd(e,t){t.set("client_id",e)}n(nd,"applyPublicAuth");async function Wo(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Go.parse(JSON.parse(r)),{error:a,error_description:i,error_uri:c}=o,s=Zo[a]||pe;return new s(i||"",c)}catch(o){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new pe(a)}}n(Wo,"parseErrorResponse");async function Lr(e,t){try{return await jr(e,t)}catch(r){if(r instanceof Ue||r instanceof Ee)return await e.invalidateCredentials?.("all"),await jr(e,t);if(r instanceof Pe)return await e.invalidateCredentials?.("tokens"),await jr(e,t);throw r}}n(Lr,"auth");async function jr(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:a,fetchFn:i}){let c=await e.discoveryState?.(),s,u,p,h=a;if(!h&&c?.resourceMetadataUrl&&(h=new URL(c.resourceMetadataUrl)),c?.authorizationServerUrl){if(u=c.authorizationServerUrl,s=c.resourceMetadata,p=c.authorizationServerMetadata??await Xo(u,{fetchFn:i}),!s)try{s=await Yo(t,{resourceMetadataUrl:h},i)}catch{}(p!==c.authorizationServerMetadata||s!==c.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:h?.toString(),resourceMetadata:s,authorizationServerMetadata:p})}else{let M=await dd(t,{resourceMetadataUrl:h,fetchFn:i});u=M.authorizationServerUrl,p=M.authorizationServerMetadata,s=M.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:h?.toString(),resourceMetadata:s,authorizationServerMetadata:p})}let y=await od(t,e,s),U=o||s?.scopes_supported?.join(" ")||e.clientMetadata.scope,R=await Promise.resolve(e.clientInformation());if(!R){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let M=p?.client_id_metadata_document_supported===!0,z=e.clientMetadataUrl;if(z&&!Nr(z))throw new Oe(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${z}`);if(M&&z)R={client_id:z},await e.saveClientInformation?.(R);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Mn=await fd(u,{metadata:p,clientMetadata:e.clientMetadata,scope:U,fetchFn:i});await e.saveClientInformation(Mn),R=Mn}}let q=!e.redirectUrl;if(r!==void 0||q){let M=await md(e,u,{metadata:p,resource:y,authorizationCode:r,fetchFn:i});return await e.saveTokens(M),"AUTHORIZED"}let O=await e.tokens();if(O?.refresh_token)try{let M=await pd(u,{metadata:p,clientInformation:R,refreshToken:O.refresh_token,resource:y,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(M),"AUTHORIZED"}catch(M){if(!(!(M instanceof A)||M instanceof pe))throw M}let oe=e.state?await e.state():void 0,{authorizationUrl:ot,codeVerifier:ae}=await ud(u,{metadata:p,clientInformation:R,state:oe,redirectUrl:e.redirectUrl,scope:U,resource:y});return await e.saveCodeVerifier(ae),await e.redirectToAuthorization(ot),"REDIRECT"}n(jr,"authInternal");function Nr(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(Nr,"isHttpsUrl");async function od(e,t,r){let o=Fo(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!$o({requestedResource:o,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${o} (or origin)`);return new URL(r.resource)}}n(od,"selectResourceURL");function Vo(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let a=Br(e,"resource_metadata")||void 0,i;if(a)try{i=new URL(a)}catch{}let c=Br(e,"scope")||void 0,s=Br(e,"error")||void 0;return{resourceMetadataUrl:i,scope:c,error:s}}n(Vo,"extractWWWAuthenticateParams");function Br(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),a=r.match(o);return a?a[1]||a[2]:null}n(Br,"extractFieldFromWwwAuth");async function Yo(e,t,r=fetch){let o=await sd(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.body?.cancel(),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return Yt.parse(await o.json())}n(Yo,"discoverOAuthProtectedResourceMetadata");async function Jr(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?Jr(e,void 0,r):void 0;throw o}}n(Jr,"fetchWithCorsRetry");function ad(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(ad,"buildWellKnownPath");async function Ko(e,t,r=fetch){return await Jr(e,{"MCP-Protocol-Version":t},r)}n(Ko,"tryMetadataDiscovery");function id(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(id,"shouldAttemptFallback");async function sd(e,t,r,o){let a=new URL(e),i=o?.protocolVersion??br,c;if(o?.metadataUrl)c=new URL(o.metadataUrl);else{let u=ad(t,a.pathname);c=new URL(u,o?.metadataServerUrl??a),c.search=a.search}let s=await Ko(c,i,r);if(!o?.metadataUrl&&id(s,a.pathname)){let u=new URL(`/.well-known/${t}`,a);s=await Ko(u,i,r)}return s}n(sd,"discoverMetadataWithFallback");function cd(e){let t=typeof e=="string"?new URL(e):e,r=t.pathname!=="/",o=[];if(!r)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let a=t.pathname;return a.endsWith("/")&&(a=a.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${a}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${a}`,t.origin),type:"oidc"}),o.push({url:new URL(`${a}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(cd,"buildDiscoveryUrls");async function Xo(e,{fetchFn:t=fetch,protocolVersion:r=br}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},a=cd(e);for(let{url:i,type:c}of a){let s=await Jr(i,o,t);if(s){if(!s.ok){if(await s.body?.cancel(),s.status>=400&&s.status<500)continue;throw new Error(`HTTP ${s.status} trying to load ${c==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return c==="oauth"?lt.parse(await s.json()):Xt.parse(await s.json())}}}n(Xo,"discoverAuthorizationServerMetadata");async function dd(e,t){let r,o;try{r=await Yo(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(o=r.authorization_servers[0])}catch{}o||(o=String(new URL("/",e)));let a=await Xo(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:a,resourceMetadata:r}}n(dd,"discoverOAuthServerInfo");async function ud(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:a,state:i,resource:c}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(zr))throw new Error(`Incompatible auth server: does not support response type ${zr}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Hr))throw new Error(`Incompatible auth server: does not support code challenge method ${Hr}`)}else s=new URL("/authorize",e);let u=await Dr(),p=u.code_verifier,h=u.code_challenge;return s.searchParams.set("response_type",zr),s.searchParams.set("client_id",r.client_id),s.searchParams.set("code_challenge",h),s.searchParams.set("code_challenge_method",Hr),s.searchParams.set("redirect_uri",String(o)),i&&s.searchParams.set("state",i),a&&s.searchParams.set("scope",a),a?.includes("offline_access")&&s.searchParams.append("prompt","consent"),c&&s.searchParams.set("resource",c.href),{authorizationUrl:s,codeVerifier:p}}n(ud,"startAuthorization");function ld(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(ld,"prepareAuthorizationCodeRequest");async function Qo(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:a,resource:i,fetchFn:c}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),u=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&r.set("resource",i.href),a)await a(u,r,s,t);else if(o){let h=t?.token_endpoint_auth_methods_supported??[],y=Qc(o,h);ed(y,o,u,r)}let p=await(c??fetch)(s,{method:"POST",headers:u,body:r});if(!p.ok)throw await Wo(p);return Fe.parse(await p.json())}n(Qo,"executeTokenRequest");async function pd(e,{metadata:t,clientInformation:r,refreshToken:o,resource:a,addClientAuthentication:i,fetchFn:c}){let s=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),u=await Qo(e,{metadata:t,tokenRequestParams:s,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:c});return{refresh_token:o,...u}}n(pd,"refreshAuthorization");async function md(e,t,{metadata:r,resource:o,authorizationCode:a,fetchFn:i}={}){let c=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(c)),!s){if(!a)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let p=await e.codeVerifier();s=ld(a,p,e.redirectUrl)}let u=await e.clientInformation();return Qo(t,{metadata:r,tokenRequestParams:s,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:i})}n(md,"fetchToken");async function fd(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:a}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let c=await(a??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!c.ok)throw await Wo(c);return pt.parse(await c.json())}n(fd,"registerClient");var Gr="zuplo.com",hd=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),gd=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function ea(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(ea,"s2FaviconHref");function yd(e){return`https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&drop_404_icon=true&fallback_opts=TYPE,SIZE,URL&url=http://${e}&size=128`}n(yd,"strictFaviconHref");var er=ea(Gr);function Fr(e){let t=e.toLowerCase();return t===Gr||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?ea(Gr):yd(e)}n(Fr,"resolveIconHref");function _d(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(_d,"hostnameFromHost");function wd(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(wd,"isLocalOrAddressHost");function Rd(e){let t=_d(e).toLowerCase().replace(/\.$/,"");if(wd(t)||gd.some(i=>t===i.slice(1)||t.endsWith(i)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let o=r.slice(-2).join("."),a=hd.has(o)?3:2;return r.slice(-a).join(".")}n(Rd,"inferFaviconDomain");function $r(e){return{src:Fr(Rd(e)),mimeType:"image/png",sizes:["128x128"]}}n($r,"resolveMcpFaviconIcon");function tr(e){try{return $r(new URL(e).host)}catch{return}}n(tr,"resolveMcpFaviconIconFromUrl");function Ie(e){let t=X().connectionsById.get(e);if(!t)throw new j(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,description:t.description,serverInfo:t.serverInfo,transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}n(Ie,"getUpstreamServerConfig");function rr(e){let t=X().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new j(`Unknown auth profile "${String(e.authProfileId)}" for upstream server "${e.upstreamServerId}". Check the route's MCP upstream policy and ensure policies.json declares a matching auth mode for that upstream connection.`);return t.authConfig}n(rr,"getUpstreamAuthConfig");function $e(e,t){let r=rr({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new j(`Upstream server "${e}" does not use upstream OAuth. Select authMode "shared-oauth" or "user-oauth" before starting an upstream OAuth connection flow.`);return r.oauth}n($e,"requireUpstreamOAuthConfig");function ta(e,t){let r=rr({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new j(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(ta,"requireUpstreamIdJagConfig");function ra(e,t){if(!t)return;if(t.aborted){e.abort(t.reason);return}let r=n(()=>e.abort(t.reason),"abort");return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}n(ra,"mergeAbortSignals");async function bd(e){try{await e.cancel()}catch{}}n(bd,"cancelReader");async function nr(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],a=0,i=await r.read();for(;!i.done;){let u=i.value;if(a+=u.byteLength,a>t.maxBytes)throw await bd(r),t.createLimitError();o.push(u),i=await r.read()}let c=new Uint8Array(a),s=0;for(let u of o)c.set(u,s),s+=u.byteLength;return c}n(nr,"readBoundedByteStream");var Id=2,Cd=1024*1024,Sd=1e4,vd=new Set([301,302,303,307,308]),Ad=["authorization","proxy-authorization","cookie","cookie2"];function Zr(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Zr,"readRequestUrl");function Ze(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(Ze,"readRequestMethod");function xd(e,t,r){let o=e.headers.get("content-length");if(!o)return;let a=Number.parseInt(o,10);if(Number.isFinite(a)&&a>t)throw new f({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}})}n(xd,"assertContentLengthWithinLimit");async function kd(e,t,r){return xd(e,t,r),nr(e.body,{maxBytes:t,createLimitError:n(()=>new f({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}}),"createLimitError")})}n(kd,"readBoundedResponseBody");function Td(e,t){let r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}n(Td,"responseFromBufferedBody");function Ud(e,t){if(!vd.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(Ud,"resolveRedirectUrl");function na(e,t){try{return t.validateUrl(e)}catch(r){throw new f({message:"Outbound URL was not allowed.",extensionMembers:{[g]:t.problemCode}},{cause:r})}}n(na,"validateOutboundUrl");function Pd(e,t){throw e instanceof f&&zt(e.extensionMembers?.[g])?e:new f({message:"Outbound fetch failed.",extensionMembers:{[g]:t}},{cause:e})}n(Pd,"normalizeFetchError");function vt(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[o,a]of Object.entries(t.extra))a!==void 0&&(r[o]=a);t.error!==void 0&&L(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(vt,"logOutboundFailure");async function Ed(e,t,r,o,a,i,c){let s=Ze(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";vt(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:s,host:T(i),error:u,extra:{abortReason:c()}}),Pd(u,a)}}n(Ed,"fetchWithNormalizedError");function Od(e){if(e.redirects>=e.maxRedirects)throw new f({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[g]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new f({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[g]:e.problemCode}})}n(Od,"assertRedirectAllowed");function qd(e,t){let r=new Headers(e);for(let o of Ad)r.delete(o);for(let o of t)r.delete(o);return r}n(qd,"stripCrossOriginHeaders");function Md(e,t,r,o,a){let i={...e,method:t,redirect:"manual",signal:r};return o&&(i.headers=qd(e.headers,a)),i}n(Md,"buildRedirectInit");function Dd(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(Dd,"buildInitialRequestInit");function zd(e){let t=Ze(e.currentInput,e.currentInit);Od({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=na(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),a=r.origin!==o.origin,i=r.toString();return{currentInput:i,currentUrl:i,currentInit:Md(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(zd,"followRedirect");async function Kr(e,t,r){let o=r.problemCode??"invalid_request",a=r.maxRedirects??Id,i=r.maxResponseBytes??Cd,c=r.timeoutMs??Sd,s=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,h=new AbortController,y=ra(h,t.signal),U=!1,R=setTimeout(()=>{U=!0,h.abort()},c),q=e,O=Dd(e,t,h.signal),oe;try{oe=na(Zr(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(ae){throw vt(p,{event:"outbound_url_blocked",problemCode:o,method:Ze(e,t),host:T(Zr(e)),error:ae}),clearTimeout(R),y?.(),ae}let ot=0;try{for(;;){let ae=await Ed(p,s,q,O,o,oe,()=>U?`timeout_after_${c}ms`:void 0),M=Ud(ae,oe);if(M!==void 0)try{let z=zd({currentInput:q,currentInit:O,currentUrl:oe,redirectUrl:M,redirects:ot,maxRedirects:a,problemCode:o,validateUrl:r.validateUrl,signal:h.signal,additionalCrossOriginStrippedHeaders:u});q=z.currentInput,O=z.currentInit,oe=z.currentUrl,ot=z.redirects;continue}catch(z){throw vt(p,{event:"outbound_redirect_blocked",problemCode:o,method:Ze(q,O),host:T(oe),error:z,extra:{redirects:ot,maxRedirects:a,redirectTargetHost:T(M)}}),z}try{return Td(ae,await kd(ae,i,o))}catch(z){throw vt(p,{event:"outbound_response_size_exceeded",problemCode:o,method:Ze(q,O),host:T(oe),error:z,extra:{maxResponseBytes:i,status:ae.status}}),z}}}finally{clearTimeout(R),y?.()}}n(Kr,"runSafeOutboundExchange");async function At(e,t,r){let o=await Kr(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(a){throw vt(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Ze(e,t),host:T(Zr(e)),error:a,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new f({message:"Outbound JSON response could not be parsed.",extensionMembers:{[g]:r.problemCode??"invalid_request"}},{cause:a})}}n(At,"runSafeOutboundJsonExchange");function oa(e,t={},r={}){return Kr(e,t,{...r,validateUrl:dt})}n(oa,"fetchConfiguredOutbound");function aa(e,t={},r={}){return At(e,t,{...r,validateUrl:dt})}n(aa,"fetchConfiguredOutboundJson");function or(e,t={},r={}){return At(e,t,{...r,validateUrl:xo})}n(or,"fetchIdentityProviderJson");function ia(e,t={},r={}){return At(e,t,{...r,validateUrl:$t})}n(ia,"fetchCimdClientMetadataJson");function sa(e,t={},r={}){return At(e,t,{...r,validateUrl:ut})}n(sa,"fetchCimdClientJwksJson");F();import{errors as ma,jwtVerify as fa,SignJWT as ha}from"jose";var J="zuplo-mcp-gateway",K=J,W="HS256";import{base64url as Hd}from"jose";var jd=new TextEncoder,Bd="MCP gateway could not initialize secure key material.",Ld=32,ca=new Map,da=new Map,Nd;function Jd(){return Nd??Dn.instance.authPrivateKey}n(Jd,"readAuthPrivateKey");function ua(e){return new Y(Bd,e===void 0?void 0:{cause:e})}n(ua,"createGeneratedKeyMaterialError");function la(e,t){let r=Hd.decode(t);if(r.byteLength!==Ld)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(la,"decodeJwkKeyField");function Gd(e){let t=Jd();if(!t)throw ua();try{let r=JSON.parse(t);if(r.kty!=="OKP"||r.crv!=="Ed25519"||typeof r.d!="string"||typeof r.x!="string")throw new Error("Generated deployment auth key is not an Ed25519 JWK.");let o=la("d",r.d);la("x",r.x);let a=jd.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),i=new Uint8Array(a.byteLength+o.byteLength);return i.set(a),i.set(o,a.byteLength),i}catch(r){throw ua(r)}}n(Gd,"decodeGeneratedKeyMaterial");function Fd(e){let t=ca.get(e);return t||(t=Gd(e),ca.set(e,t)),t}n(Fd,"getMasterKeyMaterial");async function re(e){let t=da.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Fd(e.keyMaterialPurpose));return da.set(e.purpose,r),r}n(re,"readCachedDerivedKey");var $d="SHA-256",Zd=32,Kd="zuplo-mcp-gateway:",Wd=new TextEncoder,pa=new WeakMap;async function Ce(e,t){let r=pa.get(e);r||(r=new Map,pa.set(e,r));let o=r.get(t);if(o)return o;let a=await Vd(e,t);return r.set(t,a),a}n(Ce,"deriveGatewaySigningKey");async function Vd(e,t){let r=Z(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=Wd.encode(`${Kd}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:$d,salt:new Uint8Array,info:Z(a)},o,Zd*8);return new Uint8Array(i)}n(Vd,"hkdfExpand");var ga=900,Yd=900,Xd=co.extend({id:Eo}),Qd=Xd.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ya=Ir.extend({id:Oo,purpose:d.literal("browser_connect")}),eu=Ir.extend({purpose:d.literal("browser_connect")}),tu=ya.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),_a=ga*1e3;async function wa(){return re({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ce(e,"oauth-state"),"derive")})}n(wa,"getOAuthStateKey");async function Ra(){return re({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ce(e,"browser-connect"),"derive")})}n(Ra,"getBrowserConnectKey");async function ba(e){let t=Math.floor(Date.now()/1e3)+ga;return new ha(e).setProtectedHeader({alg:W,typ:"JWT"}).setIssuer(J).setAudience(K).setIssuedAt().setExpirationTime(t).sign(await wa())}n(ba,"signOAuthState");async function ar(e){try{let{payload:t}=await fa(e,await wa(),{algorithms:[W],issuer:J,audience:K});return Qd.parse(t)}catch(t){throw t instanceof ma.JWTExpired?new f({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new f({message:"OAuth state could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(ar,"verifyOAuthState");async function Ia(e){let t=Math.floor(Date.now()/1e3)+Yd,r=eu.parse(e),o=ya.parse({...r,id:Do()});return new ha(o).setProtectedHeader({alg:W,typ:"JWT"}).setIssuer(J).setAudience(K).setIssuedAt().setExpirationTime(t).sign(await Ra())}n(Ia,"signBrowserConnectTicket");async function Ca(e){try{let{payload:t}=await fa(e,await Ra(),{algorithms:[W],issuer:J,audience:K});return tu.parse(t)}catch(t){throw t instanceof ma.JWTExpired?new f({message:"Browser connect ticket has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new f({message:"Browser connect ticket could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(Ca,"verifyBrowserConnectTicket");async function Sa(e){if((await b().consumeBrowserConnectTicket({id:e.id,expiresAt:I(new Date(e.exp*1e3)),now:I(new Date)})).kind==="consumed")throw new f({message:"Browser connect ticket has already been used",extensionMembers:{[g]:"oauth_state_reused"}})}n(Sa,"consumeBrowserConnectTicket");function ru(e,t,r=!1){return r?`${e} authorization must be renewed before this ${t} can be used.`:`${e} authorization is required before this ${t} can be used.`}n(ru,"buildConnectRequiredMessage");async function nu(e){let t=P(e.requestUrl,e.requestHeaders),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("operationId",e.operationId),r.searchParams.set("browserTicket",await Ia({...st(e),purpose:"browser_connect"})),r.toString()}n(nu,"buildGatewayBrowserTicketUrl");function ou(e){return H().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(ou,"buildGatewayConnectPath");async function Wr(e){return nu({...e,path:ou(e.upstreamServerId),redirect:!0})}n(Wr,"buildGatewayConnectUrl");async function ir(e){let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await Wr(t),message:ru(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(ir,"buildRedirectConnectRequiredResponse");function va(e){return au({...e,message:e.requiresReconsent?`An administrator must reconnect ${e.upstreamDisplayName} before this tool can be used.`:`An administrator must connect ${e.upstreamDisplayName} before this tool can be used.`})}n(va,"buildAdminConnectRequiredResponse");function au(e){return{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,...e.connectionId?{connectionId:e.connectionId}:{},message:e.message,nextAction:"admin_setup_required"}}n(au,"buildAdminSetupRequiredResponse");F();var Aa=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function iu(e,t){return e&&e.length>0?e.join(t):void 0}n(iu,"joinOAuthScopes");function su(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of Aa)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(su,"sanitizeAuthorizationServerMetadata");function xa(e){let t=su(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(xa,"sanitizeOAuthDiscoveryState");function ka(e){let t=new URL(e);for(let r of Aa){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(ka,"dedupeSingletonAuthorizationRequestParams");function sr(e){let t=new URL(e);return $(t)&&Zn(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(sr,"normalizeLoopbackOAuthRedirectUri");function Ta(e){return iu(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(Ta,"readProtectedResourceMetadataScope");function cu(e){return`Zuplo MCP Gateway - ${e}`}n(cu,"buildGatewayOAuthClientName");function du(e,t){return e&&e.length>0?e.join(t):void 0}n(du,"joinOAuthScopeList");function uu(e){if(e.clientRegistration.mode!=="auto")return du(e.scopes,e.scopeDelimiter)}n(uu,"readPublicClientMetadataScope");function Vr(e){return new URL(H().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Vr,"buildOAuthClientMetadataDocumentUrl");function Yr(e){let t=Ie(e.upstreamServerId);return{client_name:cu(t.displayName),client_uri:new URL("/",e.origin).toString(),redirect_uris:[e.redirectUri],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",...e.scope===void 0?{}:{scope:e.scope},token_endpoint_auth_method:"none"}}n(Yr,"buildGatewayOAuthClientMetadata");function Ua(e,t,r){let o=$e(t,r),a=uu(o);return{client_id:Vr({origin:e,upstreamServerId:t}),...Yr({origin:e,upstreamServerId:t,redirectUri:sr(new URL(o.redirectPath,e)).toString(),scope:a})}}n(Ua,"buildOAuthClientMetadataDocument");F();import{base64url as Se}from"jose";var lu="SHA-256",Ke="AES-GCM",pu=12,Qr="zuplo-secret",en=1,Pa="generated:auth_private_key:token-encryption",mu=d.object({version:d.literal(en),keyId:d.literal(Pa),algorithm:d.literal(Ke),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();async function Xr(){return re({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(lu,Z(e));return crypto.subtle.importKey("raw",t,{name:Ke},!1,["encrypt","decrypt"])},"derive")})}n(Xr,"getEncryptionKey");function Ea(e){return Z(new TextEncoder().encode(`${Qr}:v${e.version}:${e.keyId}`))}n(Ea,"getAssociatedData");function fu(e){return`${Qr}:v${e.version}:${Se.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(fu,"encodeEnvelope");function hu(e){let t=`${Qr}:v${en}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(Se.decode(r));return mu.parse(JSON.parse(o))}n(hu,"decodeEnvelope");async function me(e){let t=await Xr(),r=crypto.getRandomValues(new Uint8Array(pu)),o={version:en,keyId:Pa},a=await crypto.subtle.encrypt({name:Ke,iv:r,additionalData:Ea(o)},t,new TextEncoder().encode(e));return fu({...o,algorithm:Ke,iv:Se.encode(r),ciphertext:Se.encode(new Uint8Array(a))})}n(me,"encryptSecret");async function ve(e){let t=hu(e);if(t){let c=await Xr(),s=await crypto.subtle.decrypt({name:Ke,iv:Z(Se.decode(t.iv)),additionalData:Ea(t)},c,Z(Se.decode(t.ciphertext)));return new TextDecoder().decode(s)}let[r,o]=e.split(".");if(!r||!o)throw new Y("Encrypted payload is malformed");let a=await Xr(),i=await crypto.subtle.decrypt({name:Ke,iv:Z(Se.decode(r))},a,Z(Se.decode(o)));return new TextDecoder().decode(i)}n(ve,"decryptSecret");var gu=d.union([pt,Qt]),yu=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:Yt.optional(),authorizationServerMetadata:d.union([lt,Xt]).optional()}).passthrough(),_u="Bearer",wu="__zuplo_refresh_only_upstream_access_token__";function Ru(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Ru,"splitScopes");function bu(e){return je.parse(e)}n(bu,"parsePkceCodeVerifier");function Iu(e){if(typeof e.expires_in=="number")return I(new Date(Date.now()+e.expires_in*1e3))}n(Iu,"readTokenExpiry");async function Cu(e){if(e!==void 0)return me(JSON.stringify(e))}n(Cu,"encryptJson");async function Su(e,t){if(!e)return;let r=await ve(e);try{return t.parse(JSON.parse(r))}catch(o){throw new f({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:o})}}n(Su,"decryptJson");function vu(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(vu,"clientInformationAllowsRedirectUri");function Au(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(Au,"clientInformationMatchesCurrentClientMetadataUrl");function xu(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(xu,"isUrlBasedClientInformation");function ku(e,t){return t===void 0?e:{...e,scope:t}}n(ku,"applyOAuthClientMetadataScope");function Tu(e,t){return Ta({state:e,delimiter:t})}n(Tu,"readResourceMetadataScope");function Uu(e,t){return e&&e.length>0?e.join(t):void 0}n(Uu,"joinOAuthScopeList");function Pu(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new j(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return pt.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(Pu,"buildManualOAuthClientInformation");function Eu(e,t){let r=Vr({origin:new URL(t).origin,upstreamServerId:e});return Nr(r)?r:void 0}n(Eu,"buildClientMetadataUrl");function Ou(e){for(let t of e)if(t!==void 0)return t}n(Ou,"firstDefined");function qu(e){let t=$e(e.target.upstreamServerId,e.target.authProfileId),r=Uu(t.scopes,t.scopeDelimiter),o=Yr({origin:new URL(e.redirectUri).origin,upstreamServerId:e.target.upstreamServerId,redirectUri:e.redirectUri,scope:r});if(t.clientRegistration.mode==="manual")return{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,configuredClientInformation:Pu({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let a=Eu(e.target.upstreamServerId,e.redirectUri);return a===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,clientMetadataUrl:a}}n(qu,"buildInitialOAuthClientSetup");function Mu(e,t){if(t===void 0)return Ou([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(Mu,"readEncryptedClientInformation");var qe=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredScope;scopeDelimiter;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;connection;pendingState;encryptedClientInformation;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;constructor(t){let r=qu({target:t.target,redirectUri:t.redirectUri});this.target=t.target,this.redirectUriValue=t.redirectUri,this.returnOrigin=t.returnOrigin,this.clientMetadataValue=r.clientMetadata,this.configuredScope=r.configuredScope,this.scopeDelimiter=r.scopeDelimiter,this.configuredClientInformation=r.configuredClientInformation,r.clientMetadataUrl!==void 0&&(this.clientMetadataUrl=r.clientMetadataUrl),this.connection=t.connection,this.pendingState=t.pendingState?{...t.pendingState}:void 0,this.encryptedClientInformation=Mu(t,this.configuredClientInformation)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return ku(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return ba({id:t.id,...st({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId})})}async clientInformation(){return this.configuredClientInformation?this.configuredClientInformation:this.loadPersistedClientInformation()}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,de()?.info({event:"upstream_oauth_client_registered",upstreamServerId:this.target.upstreamServerId,clientId:"client_id"in t?t.client_id:void 0,redirectUriCount:"redirect_uris"in t?t.redirect_uris.length:void 0},"Upstream OAuth client registered for the gateway"),!xu({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Cu(t),await this.syncPendingState(!1)))}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=xa(yu.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,de()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:T(r.authorizationServerUrl),resourceMetadataHost:T(r.resourceMetadataUrl),resource:r.resourceMetadata?.resource,scopesSupportedCount:r.resourceMetadata?.scopes_supported?.length,hasResourceMetadata:r.resourceMetadata!==void 0},"Upstream OAuth discovery resolved authorization server and resource"),this.inferredScope=Tu(r,this.scopeDelimiter)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Fe.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,a=r.refresh_token?await me(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:Fe.parse({...r,refresh_token:await ve(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let i={id:this.connection?.id??Zt(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await me(r.access_token),encryptedRefreshToken:a,scopes:Ru(r.scope??this.readEffectiveScope()),expiresAt:Iu(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await b().upsertUpstreamConnection(i),de()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionId:this.connection.id,hasRefreshToken:!!a,scopeCount:i.scopes.length,expiresAt:i.expiresAt},"Upstream OAuth tokens persisted; upstream connection is active")}async redirectToAuthorization(t){let r=ka(t);this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:bu(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new f({message:"OAuth code verifier is missing",extensionMembers:{[g]:"oauth_state_invalid"}});return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",o=t==="all"||t==="client",a=t==="all"||t==="discovery",i=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),a&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.challengeScope=void 0,this.inferredScope=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(i),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:Mo(),...st({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,operationId:this.target.operationId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:I(new Date(Date.now()+_a)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await b().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await Su(this.encryptedClientInformation,gu)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&(!vu(t,this.redirectUriValue)||!Au({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl}))){this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}return t===void 0&&this.pendingState?.codeVerifier!==void 0&&this.clientMetadataUrl!==void 0&&(t=Qt.parse({client_id:this.clientMetadataUrl})),this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async readCachedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;this.discoveryStateLoaded=!0}readEffectiveScope(){return this.configuredScope??this.challengeScope??this.inferredScope}async loadStoredTokens(){if(this.tokensLoaded)return this.cachedTokens;if(this.tokensLoaded=!0,!this.connection||this.connection.status!=="active")return;let t=this.connection.encryptedAccessToken?await ve(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await ve(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=Fe.parse({access_token:t??wu,token_type:_u,refresh_token:r,scope:this.connection.scopes.length>0?this.connection.scopes.join(" "):void 0});return this.cachedTokens=o,o}async persistCredentialInvalidation(t){if(!this.connection)return;let r={id:this.connection.id,ownerMode:this.connection.ownerMode,subjectId:this.connection.subjectId,upstreamServerId:this.connection.upstreamServerId,authProfileId:this.connection.authProfileId,status:this.connection.status,encryptedAccessToken:this.connection.encryptedAccessToken,encryptedRefreshToken:this.connection.encryptedRefreshToken,scopes:[...this.connection.scopes],expiresAt:this.connection.expiresAt,metadata:this.connection.metadata?{...this.connection.metadata}:void 0};t&&(r.status="reconsent_required",r.encryptedAccessToken=void 0,r.encryptedRefreshToken=void 0,r.scopes=[],r.expiresAt=void 0),r.metadata=this.readStoredOAuthPersistence(this.connection.metadata?.connectedBySubjectId),this.connection=await b().upsertUpstreamConnection(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var Du=3e4,zu=256*1024,Hu=2;function ju(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(ju,"hasUsableAccessToken");var Bu="does not support dynamic client registration",Lu=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],Nu=["HTTP 403 Forbidden","Access Denied","permission to access"],Ju=new Set(["access_denied","invalid_client","invalid_grant","invalid_request","invalid_scope","invalid_target","unauthorized_client","unsupported_grant_type"]);function Gu(e){return e instanceof Error&&e.message.includes(Bu)}n(Gu,"isDynamicClientRegistrationUnsupported");function Fu(e){return e instanceof Error&&Lu.some(t=>e.message.includes(t))}n(Fu,"isProtectedResourceMetadataUnavailable");function $u(e){return e instanceof Error&&Nu.some(t=>e.message.includes(t))}n($u,"isUpstreamProviderAccessDenied");function Zu(e){return e instanceof A&&Ju.has(e.errorCode)}n(Zu,"isStoredConnectionReconsentError");function Ku(e){if(e.error instanceof f&&e.error.extensionMembers?.[g]!==void 0)return e.error;if(Gu(e.error))return new f({message:`The authorization server for ${e.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register an OAuth client for the gateway manually before retrying.`,extensionMembers:{[g]:"upstream_client_registration_required"}},{cause:e.error});if(Fu(e.error))return new f({message:`The upstream MCP server "${e.upstreamServerId}" does not publish OAuth protected resource metadata at "${e.resourceMetadataUrl}". Configure protectedResourceMetadataUrl to a working metadata document, use a provider-supported legacy client, or contact the provider to approve/allowlist this gateway OAuth client before retrying.`,extensionMembers:{[g]:"upstream_oauth_discovery_unavailable"}},{cause:e.error});if($u(e.error))return new f({message:`The upstream provider denied access while connecting ${e.upstreamServerId}. Confirm the provider allows this gateway and its OAuth client, then retry.`,extensionMembers:{[g]:"upstream_provider_access_denied"}},{cause:e.error})}n(Ku,"mapUpstreamOAuthSetupError");function Wu(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(Wu,"readOAuthFetchRequest");function Vu(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(Vu,"responseLooksJson");function Yu(e,t){let r=e.headers.get("content-type")??"",o=t.trimStart().toLowerCase();return r.includes("html")||o.startsWith("<!doctype html")||o.startsWith("<html")}n(Yu,"responseLooksHtml");function Xu(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new f({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[g]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[_e]:e.response.status,[Be]:r,[we]:e.request.url.toString(),[Le]:e.body}})}n(Xu,"throwUpstreamHtmlError");function Qu(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return{};let r=t;return{error:typeof r.error=="string"?r.error:void 0,errorDescription:typeof r.error_description=="string"?r.error_description:void 0}}catch{return{}}}n(Qu,"readUpstreamOAuthErrorBody");function el(e){let{error:t,errorDescription:r}=Qu(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.request.method??"GET",host:T(e.request.url),path:e.request.url.pathname,status:e.response.status,oauthError:t,oauthErrorDescription:r?.slice(0,256)},"Upstream OAuth HTTP request returned an error response")}n(el,"logUpstreamOAuthHttpError");function qa(e){return async(t,r)=>{let o=Wu(t),a=de(),i=Date.now(),c=await oa(t,r,{maxRedirects:Hu,maxResponseBytes:zu,problemCode:"upstream_token_exchange_failed",timeoutMs:Du}),s=await c.clone().text();if(a?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:o.method??"GET",host:T(o.url),path:o.url.pathname,status:c.status,durationMs:Date.now()-i,responseChars:s.length},"Upstream OAuth HTTP request completed"),c.ok||el({log:a,upstreamServerId:e,request:o,response:c,body:s}),!c.ok&&Yu(c,s)&&Xu({upstreamServerId:e,request:o,response:c,body:s}),!Vu(c,s))return c;try{JSON.parse(s)}catch(u){throw new f({message:`Upstream OAuth fetch ${o.url.origin}${o.url.pathname} for ${e} returned invalid JSON.`,extensionMembers:{[g]:"upstream_token_exchange_failed"}},{cause:u})}return c}}n(qa,"createUpstreamOAuthFetch");function Ma(e){de()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:T(e.serverUrl),resourceMetadataHost:T(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}n(Ma,"logUpstreamOAuthFlowStarted");function Da(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=T(e.serverUrl);r!==void 0&&(t.serverHost=r);let o=e.error instanceof f?e.error.extensionMembers?.[g]:void 0;typeof o=="string"&&(t.code=o),L(t,"error",e.error),de()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(Da,"logUpstreamOAuthFlowFailed");async function za(e,t){e.applyChallengeScope(t.requestedScope),Ma({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:qa(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),await Lr(e,r)}catch(r){Da({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=Ku({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(za,"runUpstreamOAuth");async function tl(e,t){e.applyChallengeScope(t.requestedScope),Ma({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:qa(t.upstreamServerId)};t.requestedScope!==void 0&&(r.scope=t.requestedScope);try{return await Lr(e,r)}catch(o){throw Da({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:o}),o}}n(tl,"exchangeUpstreamAuthorizationCode");async function Ha(e,t){let r=await za(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new f({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new f({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Ha,"requireUpstreamAuthorizationRedirect");async function ja(e){if(!e.forceRefresh&&ju(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t;try{t=await za(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(r){if(e.connection===void 0||!Zu(r))throw r;return de()?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:r.errorCode},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),{kind:"connect_required",payload:await Oa({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}if(t==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(t!=="REDIRECT")throw new f({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new f({message:`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}});return{kind:"connect_required",payload:await Oa({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}n(ja,"authorizeUpstreamOAuthSession");async function rl(e){let t=await ar(e.stateToken),r=await b().consumeUpstreamOAuthState({id:t.id,now:I(new Date)}),o=nl(r);return ol({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),al(o),o}n(rl,"consumeStoredCallbackState");function nl(e){switch(e.kind){case"consumed":throw new f({message:"OAuth state has already been used",extensionMembers:{[g]:"oauth_state_reused"}});case"missing":throw new f({message:"OAuth state is missing or expired",extensionMembers:{[g]:"oauth_state_expired"}});case"available":return e.record}}n(nl,"readConsumedCallbackState");function ol(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.operationId===e.signedState.operationId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw new f({message:"OAuth callback did not match the initiating request",extensionMembers:{[g]:"oauth_callback_mismatch"}})}n(ol,"assertStoredCallbackStateMatches");function al(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new f({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}})}n(al,"assertStoredCallbackStateFresh");async function Oa(e){if(e.owner.mode==="shared"){let r={upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,requiresReconsent:!!e.connection};return e.connection!==void 0&&(r.connectionId=e.connection.id),va(r)}let t={requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders},owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.operationId,subject:"tool",requiresReconsent:!!e.connection,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return e.connection!==void 0&&(t.connectionId=e.connection.id),ir(t)}n(Oa,"buildOAuthConnectRequiredResponse");async function Ba(e){let t=await rl({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Nt(t),[o]=await b().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),a={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};o!==void 0&&(a.connection=o);let i=new qe(a),c=await tl(i,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(c==="AUTHORIZED")return t;throw c!=="REDIRECT"?new f({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${c}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new f({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Ba,"finishUpstreamOAuthCallback");F();import{importPKCS8 as il,SignJWT as sl}from"jose";var Na=1e4,Ja=64*1024,Ga=2,cl=300,te=d.string().min(1),dl=d.object({access_token:te,issued_token_type:d.literal(Sr),token_type:d.string().optional(),expires_in:d.number().int().positive().optional(),scope:te.optional()}).passthrough(),ul=d.object({id_token:te,token_type:te.optional(),expires_in:d.number().int().positive().optional(),refresh_token:te.optional(),scope:te.optional()}).passthrough(),ll=d.object({access_token:te,token_type:te,expires_in:d.number().int().positive().optional(),scope:te.optional(),resource:te.optional(),refresh_token:te.optional()}).passthrough();function La(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(La,"formEncodeClientCredential");function pl(e){return e.replaceAll("\\n",`
|
|
26
|
+
`)}n(pl,"normalizePem");async function ml(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??cl,o=await il(pl(e.clientAuth.privateKeyPem),t),a={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new sl({jti:crypto.randomUUID()}).setProtectedHeader(a).setIssuer(e.clientAuth.clientId).setSubject(e.clientAuth.clientId).setAudience(e.clientAuth.audience??e.tokenUrl).setIssuedAt().setExpirationTime(`${r}s`).sign(o)}n(ml,"createPrivateKeyJwtClientAssertion");async function fl(e){switch(e.clientAuth.method){case"client_secret_post":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_secret",e.clientAuth.clientSecret);return;case"client_secret_basic":{let t=La(e.clientAuth.clientId),r=La(e.clientAuth.clientSecret);e.headers.authorization=`Basic ${btoa(`${t}:${r}`)}`;return}case"private_key_jwt":e.form.set("client_id",e.clientAuth.clientId),e.form.set("client_assertion_type",Gt),e.form.set("client_assertion",await ml({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}n(fl,"appendClientAuthentication");async function tn(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await fl({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}n(tn,"buildFormRequest");function Fa(e){return(t,r)=>or(t,r,{context:e,maxRedirects:Ga,maxResponseBytes:Ja,problemCode:"upstream_token_exchange_failed",timeoutMs:Na})}n(Fa,"defaultIdpFetchJson");function hl(e){return(t,r)=>aa(t,r,{context:e,maxRedirects:Ga,maxResponseBytes:Ja,problemCode:"upstream_token_exchange_failed",timeoutMs:Na})}n(hl,"defaultResourceAsFetchJson");function cr(e){let t={[g]:e.code,[we]:e.tokenUrl};return e.response!==void 0&&(t[_e]=e.response.status),new f({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}n(cr,"runtimeError");function rn(e){if(!e.response.ok)throw cr({code:"upstream_token_exchange_failed",message:(()=>{switch(e.stage){case"idp_refresh_token":return"IdP refresh-token grant failed while renewing the upstream ID-JAG subject token.";case"idp_token_exchange":return"IdP token exchange failed while requesting an upstream ID-JAG.";case"resource_as_jwt_bearer":return"Upstream Resource AS rejected the ID-JAG JWT-bearer exchange."}})(),tokenUrl:e.tokenUrl,response:e.response})}n(rn,"assertTokenEndpointSucceeded");function gl(e){let t=ul.safeParse(e.json);if(!t.success)throw cr({code:"upstream_token_response_invalid",message:"IdP refresh-token grant returned an invalid subject-token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={idToken:t.data.id_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),t.data.scope!==void 0&&(r.scope=t.data.scope),r}n(gl,"parseIdpRefreshTokenResponse");function yl(e){let t=dl.safeParse(e.json);if(!t.success)throw cr({code:"upstream_token_response_invalid",message:"IdP token exchange returned an invalid ID-JAG response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={assertion:t.data.access_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),r}n(yl,"parseIdJagTokenExchangeResponse");function _l(e){let t=ll.safeParse(e.json);if(!t.success)throw cr({code:"upstream_token_response_invalid",message:"Upstream Resource AS returned an invalid JWT-bearer token response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={accessToken:t.data.access_token,tokenType:t.data.token_type};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),t.data.resource!==void 0&&(r.resource=t.data.resource),t.data.refresh_token!==void 0&&(r.refreshToken=t.data.refresh_token),r}n(_l,"parseAccessTokenResponse");async function $a(e){let t=new URLSearchParams({grant_type:Jt,requested_token_type:Sr,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,audience:e.audience});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope),e.authorizationDetails!==void 0&&t.set("authorization_details",JSON.stringify(e.authorizationDetails));let r=e.fetchJson??Fa(e.context),{response:o,json:a}=await r(e.idp.tokenUrl,await tn({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return rn({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),yl({json:a,response:o,tokenUrl:e.idp.tokenUrl})}n($a,"requestIdJag");async function Za(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??Fa(e.context),{response:o,json:a}=await r(e.idp.tokenUrl,await tn({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return rn({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),gl({json:a,response:o,tokenUrl:e.idp.tokenUrl})}n(Za,"refreshIdpSubjectToken");async function Ka(e){let t=new URLSearchParams({grant_type:be,assertion:e.assertion});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope);let r=e.fetchJson??hl(e.context),{response:o,json:a}=await r(e.resourceAs.tokenUrl,await tn({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return rn({response:o,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),_l({json:a,response:o,tokenUrl:e.resourceAs.tokenUrl})}n(Ka,"exchangeIdJagForAccessToken");function wl(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(wl,"hasUsableAccessToken");function Rl(e){if(e.tokenType.toLowerCase()!=="bearer")throw new f({message:"Upstream Resource AS returned a token type the MCP gateway cannot send as a bearer token.",extensionMembers:{[g]:"upstream_token_response_invalid"}})}n(Rl,"assertBearerToken");function bl(e,t){if(t===Ge)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}n(bl,"hasExpiredSubjectToken");async function Il(e){let t=await ve(e.encryptedSubjectToken);if(e.subjectTokenType!==Ge)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await Za({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});return r.refreshToken===void 0?{connection:e.connection,subjectToken:r.idToken,subjectTokenType:ct}:{connection:await b().upsertUpstreamConnection({id:e.connection.id,ownerMode:e.connection.ownerMode,subjectId:e.connection.subjectId,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,status:"active",encryptedAccessToken:e.connection.encryptedAccessToken,encryptedRefreshToken:e.connection.encryptedRefreshToken,scopes:e.connection.scopes,expiresAt:e.connection.expiresAt,metadata:{...e.connection.metadata??{},encryptedIdpSubjectToken:await me(r.refreshToken),idpSubjectTokenType:Ge,idpSubjectTokenExpiresAt:void 0}}),subjectToken:r.idToken,subjectTokenType:ct}}n(Il,"resolveIdJagSubjectToken");async function Wa(e){let t="preloadedConnection"in e?e.preloadedConnection:(await b().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(!e.forceRefresh&&wl(t))return{kind:"authorized",credential:{type:"bearer_token",token:await ve(t.encryptedAccessToken)}};let r=t?.metadata?.encryptedIdpSubjectToken,o=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||r===void 0||o===void 0||bl(t,o))return{kind:"connect_required",payload:{state:"admin_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,message:`An IdP subject-token binding is required for ${e.upstreamDisplayName} before this tool can use XAA / ID-JAG.`,nextAction:"admin_setup_required"}};let a=Ie(e.upstreamServerId),i=ta(e.upstreamServerId,e.authProfileId),c=i.resourceAs.resource??a.transport.baseUrl,s=e.requestedScope??(i.scopes.length===0?void 0:i.scopes.join(i.scopeDelimiter)),u=await Il({connection:t,encryptedSubjectToken:r,subjectTokenType:o,idp:{tokenUrl:i.idp.tokenUrl},clientAuth:i.idp.clientAuth,context:e.context}),p=await $a({idp:{tokenUrl:i.idp.tokenUrl},subjectToken:u.subjectToken,subjectTokenType:u.subjectTokenType,audience:i.resourceAs.audience,resource:c,scope:s,clientAuth:i.idp.clientAuth,context:e.context}),h=p.scope??s,y=await Ka({resourceAs:{tokenUrl:i.resourceAs.tokenUrl},assertion:p.assertion,resource:c,scope:h,clientAuth:i.resourceAs.clientAuth,context:e.context});if(Rl(y),t!==void 0){let U=y.scope??h;await b().upsertUpstreamConnection({id:u.connection.id,ownerMode:u.connection.ownerMode,subjectId:u.connection.subjectId,upstreamServerId:u.connection.upstreamServerId,authProfileId:u.connection.authProfileId,status:"active",encryptedAccessToken:await me(y.accessToken),encryptedRefreshToken:u.connection.encryptedRefreshToken,scopes:U?.split(/[,\s]+/).filter(Boolean)??[],expiresAt:y.expiresIn===void 0?void 0:I(new Date(Date.now()+y.expiresIn*1e3)),metadata:u.connection.metadata})}return{kind:"authorized",credential:{type:"bearer_token",token:y.accessToken}}}n(Wa,"authorizeUpstreamIdJagRequest");function Cl(e){return sr(new URL(e.callbackPath,P(e.requestUrl,e.requestHeaders))).toString()}n(Cl,"buildGatewayOAuthRedirectUri");async function Va(e){let t=Ie(e.upstreamServerId),r=$e(e.upstreamServerId,e.authProfileId),o=Cl({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),a="preloadedConnection"in e?e.preloadedConnection:(await b().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:a,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,returnTo:e.returnTo},redirectUri:o,returnOrigin:P(e.request.url,e.request.headers)}}}n(Va,"prepareUpstreamOAuthRequest");async function Ya(e){let t=await Va(e),r=new qe({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Ha(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Ya,"startUpstreamConnect");async function Xa(e){let t=await Va(e),r=new qe({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return ja({target:e,provider:r,connection:t.connection,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Xa,"authorizeUpstreamRequest");async function We(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return Xa({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo});case"id-jag":return Wa({request:e.request,context:e.context,authMode:t.authMode,ownerMode:t.ownerMode,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,operationId:t.operationId,upstreamDisplayName:t.upstreamDisplayName,forceRefresh:e.forceRefresh,requestedScope:e.requestedScope,...e.preloadedConnection===void 0?{}:{preloadedConnection:e.preloadedConnection},returnTo:t.returnTo})}let r=t;throw new Y(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(We,"resolveUpstreamCredentialForRoute");async function Qa(e){if(e.connectRequest.authMode==="id-jag")throw new Y(`Upstream server ${e.connectRequest.upstreamServerId} uses XAA / ID-JAG and does not support browser OAuth connection flows.`);let t=await Ya({request:e.request,owner:e.connectRequest.owner,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,upstreamServerId:e.connectRequest.upstreamServerId,authProfileId:e.connectRequest.authProfileId,operationId:e.connectRequest.operationId,returnTo:e.connectRequest.returnTo});return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,operationId:e.connectRequest.operationId}}n(Qa,"startUpstreamConnectForRequest");async function ei(e){let r=(await ar(e.callbackRequest.state)).authProfileId;if(rr({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}).mode==="id-jag")throw new Y(`Upstream server ${e.callbackRequest.upstreamServerId} uses XAA / ID-JAG and does not support OAuth callbacks.`);return Ba({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:Ie(e.callbackRequest.upstreamServerId)})}n(ei,"finishUpstreamCallbackForRequest");function Sl(e){return{upstreamServerId:e.connection.upstreamServerId,operationId:e.operationId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(Sl,"buildRouteAuthBaseFromConnection");function ti(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:uo(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(ti,"buildRouteAuthBaseFromPolicyOptions");function dr(e,t){let o=X().byOperationId.get(t);if(!o)throw new j(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new j(`MCP route "${t}" does not declare an MCP token exchange policy. Add one before starting an upstream connection flow.`);if(o.connection.upstreamServerId!==e)throw new j(`MCP route "${t}" does not bind upstream "${e}". Check the route's MCP upstream policies and bind the upstream before starting an upstream connection flow.`);return Sl({connection:o.connection,operationId:t})}n(dr,"resolveRouteAuthBase");function nn(e,t){switch(e){case"user":return Ne(t);case"shared":return so()}}n(nn,"buildOwnerForSubject");function Ve(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:nn("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:nn("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:nn("user",t),initiatedBySubjectId:t}}}n(Ve,"resolveRouteAuthForSubject");var vl=at.InvalidRequest,Al=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function xl(e,t){return{credentialType:e.type,forceRefresh:t}}n(xl,"buildCredentialResolvedAttributes");function kl(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(kl,"connectRequiredReasonCode");function ri(e){v(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:xl(e.credential,e.forceRefresh===!0)})}n(ri,"emitCredentialResolvedAnalyticsEvent");function ni(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(v(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CREDENTIAL_MISSING,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"connect_required",reasonClass:"auth",attributes:t}),e.payload.state==="reconsent_required"){v(e.context,{eventType:C.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}v(e.context,{eventType:C.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:kl(e.payload.state),reasonClass:"auth",attributes:t})}n(ni,"emitCredentialMissingAnalyticsEvents");function Tl(e){let t=e.route.raw();return jt.parse(t?.operationId)}n(Tl,"readOperationId");async function Ul(e,t,r,o){let a=await We({request:e,context:o,routeAuth:t});if(a.kind==="connect_required")return ni({context:o,payload:a.payload,routeBinding:t}),o.log.info({event:"mcp_upstream_connect_required",upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId},"MCP upstream proxy: upstream connection required"),{kind:"connect_required",payload:a.payload};let i=a.credential;if(ri({context:o,credential:i,routeBinding:t}),i.type==="bearer_token")return{kind:"headers",headers:[["authorization",`Bearer ${i.token}`]]};let c=await i.provider.tokens();return c?{kind:"headers",headers:[["authorization",`${c.token_type??"Bearer"} ${c.access_token}`]]}:(o.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:t.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),Response.json({error:"no_upstream_tokens"},{status:401}))}n(Ul,"buildCredentialHeaders");var Pl=new Set(["authorization","cookie","cookie2"]);function El(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return t&&typeof t=="object"&&!Array.isArray(t)&&"method"in t&&typeof t.method=="string"?t.method:void 0}catch{return}}n(El,"readJsonRequestMethod");function Ol(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(Ol,"isJsonResponse");function on(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(on,"isRecord");function ql(e){return Array.isArray(e)&&e.length>0}n(ql,"hasIconList");function Ml(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=tr(eo(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(Ml,"readFallbackServerIcons");function Dl(e){if(!on(e.body))return e.body;let t=e.body.result;if(!on(t))return e.body;let r=t.serverInfo;return!on(r)||ql(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n(Dl,"addMissingServerIcons");function zl(e,t){let r=new Headers(e.headers);for(let o of Pl)r.delete(o);for(let[o,a]of t)r.set(o,a);return new Hn(e,{headers:r})}n(zl,"applyUpstreamHeaders");function Hl(e){let t=new Headers(e.headers);for(let r of Al)t.delete(r);return t}n(Hl,"buildProxyHeaders");async function jl(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(jl,"readRetryBody");function oi(e,t){let r=t.authUrl===void 0?void 0:Ho({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(Wt({id:zo(e),error:{code:r?.code??vl,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(oi,"connectRequiredJsonRpcResponse");async function Bl(e){let{scope:t}=Vo(e.upstreamResponse),r=await We({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="connect_required")return ni({context:e.context,payload:r.payload,routeBinding:e.routeAuth,forceRefresh:!0}),{kind:"connect_required",payload:r.payload};let o=new Headers(e.headers),a=r.credential;if(ri({context:e.context,credential:a,routeBinding:e.routeAuth,forceRefresh:!0}),a.type==="bearer_token")return o.set("authorization",`Bearer ${a.token}`),{kind:"headers",headers:o};let i=await a.provider.tokens();return i?(o.set("authorization",`${i.token_type??"Bearer"} ${i.access_token}`),{kind:"headers",headers:o}):(e.context.log.warn({event:"mcp_upstream_no_tokens_after_refresh",upstreamServerId:e.routeAuth.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens after refresh"),{kind:"response",response:Response.json({error:"no_upstream_tokens"},{status:401})})}n(Bl,"applyRefreshedCredentialHeaders");function Ll(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await Bl({request:e.request,context:e.context,headers:Hl(r),routeAuth:e.routeAuth,upstreamResponse:t});if(o.kind==="connect_required")return oi(e.requestBody,o.payload);if(o.kind==="response")return o.response;let a=to({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return qt.fetch(a.url,a.init)})}n(Ll,"installUpstreamAuthRetryHook");function Nl(e){if(El(e.requestBody)!=="initialize")return;let t=Ml({connection:e.connection,context:e.context});t===void 0||t.length===0||e.context.addResponseSendingHook(async r=>{if(!Ol(r))return r;let o;try{o=await r.clone().json()}catch{return r}let a=Dl({body:o,icons:t});if(a===o)return r;let i=new Headers(r.headers);return i.delete("content-length"),new Response(JSON.stringify(a),{status:r.status,statusText:r.statusText,headers:i})})}n(Nl,"installInitializeIconHook");async function an(e,t,r){let o=Tl(t),a=await jl(e),i=ti({connection:r,operationId:o}),c=Te(e.user,e.url,e.headers);t.log.setLogProperties?.({requestId:t.requestId}),go(t,c);let s=Ve(i,c.subjectId),u=await Ul(e,s,r,t);if(!(u instanceof Response)&&u.kind==="connect_required")return oi(a,u.payload);if(u instanceof Response)return u;let p=zl(e,u.headers);return Ll({request:p,context:t,requestBody:a,routeAuth:s}),Nl({context:t,requestBody:a,connection:r}),p}n(an,"mcpTokenExchangePolicy");var sn=class extends Mt{static{n(this,"McpTokenExchangeInboundPolicy")}constructor(t,r){let o=lo(t,r);super(o,r)}async handler(t,r){return G("policy.inbound.mcp-token-exchange"),an(t,r,this.options)}};F();var ai=Symbol("Html");function Jl(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}n(Jl,"escapeHtml");function Gl(e){return e===null||typeof e!="object"?!1:e[ai]===!0}n(Gl,"isHtml");function ii(e){return e==null||e===!1?"":Array.isArray(e)?e.map(ii).join(""):Gl(e)?e.value:Jl(String(e))}n(ii,"renderValue");function fe(e){return{[ai]:!0,value:e}}n(fe,"trustedHtml");var Q=fe("");function S(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=ii(t[o]),r+=e[o+1]??"";return fe(r)}n(S,"html");function Ye(e){return e.value}n(Ye,"renderHtml");function si(e){return S`<p class="card__description">${e.detail}</p>${e.guidance} ${e.technicalDetails} ${e.action}`}n(si,"renderBrowserErrorPage");var Xe=fe('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;justify-content:center;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;min-height:40px;padding:8px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.reconnect-action{align-items:center;margin-right:auto;display:inline-flex;position:relative}.reconnect-button{gap:7px}.tooltip{width:16px;height:16px;color:var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);cursor:help;border:1.5px solid;border-radius:50%;justify-content:center;align-items:center;font-size:10.5px;font-weight:700;line-height:1;display:inline-flex;position:relative}.tooltip:after{content:attr(aria-label);z-index:10;border-radius:var(--radius-sm);background:var(--accent);width:280px;max-width:min(280px,100vw - 48px);color:var(--accent-text);box-shadow:var(--shadow);text-align:left;white-space:normal;opacity:0;pointer-events:none;padding:12px 14px;font-size:13px;font-weight:600;line-height:1.45;transition:opacity .12s;position:absolute;bottom:calc(100% + 12px);left:50%;transform:translate(-50%)}.tooltip:before{content:"";z-index:11;border-left:7px solid #0000;border-right:7px solid #0000;border-top:8px solid var(--accent);opacity:0;pointer-events:none;transition:opacity .12s;position:absolute;bottom:calc(100% + 5px);left:50%;transform:translate(-50%)}.tooltip:hover:after,.tooltip:hover:before,.tooltip:focus-visible:after,.tooltip:focus-visible:before{opacity:1}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}.reconnect-action{justify-content:center;width:100%;margin-right:0}.reconnect-action .button{flex:1}.tooltip:after{left:auto;right:0;transform:none}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function Qe(e){return S`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" href="${e.iconHref}" /><style>
|
|
27
27
|
${e.styles}
|
|
28
|
-
</style></head><body><main class="card"><header class="card__head">${e.headerIcon}<h1 class="card__title">${e.heading}</h1>${e.subhead}</header><div class="card__body">${e.body}</div>${e.footer}</main></body></html>`}n(
|
|
29
|
-
`);return S`<pre class="banner__message" style="white-space: pre-wrap; overflow-wrap: anywhere; margin-top: 8px;"><code>${t}</code></pre>`}n(
|
|
28
|
+
</style></head><body><main class="card"><header class="card__head">${e.headerIcon}<h1 class="card__title">${e.heading}</h1>${e.subhead}</header><div class="card__body">${e.body}</div>${e.footer}</main></body></html>`}n(Qe,"renderShell");var Fl="text/html; charset=utf-8";function et(e){try{return new URL(e).host}catch{return""}}n(et,"safeHostFromUrl");function ne(e){let t=Zl(e.kind??"authorization_failed"),r=$l(e);return new Response(Ye(Qe({title:e.title??t.title,iconHref:"",styles:Xe,headerIcon:Q,heading:e.title??t.title,subhead:"",body:si({detail:e.detail,guidance:S`<p class="card__description">${t.guidance}</p>`,technicalDetails:Xl({diagnostic:r,upstreamHtml:e.upstreamHtml}),action:Vl(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":Fl,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(ne,"browserErrorPageResponse");function $l(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??Kl(t),timestamp:e.diagnostic?.timestamp??new Date().toISOString(),...e.requestId===void 0&&e.diagnostic?.requestId===void 0?{}:{requestId:e.diagnostic?.requestId??e.requestId},...e.diagnostic?.operationId===void 0?{}:{operationId:e.diagnostic.operationId},...e.diagnostic?.routePath===void 0?{}:{routePath:e.diagnostic.routePath},...e.diagnostic?.upstreamServerId===void 0?{}:{upstreamServerId:e.diagnostic.upstreamServerId},...e.diagnostic?.authProfileId===void 0?{}:{authProfileId:e.diagnostic.authProfileId},...e.diagnostic?.upstreamUrl===void 0?{}:{upstreamUrl:e.diagnostic.upstreamUrl},...e.diagnostic?.metadataUrl===void 0?{}:{metadataUrl:e.diagnostic.metadataUrl},...e.diagnostic?.httpStatus===void 0?{}:{httpStatus:e.diagnostic.httpStatus},...e.diagnostic?.contentType===void 0?{}:{contentType:e.diagnostic.contentType},...e.diagnostic?.providerError===void 0?{}:{providerError:e.diagnostic.providerError},...e.diagnostic?.providerErrorDescription===void 0?{}:{providerErrorDescription:e.diagnostic.providerErrorDescription},suggestedFix:e.diagnostic?.suggestedFix??Wl(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}n($l,"buildBrowserErrorDiagnostic");function Zl(e){switch(e){case"session_expired":return{title:"Authorization expired",guidance:"Return to your MCP client and reconnect. Expired authorization requests cannot be resumed."};case"access_denied":return{title:"Authorization canceled",guidance:"Return to your MCP client to retry if you want to grant access."};case"configuration_error":return{title:"Configuration needs attention",guidance:"Contact your workspace admin with this error code. The gateway or upstream configuration must be fixed before retrying."};case"connection_failed":return{title:"Connection failed",guidance:"Return to your MCP client and reconnect this upstream. If this keeps happening, contact your gateway administrator with this error code."};case"invalid_request":return{title:"Authorization request invalid",guidance:"Return to your MCP client and try connecting again. If this keeps happening, the client request may need to be fixed."};case"admin_required":return{title:"Admin setup required",guidance:"Contact your workspace admin with this error code. This connection cannot be completed until setup is finished."};case"internal_error":return{title:"Gateway error",guidance:"Try again later from your MCP client. If this keeps happening, contact your gateway administrator with this error code."};case"authorization_failed":return{title:"Authorization failed",guidance:"Return to your MCP client and start authorization again. If this keeps happening, contact your gateway administrator with this error code."}}}n(Zl,"readBrowserErrorPagePresentation");function Kl(e){switch(e){case"upstream_oauth_discovery_unavailable":return"upstream_oauth_discovery";case"upstream_client_registration_required":return"upstream_oauth_client_registration";case"upstream_provider_access_denied":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"upstream_token_exchange";case"provider_access_denied":return"upstream_oauth_callback";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"upstream_oauth_state";case"browser_login_verification_failed":return"downstream_browser_login";case"authentication_required":case"identity_context_missing":return"downstream_auth";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"gateway_configuration";case"server_error":case"internal_server_error":return"gateway_internal";default:return"gateway_request"}}n(Kl,"readBrowserErrorStage");function Wl(e){switch(e){case"upstream_oauth_discovery_unavailable":return"Confirm the upstream MCP URL and OAuth protected resource metadata. If the provider requires approval, configure the provider app or contact the provider.";case"upstream_client_registration_required":return"Register an OAuth client with the upstream provider, then configure the gateway to use that client before retrying.";case"upstream_provider_access_denied":return"Confirm the provider allows this gateway, OAuth client, and upstream MCP URL, then retry the connection.";case"upstream_token_exchange_failed":return"Retry the connection. If it repeats, verify the upstream OAuth client, redirect URI, token endpoint, and provider allowlist.";case"upstream_token_response_invalid":return"Verify the upstream token endpoint returns a valid OAuth token response for this gateway client.";case"provider_access_denied":return"Start the connection again if access was denied by mistake. Otherwise, grant the requested upstream provider access.";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"Start a new connection from the MCP client. The previous browser authorization request cannot be resumed.";case"browser_login_verification_failed":return"Retry the browser login flow. If it repeats, verify the downstream login callback configuration.";case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"Check the MCP route, upstream server, and auth profile entries in the gateway configuration.";case"authentication_required":case"identity_context_missing":return"Verify the normal Zuplo auth policy runs before the MCP gateway policy and sets request.user.";case"server_error":case"internal_server_error":return"Retry later and check gateway logs with the request ID.";default:return"Check the gateway configuration and request details associated with this error code."}}n(Wl,"readBrowserErrorSuggestedFix");function Vl(e){return e===void 0?Q:S`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(Vl,"renderAction");function Yl(e){let t=[["Error code",e.code],["Stage",e.stage],["Request ID",e.requestId],["Time",e.timestamp],["Gateway route",e.routePath],["Operation ID",e.operationId],["Upstream",e.upstreamServerId],["Auth profile",e.authProfileId],["Upstream URL",e.upstreamUrl],["Metadata URL",e.metadataUrl],["HTTP status",e.httpStatus],["Content type",e.contentType],["Provider error",e.providerError],["Provider error description",e.providerErrorDescription],["Suggested fix",e.suggestedFix],["Underlying error",e.underlyingError]].filter(r=>r[1]!==void 0).map(([r,o])=>`${r}: ${o}`).join(`
|
|
29
|
+
`);return S`<pre class="banner__message" style="white-space: pre-wrap; overflow-wrap: anywhere; margin-top: 8px;"><code>${t}</code></pre>`}n(Yl,"renderTechnicalPre");function ur(e){return e.value===void 0||e.value===""?Q:S`<p class="banner__message"><strong>${e.label}:</strong> <code>${e.value}</code></p>`}n(ur,"renderOptionalTechnicalRow");function Xl(e){return S`<section class="banner banner--warning" aria-label="Developer details">
|
|
30
30
|
<span class="banner__icon" aria-hidden="true">!</span>
|
|
31
31
|
<div class="banner__body">
|
|
32
32
|
<p class="banner__title">Developer details</p>
|
|
33
33
|
<p class="banner__message" data-gateway-error-code="${e.diagnostic.code}">
|
|
34
34
|
<strong>Error code:</strong> <code>${e.diagnostic.code}</code>
|
|
35
35
|
</p>
|
|
36
|
-
${
|
|
37
|
-
${
|
|
38
|
-
${
|
|
39
|
-
${
|
|
40
|
-
${
|
|
41
|
-
${
|
|
36
|
+
${ur({label:"Stage",value:e.diagnostic.stage})}
|
|
37
|
+
${ur({label:"Request ID",value:e.diagnostic.requestId})}
|
|
38
|
+
${ur({label:"Suggested fix",value:e.diagnostic.suggestedFix})}
|
|
39
|
+
${ur({label:"Reason",value:e.diagnostic.underlyingError})}
|
|
40
|
+
${Yl(e.diagnostic)}
|
|
41
|
+
${Ql(e.upstreamHtml)}
|
|
42
42
|
</div>
|
|
43
|
-
</section>`}n(
|
|
43
|
+
</section>`}n(Xl,"renderTechnicalDetails");function Ql(e){return e===void 0?Q:S`<iframe
|
|
44
44
|
title="Upstream HTML error response"
|
|
45
45
|
sandbox
|
|
46
46
|
srcdoc="${e}"
|
|
47
47
|
style="border: 1px solid var(--warning-border); border-radius: var(--radius-sm); background: white; width: 100%; min-height: 220px; margin-top: 8px;"
|
|
48
|
-
></iframe>`}n(Vl,"renderUpstreamHtml");var ii="application/json",Yl="application/x-www-form-urlencoded";function cr(e,t){return new f({message:e,extensionMembers:{[g]:"invalid_request"}},t===void 0?void 0:{cause:t})}n(cr,"invalidRequestError");function Xl(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}n(Xl,"normalizeContentType");function Ql(e,t){return e===t?!0:t===ii&&e.endsWith("+json")}n(Ql,"contentTypeMatches");function ep(e,t){if(!t||t.length===0)return;let r=Xl(e.headers.get("content-type"));if(!t.some(o=>Ql(r,o)))throw cr(`Request body must be ${t.join(" or ")}.`)}n(ep,"assertExpectedContentType");function tp(e,t,r){let o=e.headers.get("content-length");if(!o)return;let a=Number.parseInt(o,10);if(Number.isFinite(a)&&a>t)throw cr(`${r} exceeded the maximum allowed size.`)}n(tp,"assertContentLengthWithinLimit");async function si(e,t){let r=t.label??"Request body";ep(e,t.expectedContentTypes),tp(e,t.maxBytes,r);let o=await er(e.body,{maxBytes:t.maxBytes,createLimitError:n(()=>cr(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(o)}n(si,"readBoundedTextBody");async function ci(e,t){let r=await si(e,{...t,expectedContentTypes:[ii]});try{return JSON.parse(r)}catch(o){throw cr("Request body must be valid JSON.",o)}}n(ci,"readBoundedJsonBody");async function di(e,t){let r=await si(e,{...t,expectedContentTypes:[Yl]});return new URLSearchParams(r)}n(di,"readBoundedFormUrlEncodedBody");F();F();import{errors as ui,jwtVerify as li,SignJWT as pi}from"jose";var rp={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},m=class extends Error{static{n(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,o=rp[t],a){super(r,a),this.name="OAuthProtocolError",this.errorCode=t,this.status=o}};var np=5*60,op=d.object({purpose:d.literal("gateway_browser_login"),transactionId:Ir,stateId:Cr,exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ap=d.object({purpose:d.literal("gateway_authorization_setup"),transactionId:Ir,stateId:Cr,exp:d.number().int().positive(),iat:d.number().int().positive().optional()});async function mi(){return te({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ie(e,"browser-login"),"derive")})}n(mi,"getBrowserLoginKey");async function fi(){return te({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ie(e,"authorization-csrf"),"derive")})}n(fi,"getCsrfKey");function hi(e){return{now:e.now??new Date,ttlSeconds:gi()}}n(hi,"readPendingTransactionDependencies");function gi(){return B().browserLogin.stateTtlSeconds}n(gi,"readBrowserLoginStateTtlSeconds");function ip(e){let t=j();return $(e)&&t.isActionPath(e.pathname,"/oauth/dev-login")}n(ip,"isLoopbackDevLoginUrl");function sp(e){let t=B().browserLogin,r=j(),o=new URL(we("url")),a=new URL(r.actionPath("/oauth/callback"),Be(e.requestUrl,e.requestHeaders));return ip(o)?(o.searchParams.set("redirect_uri",a.toString()),o.searchParams.set("state",e.state),o):(o.searchParams.set("response_type","code"),o.searchParams.set("client_id",we("clientId")),o.searchParams.set("redirect_uri",a.toString()),o.searchParams.set("scope",t.scope),o.searchParams.set("state",e.state),o.searchParams.set("nonce",e.nonce),t.audience&&o.searchParams.set("audience",t.audience),o)}n(sp,"buildBrowserLoginUrl");function cp(e,t){return e.subjectId===t.subjectId}n(cp,"principalsMatch");function yi(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}n(yi,"toPendingPrincipal");function _i(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,operationId:e.transaction.operationId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:I(e.now),expiresAt:I(se(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw w("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:yi(e.principal)}}n(_i,"createTransactionRecord");async function wi(e){let{id:t,...r}=e.record,o=await b().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(o.kind){case"started":return o.transaction;case"already_exists":throw w("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new m("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new m("invalid_request","redirect_uri is not registered for the client.")}}n(wi,"startPendingTransaction");async function dp(e){return new pi({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:K,typ:"JWT"}).setIssuer(J).setAudience(Z).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await mi())}n(dp,"signBrowserLoginState");async function Ri(e){return new pi({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:vr()}).setProtectedHeader({alg:K,typ:"JWT"}).setIssuer(J).setAudience(Z).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await fi())}n(Ri,"signCsrfToken");async function on(e){try{let{payload:t}=await li(e,await mi(),{algorithms:[K],issuer:J,audience:Z}),r=op.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof ui.JWTExpired?w("oauth_state_expired","Browser login state has expired.",t):w("oauth_state_invalid","Browser login state could not be verified.",t)}}n(on,"verifyBrowserLoginStateToken");async function dr(e){try{let{payload:t}=await li(e,await fi(),{algorithms:[K],issuer:J,audience:Z});return{transactionId:ap.parse(t).transactionId}}catch(t){throw t instanceof ui.JWTExpired?w("oauth_state_expired","Authorization setup state has expired.",t):w("oauth_state_invalid","Authorization setup state could not be verified.",t)}}n(dr,"verifyCsrfToken");function an(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}n(an,"pendingStateErrorCode");function up(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}n(up,"toPendingAuthorizationGetResult");function lp(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}n(lp,"toPendingAuthorizationAdvanceResult");function sn(e){return e==="principal_mismatch"?"oauth_callback_mismatch":an(e==="consumed_already"?"consumed_already":e)}n(sn,"setupDecisionErrorCode");async function bi(e){let t=e.now??new Date,r=await dr(e.csrfToken),o=await b().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await x(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:I(t)});if(o.kind!=="marked")throw w(sn(o.kind),"Authorization setup state is invalid, expired, or already used.");return Ii({kind:"available",record:o.transaction})}n(bi,"markSetupApproved");function Ii(e){if(e.kind!=="available")throw w(an(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw w("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}n(Ii,"requireAwaitingSetup");function pp(e){if(!cp(e.currentBrowserPrincipal,e.transaction.principal))throw w("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}n(pp,"requireCurrentPrincipalMatches");async function Ci(e){let t=e.now??new Date,r=gi(),o=Sr(),a=vr(),i=await dp({transactionId:o,stateId:a,ttlSeconds:r}),c=_i({id:o,transaction:e.transaction,currentStateHash:await x(i),phase:"awaiting_login",now:t,ttlSeconds:r});if(c.phase!=="awaiting_login")throw w("oauth_state_invalid","Authorization transaction did not start in login phase.");let s=await wi({record:c,client:e.transaction.client});if(s.phase!=="awaiting_login")throw w("oauth_state_invalid","Authorization transaction did not start in login phase.");return{transaction:s,browserLoginStateToken:i,browserLoginUrl:sp({state:i,nonce:a,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}})}}n(Ci,"startAwaitingLogin");async function Si(e){let{now:t,ttlSeconds:r}=hi(e),o=Sr(),a=await Ri({transactionId:o,ttlSeconds:r}),i=_i({id:o,transaction:e.transaction,currentStateHash:await x(a),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw w("oauth_state_invalid","Authorization transaction did not start in setup phase.");let c=await wi({record:i,client:e.transaction.client});if(c.phase!=="awaiting_setup")throw w("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:c,csrfToken:a}}n(Si,"startAwaitingSetup");async function vi(e){let{now:t,ttlSeconds:r}=hi(e),o=await on(e.browserLoginStateToken),a=await Ri({transactionId:o.transactionId,ttlSeconds:r}),i=lp(await b().advancePendingAuthorization({transactionId:o.transactionId,expectedPhase:"awaiting_login",currentStateHash:await x(e.browserLoginStateToken),nextStateHash:await x(a),nextPhase:"awaiting_setup",principal:yi(e.principal),now:I(t)}));if(i.kind!=="advanced")throw w(an(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw w("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:a}}n(vi,"completeLogin");async function Ai(e){let t=await cn(e);return pp({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}n(Ai,"getSetup");async function cn(e){let t=e.now??new Date,r=await dr(e.csrfToken);return Ii(up(await b().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await x(e.csrfToken),now:I(t)})))}n(cn,"getSetupTransaction");async function mp(e){let t=await dr(e.csrfToken),r=ue(),o=I(se(e.now,np)),a=await b().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await x(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await x(r),authorizationCodeExpiresAt:o,grantId:go(),now:I(e.now)});if(a.kind!=="approved")throw w(a.kind==="cancelled"?"oauth_state_invalid":sn(a.kind),"Authorization setup state is invalid, expired, or already used.");let i=new URL(a.transaction.redirectUri);return i.searchParams.set("code",r),a.transaction.clientState&&i.searchParams.set("state",a.transaction.clientState),i}n(mp,"createAuthorizationCodeRedirectWithDecision");async function fp(e){let t=await dr(e.csrfToken),r=await b().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await x(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:I(e.now)});if(r.kind!=="cancelled")throw w(r.kind==="approved"?"oauth_state_invalid":sn(r.kind),"Authorization setup state is invalid, expired, or already used.");return hp({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}n(fp,"createCancelRedirectWithDecision");function hp(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),t}n(hp,"buildClientCancelRedirect");async function xi(e){let t=e.now??new Date;return mp({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(xi,"approve");async function ki(e){let t=e.now??new Date;return fp({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(ki,"cancel");F();import{createRemoteJWKSet as gp,errors as Qe,jwtVerify as Ui,SignJWT as yp}from"jose";var ln="zuplo_mcp_session",_p=d.object({purpose:d.literal("gateway_browser_session"),sub:ot,browserLoginOrigin:d.string().min(1),roles:d.array(d.string().min(1)).optional(),exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),wp=d.object({id_token:d.string().min(1),token_type:d.string().min(1).optional(),expires_in:d.number().optional(),access_token:d.string().min(1).optional(),refresh_token:d.string().min(1).optional(),scope:d.string().min(1).optional()}),Rp=d.object({error:d.string().min(1).optional(),error_description:d.string().min(1).optional(),error_uri:d.string().min(1).optional()}),bp=d.object({sub:ot,nonce:d.string().min(1)}).catchall(d.unknown()),dn;function Ip(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let o=r.indexOf("=");if(o<0)continue;let a=r.slice(0,o).trim(),i=r.slice(o+1).trim();if(a)try{t.set(a,decodeURIComponent(i))}catch{t.set(a,i)}}return t}n(Ip,"parseCookieHeader");async function Ti(){return te({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ie(e,"browser-session"),"derive")})}n(Ti,"getBrowserSessionKey");function un(e,t){let r=new URL(P(e,t)),o=[`${ln}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return r.protocol==="https:"&&o.push("Secure"),o.join("; ")}n(un,"buildBrowserSessionEvictionCookie");function Cp(e){let t=new URL(P(e.requestUrl,e.requestHeaders)),r=[`${ln}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(Cp,"serializeSessionCookie");function Pi(){return new URL(we("url")).origin}n(Pi,"readBrowserLoginOrigin");function Sp(e){let t=Rp.safeParse(e);if(!t.success)return{};let r={};return t.data.error!==void 0&&(r.idpError=t.data.error),t.data.error_description!==void 0&&(r.idpErrorDescription=t.data.error_description.slice(0,256)),t.data.error_uri!==void 0&&(r.idpErrorUri=t.data.error_uri.slice(0,256)),r}n(Sp,"readIdpErrorFields");function vp(e){return e instanceof Qe.JWTExpired?"expired":e instanceof Qe.JWTClaimValidationFailed?"claim":e instanceof Qe.JWSSignatureVerificationFailed?"signature":e instanceof Qe.JWKSNoMatchingKey?"jwks_no_match":e instanceof Qe.JWTInvalid?"invalid":e instanceof d.ZodError?"schema":"other"}n(vp,"readJwtFailureKind");function Ap(e){return e instanceof Error&&"cause"in e?e.cause:e}n(Ap,"readErrorCause");function xp(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}n(xp,"readRuntimeGatewayCode");function kp(){if(!dn){let e=B();dn=gp(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return dn}n(kp,"readFederatedJwks");function Ei(e){if(!e.user)throw w("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return ke(e.user,e.url)}n(Ei,"resolveCurrentRequestPrincipal");async function ur(e,t={}){let r=Ip(e.headers.get("cookie")).get(ln);if(!r)return{};try{let{payload:o}=await Ui(r,await Ti(),{algorithms:[K],issuer:J,audience:Z}),a=_p.parse(o);if(a.browserLoginOrigin!==Pi())return{evictCookie:un(e.url,e.headers)};let i={subjectId:a.sub};return a.roles&&a.roles.length>0&&(i.roles=a.roles),{principal:i}}catch(o){return o instanceof Qe.JWTExpired?{evictCookie:un(e.url,e.headers)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:o instanceof Error?o.name:"unknown",errorMessage:o instanceof Error?o.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:un(e.url,e.headers)})}}n(ur,"readBrowserSession");async function lr(e){let t=B().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:Pi()};e.principal.roles&&(r.roles=e.principal.roles);let o=await new yp(r).setProtectedHeader({alg:K,typ:"JWT"}).setIssuer(J).setAudience(Z).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await Ti());return Cp({value:o,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t})}n(lr,"createBrowserSessionCookie");async function Up(e){let t=B(),r=we("tokenUrl"),o=we("clientId"),a=we("clientSecret"),i=new URL(j().actionPath("/oauth/callback"),Be(e.requestUrl,e.requestHeaders)).toString(),c=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:i,client_id:o,client_secret:a});try{let{response:s,json:u}=await tr(r,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:c},{maxResponseBytes:32768,problemCode:"browser_login_verification_failed",timeoutMs:t.browserLogin.remoteTimeoutMs,context:e.context});if(!s.ok){let R=Sp(u);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:U(r),idpStatus:s.status,...R},"Federated browser login token exchange returned non-2xx from the identity provider"),w({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${s.status}${R.idpError?` idp_error=${R.idpError}`:""}${R.idpErrorDescription?` idp_error_description=${R.idpErrorDescription}`:""})`)})}let p=wp.parse(u),h;try{({payload:h}=await Ui(p.id_token,kp(),{issuer:t.oidc.issuer,audience:o}))}catch(R){let q={};throw L(q,"error",R),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:vp(R),idpHost:U(r),expectedIssuer:t.oidc.issuer,...q},"Federated id_token failed jose verification"),R}if(h.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:U(r),nonceMissingFromIdToken:h.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),w("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let y=bp.parse(h);return{principal:ke({sub:y.sub,data:y},e.requestUrl),subjectToken:{token:p.id_token,tokenType:it,expiresAt:typeof h.exp=="number"?I(new Date(h.exp*1e3)):void 0}}}catch(s){let u=ie(s)??xp(s);throw u!==void 0&&u!=="browser_login_verification_failed"?s:w("browser_login_verification_failed","Federated browser login callback could not be verified.",Ap(s))}}n(Up,"exchangeFederatedAuthorizationCode");async function Oi(e){let t=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(t)return Up({code:t,nonce:e.stateId,requestUrl:e.request.url,requestHeaders:e.request.headers,context:e.context});let r=await ur(e.request,{context:e.context});if(r.principal)return{principal:r.principal};throw w("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.")}n(Oi,"resolveBrowserLoginCallbackIdentity");F();var Tp=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function Pp(e){return e.protocol.replace(/:$/u,"").toLowerCase()}n(Pp,"readScheme");function Ep(e){return e.protocol==="https:"}n(Ep,"isSpecCompliantRedirectUri");function Op(e){let t=Pp(e);return t.length>0&&t!=="http"&&t!=="https"&&!Tp.has(t)}n(Op,"isNativeAppCustomSchemeRedirectUri");var Mi=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:n(e=>Ep(e),"accepts")},{id:"oauth.redirect_uri.loopback_http",mode:"native_app",accepts:n(e=>$(e),"accepts"),matches:n((e,t)=>$(e)&&$(t)&&e.pathname===t.pathname&&e.search===t.search,"matches")},{id:"oauth.redirect_uri.custom_scheme",mode:"native_app",accepts:n(e=>Op(e),"accepts")}];function Di(e){let t=Mi.find(r=>r.accepts(e.url));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}n(Di,"evaluateBuiltInRedirectUriCompatibility");function qi(e){try{return new URL(e)}catch{return}}n(qi,"parseUrl");function zi(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=qi(e.registeredRedirectUri),r=qi(e.requestedRedirectUri);return t===void 0||r===void 0?!1:Mi.some(o=>o.matches?.(t,r))}n(zi,"redirectUriMatchesBuiltInCompatibility");var qp=1e4,Mp=5*1024,Dp=0,zp=90*24*60*60,ji=["authorization_code","refresh_token",Bt,Re],jp=["authorization_code","refresh_token"],Hi=[po],Hp=["code"],Bp=d.object({client_name:d.string().min(1).optional(),redirect_uris:d.array(d.string().min(1)).min(1),grant_types:d.array(d.enum(ji)).min(1).max(ji.length).optional(),authorization_grant_profiles_supported:d.array(d.enum(Hi)).min(1).max(Hi.length).optional(),response_types:d.array(d.enum(Hp)).min(1).max(1).optional(),scope:d.literal(E).optional(),token_endpoint_auth_method:ho.optional(),jwks_uri:d.string().min(1).optional()});function Lp(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&$(t))&&t.pathname!=="/"}catch{return!1}}n(Lp,"isCimdClientIdCandidate");function Bi(e,t){throw new m("invalid_client",So({clientId:e})??"OAuth client is not registered.",void 0,t===void 0?void 0:{cause:t})}n(Bi,"invalidCimdClientError");function et(e,t="invalid_request"){if(Np(e))throw new m(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new m(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new m(t,"redirect_uris must not include credentials or fragments.");if(Di({url:r}).kind==="rejected")throw new m(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}n(et,"assertValidRedirectUri");function Np(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}n(Np,"hasForbiddenRawRedirectUriCharacter");async function Jp(e){let{response:t,json:r}=await na(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:Dp,maxResponseBytes:Mp,timeoutMs:qp});if(!t.ok)throw w("invalid_request","CIMD metadata could not be fetched.");let o=Jt(r);for(let a of o.redirect_uris)et(a,"invalid_request");if(o.jwks_uri!==void 0&&ct(o.jwks_uri),o.client_id!==e.clientId)throw w("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return o}n(Jp,"fetchCimdMetadata");async function Gp(e){let t=Gt(e),r=await Jp({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}n(Gp,"resolveCimdClient");async function pr(e,t){let r=de.parse(e);if(Lp(r)){B().gateway.downstreamCimdEnabled||Bi(r);try{return await Gp(r)}catch(a){Bi(r,a)}}let o=await b().readClient({clientId:r});if(o.kind==="found"){let a=o.client,i=Ao(a.clientId),c=i===void 0?a.tokenEndpointAuthMethod:"private_key_jwt",s=a.jwksUri??i;if(c==="private_key_jwt"&&s===void 0)throw new m("invalid_client","Dynamic private_key_jwt client is missing JWKS metadata. Re-run client registration before authorization.");let u=Jt({client_id:a.clientId,client_name:a.clientName,redirect_uris:a.redirectUris,token_endpoint_auth_method:c,...s===void 0?{}:{jwks_uri:s}}),p={kind:"dcr",clientId:r,metadata:u};return a.hashedClientSecret&&(p.hashedClientSecret=a.hashedClientSecret),p}throw new m("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}n(pr,"resolveClient");function Li(e,t){if(!e.metadata.redirect_uris.some(r=>zi({registeredRedirectUri:r,requestedRedirectUri:t})))throw w("invalid_request","redirect_uri is not registered for the client.")}n(Li,"assertRedirectRegistered");function Fp(e){return e===void 0?[...jp]:Array.from(new Set(e))}n(Fp,"normalizeGrantTypes");function $p(e){try{ct(e)}catch(t){throw new m("invalid_client_metadata","jwks_uri must be an HTTPS URL with a path, no credentials or fragment, and must not point at a blocked host.",void 0,{cause:t})}}n($p,"assertValidDcrJwksUri");function Zp(e){return e.tokenEndpointAuthMethod==="private_key_jwt"&&e.jwksUri!==void 0?de.parse(vo({clientId:crypto.randomUUID(),jwksUri:e.jwksUri})):de.parse(`dcr:${crypto.randomUUID()}`)}n(Zp,"createDcrClientId");function tt(e){if(e===void 0||e===E)return E;throw new m("invalid_request",`Only the ${E} scope is supported.`)}n(tt,"assertSupportedOAuthScope");function qe(e,t,r){let o;try{o=new URL(t)}catch{throw new m("invalid_target","resource must be an absolute URI.")}if(o.hash)throw new m("invalid_target","resource must not include a fragment.");if(o.protocol!=="https:"&&!$(o))throw new m("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let a=P(e,r),i=uo(),c=i?[...i.byOperationId.values()].find(s=>new URL(s.routePath,a).toString()===t):void 0;if(!c)throw new m("invalid_target","resource must match a published MCP route.");return c}n(qe,"resolveResource");async function Ni(e){let t;try{t=Bp.parse(e)}catch(R){if(R instanceof d.ZodError){let q=R.issues.some(O=>O.path[0]==="redirect_uris");throw new m(q?"invalid_redirect_uri":"invalid_client_metadata",R.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:R})}throw R}for(let R of t.redirect_uris)et(R,"invalid_redirect_uri");if(t.token_endpoint_auth_method==="private_key_jwt"&&t.jwks_uri===void 0)throw new m("invalid_client_metadata","jwks_uri is required for private_key_jwt clients.");t.jwks_uri!==void 0&&$p(t.jwks_uri);let r=new Date,o=t.token_endpoint_auth_method??"none",a=o==="private_key_jwt"?"none":o,i=Zp({tokenEndpointAuthMethod:o,jwksUri:t.jwks_uri}),c=Jt({client_id:i,client_name:t.client_name??"Dynamically registered MCP client",redirect_uris:t.redirect_uris,token_endpoint_auth_method:o,...t.jwks_uri===void 0?{}:{jwks_uri:t.jwks_uri}}),s=se(r,zp),u=Math.floor(r.getTime()/1e3),p=Math.floor(s.getTime()/1e3),h={client_id:c.client_id,client_name:c.client_name,redirect_uris:c.redirect_uris,grant_types:Fp(t.grant_types),authorization_grant_profiles_supported:t.authorization_grant_profiles_supported,response_types:["code"],scope:E,token_endpoint_auth_method:c.token_endpoint_auth_method,client_id_issued_at:u,jwks_uri:c.jwks_uri},y={clientId:c.client_id,clientName:c.client_name,redirectUris:c.redirect_uris,tokenEndpointAuthMethod:a,createdAt:I(r),clientExpiresAt:I(s)};if(o==="client_secret_basic"||o==="client_secret_post"){let R=ue();y.hashedClientSecret=await x(R),y.clientSecretExpiresAt=I(s),h.client_secret=R,h.client_secret_expires_at=p,h.client_secret_issued_at=u}if((await b().registerClient(y)).kind==="already_exists")throw w("invalid_request","OAuth client is already registered.");return h}n(Ni,"registerDownstreamClient");function Kp(e){return e?.metadata?.idpSubjectTokenType!==Le&&e?.metadata?.idpSubjectTokenExpiresAt!==void 0&&new Date(e.metadata.idpSubjectTokenExpiresAt).getTime()<=Date.now()?!1:e?.status==="active"&&e.metadata?.encryptedIdpSubjectToken!==void 0&&e.metadata.idpSubjectTokenType!==void 0}n(Kp,"hasStoredIdJagSubjectTokenBinding");async function Ji(e){let t=He(e.principal.subjectId);return(await b().batchGetUpstreamConnections([{owner:t,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId}]))[0]}n(Ji,"readIdJagSubjectConnection");async function pn(e){let t=Y().byOperationId.get(e.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag")return!1;let r=await Ji({connection:t.connection,principal:e.principal});return!Kp(r)}n(pn,"requiresIdJagSubjectTokenBinding");async function Gi(e){if(e.subjectToken===void 0)return;let t=Y().byOperationId.get(e.transaction.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag"||e.principal.subjectId!==e.transaction.principal.subjectId)return;let r=await Ji({connection:t.connection,principal:e.principal});return b().upsertUpstreamConnection({id:r?.id??Ft(),ownerMode:"user",subjectId:e.transaction.principal.subjectId,upstreamServerId:t.connection.upstreamServerId,authProfileId:t.connection.authProfileId,status:"active",encryptedAccessToken:r?.encryptedAccessToken,encryptedRefreshToken:r?.encryptedRefreshToken,scopes:r?.scopes??[],expiresAt:r?.expiresAt,metadata:{...r?.metadata??{},encryptedIdpSubjectToken:await pe(e.subjectToken.token),idpSubjectTokenType:e.subjectToken.tokenType,idpSubjectTokenExpiresAt:e.subjectToken.expiresAt}})}n(Gi,"bindIdJagSubjectTokenForAuthorizationTransaction");function mr(e){return S`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}n(mr,"renderShellIcon");function Fi(e){return S`<form class="actions" method="post" action="${e.setupAction}" ${e.submitOnceAttrs}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate >Cancel</button><button class="button button--primary" type="submit" name="decision" value="approve" ${e.authorizeAttrs} >Authorize</button></form>`}n(Fi,"renderActions");var $i=me('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="4.6" x2="8" y2="8.4"/><circle cx="8" cy="11" r=".7" fill="currentColor" stroke="none"/></svg>');function Zi(e){return S`<div class="banner banner--warning" role="status"><span class="banner__icon" aria-hidden="true">${e.icon}</span><div class="banner__body"><p class="banner__title">Setup required</p><p class="banner__message">${e.message}</p></div></div>`}n(Zi,"renderBannerWarning");var RR=me('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),bR=me('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>');var IR=me('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var Wp="data:,",Ki=S`data-submit-once="true" onsubmit="if (this.dataset.submitted === 'true') return false; this.dataset.submitted = 'true'; setTimeout(() => this.querySelectorAll('button').forEach((button) => { button.disabled = true; }), 0);"`,Wi=S`data-activate-once="true" onclick="if (this.dataset.activated === 'true') return false; this.dataset.activated = 'true'; this.setAttribute('aria-disabled', 'true'); this.style.pointerEvents = 'none';"`;function Vp(e,t,r){if(e)try{let o=new URL(t).origin,a=new URL(e,o);return a.origin!==o||!a.pathname.startsWith(r.actionPath("/auth/connections/"))?void 0:a.toString()}catch{return}}n(Vp,"safeGatewayConnectHref");function Yp(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}n(Yp,"deriveMode");function Xp(e){return Fi({state:e.state,setupAction:e.gateway.actionPath("/oauth/setup"),submitOnceAttrs:Ki,authorizeAttrs:X})}n(Xp,"renderActions");function mn(e,t,r,o){for(let a of e){if(a.ownerMode!=="user"||a.status!==r)continue;let i=Vp(a.connectUrl,t,o);if(i)return i}}n(mn,"firstUserConnectHref");function Qp(e){let t=e.connectHref===void 0?X:S`<a class="button button--primary" href="${e.connectHref}" ${Wi}>Connect</a>`;return S`<form class="actions" method="post" action="${e.gateway.actionPath("/oauth/setup")}" ${Ki}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate>Cancel</button>${t}</form>`}n(Qp,"renderSetupActions");function em(e){return e?S`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${Wi}>Re-connect<span class="tooltip" tabindex="0" aria-label="Reset or change how the gateway connects to the upstream service, including changing scopes.">?</span></a></span>`:X}n(em,"renderReconnectAction");function tm(e){try{let t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?!0:t.protocol==="data:"&&/^data:image\/(?:png|jpe?g|webp|svg\+xml);/i.test(e)}catch{return!1}}n(tm,"isRenderableIconHref");function Vi(e){return e?.find(t=>tm(t.src))?.src}n(Vi,"readIconHref");function rm(e){return Vi(e.serverIcons)??(e.transportHost===void 0?void 0:Jr(e.transportHost).src)}n(rm,"readUpstreamIconHref");function nm(e){let t=Vi(e.routeIcons);if(t!==void 0)return t;for(let r of e.upstreams){let o=rm(r);if(o!==void 0)return o}}n(nm,"readHeaderIconHref");function om(e){let t=e.setupMessage===void 0?X:Zi({icon:$i,message:e.setupMessage});return S`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>${t}`}n(om,"renderBody");function fn(e){let t=Yp(e.upstreams),r=mn(e.upstreams,e.gatewayOrigin,"not_connected",e.gateway),o=mn(e.upstreams,e.gatewayOrigin,"reconsent_required",e.gateway),a=mn(e.upstreams,e.gatewayOrigin,"active",e.gateway),i=t==="setup"?r??o:void 0,c=t==="setup"?e.upstreams.find(p=>p.ownerMode==="user"&&p.status!=="active"&&p.connectUrl===void 0&&p.setupMessage!==void 0)?.setupMessage:void 0,s=nm({routeIcons:e.routeIcons,upstreams:e.upstreams}),u=t==="setup"?S`<footer class="card__footer">${Qp({state:e.state,connectHref:i,gateway:e.gateway})}</footer>`:S`<footer class="card__footer">${em(a)}${Xp({state:e.state,gateway:e.gateway})}</footer>`;return We(Ye({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:s??Wp,styles:Ve,headerIcon:s===void 0?X:mr({iconHref:s,fallbackIconHref:Yt}),heading:"Authorize access",subhead:X,body:om({routeDisplayName:e.routeDisplayName,clientDisplayName:e.clientDisplayName,setupMessage:c}),footer:u}))}n(fn,"renderConsentPage");var am=1e4,Yi="mcp-session-id",im;function rs(){return{tools:[],prompts:[],resources:[]}}n(rs,"emptyCapabilities");function Xi(){return new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":Ar})}n(Xi,"buildReadinessHeaders");async function Qi(e){if(e.type==="bearer_token"){let o=Xi();return o.set("authorization",`Bearer ${e.token}`),o}let t=await e.provider.tokens();if(!t)return;let r=Xi();return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}n(Qi,"buildAsyncCredentialHeaders");function es(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(jt.parse({jsonrpc:zt,id:1,method:"initialize",params:{protocolVersion:Ar,capabilities:{},clientInfo:{name:"zuplo-mcp-gateway-readiness",version:"0.0.0"}}}))})}n(es,"buildInitializePreflight");async function hn(e){st(e.url);let t=new AbortController,r=setTimeout(()=>t.abort(),am);try{let o=new Request(e,{redirect:"manual",signal:t.signal});return await Pt.fetch(o)}finally{clearTimeout(r)}}n(hn,"runPreflight");function gn(e){e.body?.cancel().catch(()=>{})}n(gn,"releasePreflightBody");async function sm(e){let t=e.response.headers.get(Yi);if(!t)return;let r=new Headers(e.headers);r.set(Yi,t),r.delete("content-type");try{let o=await hn(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));gn(o)}catch{}}n(sm,"terminatePreflightSession");async function ns(e){let{response:t}=e;return gn(t),t.status>=200&&t.status<300?(await sm(e),{kind:"ready",upstreamStatus:t.status,capabilities:rs()}):t.status===401||t.status===403?{kind:"upstream_auth_rejected",status:t.status,message:"Upstream MCP server rejected the configured credential."}:{kind:"upstream_unavailable",status:t.status,message:"Upstream MCP server did not accept the readiness preflight."}}n(ns,"classifyResponse");function ts(e){let t={status:e.state==="reconsent_required"?"reconsent_required":"not_connected",connected:!1};return e.nextAction==="admin_setup_required"?{kind:"admin_setup_required",payload:e,connectionStatus:t}:{kind:"connect_required",payload:e,connectionStatus:t}}n(ts,"connectRequiredResult");async function cm(e){try{return ns({response:await hn(e.request),upstreamUrl:e.upstreamUrl,headers:e.headers})}catch(t){return{kind:"upstream_unavailable",message:t instanceof Error?t.message:"Upstream MCP server readiness preflight failed."}}}n(cm,"classifyPreflight");async function dm(e){let t=e.route.connection;if(t===void 0)return{kind:"ready",upstreamStatus:204,capabilities:rs()};let r=ir(t.upstreamServerId,e.route.operationId),o=Ke(r,e.subjectId),a=e.returnTo===void 0?o:{...o,returnTo:e.returnTo},i=new Request(e.requestUrl,{headers:e.requestHeaders}),c=await Ze({request:i,routeAuth:a,preloadedConnection:e.preloadedConnection});if(c.kind==="connect_required")return ts(c.payload);let s=await Qi(c.credential);if(s===void 0)return{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens."};let u=es({upstreamUrl:t.mcpUrl,headers:s}),p;try{p=await hn(u)}catch(T){return{kind:"upstream_unavailable",message:T instanceof Error?T.message:"Upstream MCP server readiness preflight failed."}}if(p.status!==401)return ns({response:p,upstreamUrl:t.mcpUrl,headers:s});gn(p);let h=await Ze({request:i,routeAuth:a,forceRefresh:!0,preloadedConnection:e.preloadedConnection});if(h.kind==="connect_required")return ts(h.payload);let y=await Qi(h.credential);return y===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:cm({request:es({upstreamUrl:t.mcpUrl,headers:y}),upstreamUrl:t.mcpUrl,headers:y})}n(dm,"checkUpstreamRouteReadinessImpl");function os(e){return(im??dm)(e)}n(os,"checkUpstreamRouteReadiness");function um(e){try{return new URL(e).host}catch{return}}n(um,"safeUrlHost");function as(e){return e!==void 0&&e.length>0}n(as,"hasItems");function lm(e){let t=e.serverInfo?.icons;if(as(t))return t;let r=Xt(e.mcpUrl);return r===void 0?void 0:[r]}n(lm,"readServerIcons");async function pm(e){let{authConfig:t,authMode:r,description:o,displayName:a,mcpUrl:i,ownerMode:c,upstreamServerId:s,authProfileId:u}=e.registeredConnection,p=c==="user",h=p&&r!=="id-jag",y=e.readiness??(p?To(e.connection):{connected:!0,status:"active"}),T=h?e.readiness?.connectUrl??(e.returnTo!==void 0?await $r({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:s,authProfileId:u,operationId:e.route.operationId,returnTo:e.returnTo}):void 0):void 0,R=t.mode==="id-jag"?t.idJag.scopes:t.oauth.scopes;return{upstreamServerId:s,authProfileId:u,authMode:r,ownerMode:c,upstreamDisplayName:a,description:o,transportHost:um(i),scopesRequested:as(R)?R:void 0,serverIcons:lm(e.registeredConnection),status:y.status,connected:y.connected,capabilities:{tools:[],prompts:[],resources:[]},connectUrl:T,setupMessage:e.setupMessage,updatedAt:p&&"updatedAt"in y&&y.updatedAt!==void 0?y.updatedAt:void 0,expiresAt:e.readiness?.expiresAt??e.connection?.expiresAt}}n(pm,"buildSetupRequirement");function is(e){let t=Y().byOperationId.get(e);if(!t)throw w("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}n(is,"requireRoute");async function yn(e){let t=is(e.transaction.operationId),r=He(e.transaction.principal.subjectId),o=t.connection;if(o===void 0)return[];let i=o.ownerMode==="user"?(await b().batchGetUpstreamConnections([{owner:r,upstreamServerId:o.upstreamServerId,authProfileId:o.authProfileId}]))[0]:void 0,c=await os({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,route:t,subjectId:e.transaction.principal.subjectId,preloadedConnection:i,returnTo:e.returnTo}),s="connectionStatus"in c?c.connectionStatus:void 0,u=(c.kind==="connect_required"||c.kind==="admin_setup_required")&&c.payload.authUrl!==void 0?c.payload.authUrl:void 0,p=c.kind==="admin_setup_required"?c.payload.message:void 0;return[await pm({connection:i,registeredConnection:o,route:t,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:e.returnTo,transaction:e.transaction,userOwner:r,setupMessage:p,readiness:s===void 0?void 0:{...s,connectUrl:u}})]}n(yn,"requirementsForSetup");async function _n(e){let t=is(e.transaction.operationId),r=await b().readClient({clientId:e.transaction.clientId}),o=r.kind==="found"?r.client:void 0,a={gatewayOrigin:P(e.requestUrl,e.requestHeaders),routeDisplayName:t.connection?.displayName??t.operationId,clientDisplayName:o?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},i=t.connection?.description;return i!==void 0&&(a.routeDescription=i),a}n(_n,"consentContext");function wn(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}n(wn,"hasUnresolvedUserUpstream");var mm=["mcp_user"],fm="dev-browser-user",hm=["resource is required for /oauth/authorize.","MCP clients should start at the MCP server URL and follow its WWW-Authenticate resource_metadata link.","If your client reached this endpoint directly, use /oauth/authorize/{routePath} where {routePath} is the published MCP route path without a leading slash and each segment is URL-encoded as needed, for example /oauth/authorize/mcp/linear, or add resource={protected resource URI from protected-resource metadata}."].join(" "),gm=d.object({response_type:d.literal("code"),client_id:d.string().min(1),redirect_uri:d.string().min(1),resource:d.url(),code_challenge:d.string().min(43),code_challenge_method:mo,state:d.string().min(1).optional(),scope:d.literal(E).default(E)}),ym=d.enum(["continue","approve","cancel"]).default("continue"),_m=d.object({state:d.string().min(1),decision:ym}),ve=class extends Error{static{n(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription}};function ss(e){return typeof e=="string"&&e.length>0?e:void 0}n(ss,"readQueryString");function wm(e,t){let r=ss(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new m("invalid_target",hm)}let o=Ro(t,e.url,e.headers);if(r===void 0||r===o)return o;throw new m("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}n(wm,"requireAuthorizeResource");async function Rm(e,t){let r={};t!==void 0&&(r.context=t);let o=await ur(e,r);if(o.principal)return{principal:o.principal};if(!e.user)return o.evictCookie===void 0?{}:{setCookie:o.evictCookie};let a=Ei(e);return{principal:a,setCookie:await lr({principal:a,requestUrl:e.url,requestHeaders:e.headers})}}n(Rm,"resolveBrowserPrincipal");async function bm(e,t){let r={};t!==void 0&&(r.context=t);let o=await ur(e,r);if(!o.principal)throw w("authentication_required","Authorization setup requires a current browser session.");return o.principal}n(bm,"requireSetupPrincipal");function cs(e){return`${j().actionPath("/oauth/setup")}?state=${encodeURIComponent(e)}`}n(cs,"buildSetupReturnTo");async function ds(e){let t=await yn({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:cs(e.csrfToken)}),r=await _n({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders}),o={kind:"setup_page",html:fn({state:e.csrfToken,operationId:e.transaction.operationId,gateway:j(),upstreams:t,...r})};return e.setCookie!==void 0&&(o.setCookie=e.setCookie),o}n(ds,"renderSetup");function Im(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}n(Im,"toAuthorizationTransactionClient");async function Rn(e,t={}){let r=gm.parse({...e.query,resource:wm(e,t.operationId),state:ss(e.query.state)}),o=tt(r.scope);et(r.redirect_uri,"invalid_request");let a=new Date,i=de.parse(r.client_id),c=await pr(r.client_id,a);Li(c,r.redirect_uri);try{let s=qe(e.url,r.resource,e.headers),u=Im(c);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:i,operationId:s.operationId,scope:o,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved"),t.context&&v(t.context,{eventType:C.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:s.operationId,attributes:{clientId:i,scope:o,responseType:r.response_type}});let p={clientId:c?.clientId??i,...u===void 0?{}:{client:u},redirectUri:r.redirect_uri,resource:r.resource,operationId:s.operationId,scope:o,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state}},{principal:h,setCookie:y}=await Rm(e,t.context),T=h===void 0?!1:await pn({operationId:s.operationId,principal:h});if(!h||T){let q=await Ci({transaction:p,requestUrl:e.url,requestHeaders:e.headers,now:a});t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:i,operationId:s.operationId,reason:h?"id_jag_subject_binding_missing":"no_browser_session"},"Downstream OAuth authorize: redirecting to browser login");let O={kind:"redirect",location:q.browserLoginUrl};return y!==void 0&&(O.setCookie=y),O}let R=await Si({transaction:p,principal:h,now:a});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:i,operationId:s.operationId,subjectId:h.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),t.context&&v(t.context,{eventType:C.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:s.operationId,attributes:{clientId:i,scope:o,responseType:r.response_type,subjectId:h.subjectId}}),ds({transaction:R.transaction,csrfToken:R.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookie:y})}catch(s){throw Cm({redirectUri:r.redirect_uri,clientState:r.state,cause:s})}}n(Rn,"authorizeDownstreamClient");function Cm(e){if(e.cause instanceof ve)return e.cause;let t=Sm(e.cause);return t?new ve({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}n(Cm,"toDownstreamAuthorizeRedirectError");function Sm(e){if(e instanceof m)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof d.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}n(Sm,"mapToOAuthRedirectError");async function us(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let p=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,h=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...p===void 0?{}:{idpErrorDescription:p},...h===void 0?{}:{idpErrorUri:h}},"Identity provider redirected browser-login callback with an error"),w("provider_access_denied",p??"The delegated browser login was not completed.")}let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),w("oauth_state_invalid","Browser login callback is missing state.");let a=await on(o),i={request:e,stateId:a.stateId};t.context!==void 0&&(i.context=t.context);let c=await Oi(i),s=await vi({browserLoginStateToken:o,principal:c.principal});if(await Gi({transaction:s.transaction,principal:c.principal,subjectToken:c.subjectToken}),await pn({operationId:s.transaction.operationId,principal:c.principal}))throw w("browser_login_verification_failed","The identity provider did not return the subject token required for XAA / ID-JAG.");let u=await ds({transaction:s.transaction,csrfToken:s.csrfToken,requestUrl:e.url,requestHeaders:e.headers});return u.setCookie=await lr({principal:c.principal,requestUrl:e.url,requestHeaders:e.headers}),u}n(us,"completeBrowserLoginCallback");async function ls(e){let t=B(),r=new URL(e.url);if(!$(r))throw w("forbidden","Local browser login is only available on loopback HTTP origins.");let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw w("oauth_state_invalid","Local browser login is missing state.");let a=j().actionPath("/oauth/callback"),i=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:a,P(e.url)),c=new URL(P(e.url)).origin;if(i.origin!==c||i.pathname!==a)throw w("oauth_callback_mismatch",`Local browser login redirect_uri must target this gateway's ${a} route.`);i.searchParams.set("state",o);let s={subjectId:ot.parse(fm),roles:mm};return{kind:"redirect",location:i,setCookie:await lr({principal:s,requestUrl:e.url,requestHeaders:e.headers})}}n(ls,"completeLocalDevBrowserLogin");function vm(e){let t=e.method==="POST"?e.body:e.query;return _m.parse(t)}n(vm,"readSetupContinueRequest");async function ps(e){let{state:t,decision:r}=vm({method:e.request.method,query:e.request.query,body:e.body}),o=new Date,a=await cn({csrfToken:t,now:o}),i=await bm(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await ki({csrfToken:t,currentBrowserPrincipal:i,now:o})};let c=await Ai({csrfToken:t,currentBrowserPrincipal:i,now:o}),s=await yn({transaction:c,requestUrl:e.request.url,requestHeaders:e.request.headers,returnTo:cs(t)});if(r==="approve"&&wn(s)&&await bi({csrfToken:t,currentBrowserPrincipal:i,now:o}),wn(s)){let u=await _n({transaction:c,requestUrl:e.request.url,requestHeaders:e.request.headers});return{kind:"setup_page",html:fn({state:t,operationId:c.operationId,gateway:j(),upstreams:s,...u})}}return{kind:"redirect",location:await xi({csrfToken:t,currentBrowserPrincipal:i,now:o})}}n(ps,"continueDownstreamAuthorizeSetup");F();import{createLocalJWKSet as jm,decodeJwt as Hm,errors as At,jwtVerify as Bm}from"jose";F();import{createRemoteJWKSet as Am,decodeJwt as xm,decodeProtectedHeader as km,errors as vt,jwtVerify as Um}from"jose";var ys=30,k=d.string().min(1),Tm=d.union([k,d.array(k).min(1)]),Pm=d.union([k,d.array(k).min(1)]),Em=d.object({type:k,locations:d.array(k).optional(),actions:d.array(k).optional(),datatypes:d.array(k).optional(),identifier:k.optional(),privileges:d.array(k).optional()}).passthrough(),Om=d.object({iss:d.url(),sub:k,aud:Tm,client_id:k,resource:Pm.optional(),scope:k.optional(),authorization_details:d.array(Em).optional(),jti:k,iat:d.number().int(),nbf:d.number().int().optional(),exp:d.number().int(),tenant:k.optional(),aud_tenant:k.optional(),aud_sub:k.optional(),sub_id:k.optional(),act:d.unknown().optional(),email:k.optional(),auth_time:d.number().int().optional(),acr:k.optional(),amr:d.array(k).optional(),cnf:d.unknown().optional()}).passthrough();function W(e){throw new m("invalid_grant",e)}n(W,"throwInvalidGrant");function qm(e){return e instanceof vt.JWTExpired?"expired":e instanceof vt.JWTClaimValidationFailed?"claim":e instanceof vt.JWSSignatureVerificationFailed?"signature":e instanceof vt.JWKSNoMatchingKey?"jwks_no_match":e instanceof vt.JWTInvalid?"invalid":e instanceof d.ZodError?"schema":"other"}n(qm,"readJwtFailureKind");function Mm(e){return Array.isArray(e.aud)?(e.aud.length!==1&&W("ID-JAG audience must contain exactly one value."),e.aud[0]):e.aud}n(Mm,"readSingleAudience");function ms(e){try{let t=Om.parse(e);return Mm(t),t}catch(t){if(t instanceof m)throw t;W("ID-JAG claims are invalid.")}}n(ms,"parseIdJagClaims");function Dm(e,t){e.idJag.enabled||W("ID-JAG grant is not enabled.");let r=e.idJag.trustedIssuers.find(o=>o.issuer===t);return r===void 0&&W("ID-JAG issuer is not trusted."),r}n(Dm,"readTrustedIssuer");function zm(e){let t=e.authorizationDetails;if(t===void 0)return;if(e.allowedTypes===void 0)return t;let r=new Set(e.allowedTypes);return t.filter(o=>r.has(o.type))}n(zm,"readGrantedAuthorizationDetails");function fs(e){if(e.clientAuth.method==="none")throw new m("invalid_client","Client authentication failed.");e.claims.client_id!==e.authenticatedClientId&&W("ID-JAG client_id must match the authenticated client."),e.trustedIssuer.expectedClientIds!==void 0&&!e.trustedIssuer.expectedClientIds.includes(e.claims.client_id)&&W("ID-JAG client_id is not allowed for this issuer.")}n(fs,"assertClientBinding");function hs(e){e.cnf!==void 0&&W("ID-JAG cnf-bound assertions require DPoP support.")}n(hs,"assertProofOfPossessionNotDeferred");function gs(e){let t=Math.floor(e.now.getTime()/1e3)+ys;e.claims.iat>t&&W("ID-JAG iat must not be in the future.")}n(gs,"assertIssuedAtNotInFuture");async function _s(e){let t;try{t=km(e.assertion)}catch{W("ID-JAG assertion is malformed.")}t.typ!==Rr&&W('ID-JAG header typ must be "oauth-id-jag+jwt".');let r;try{r=ms(xm(e.assertion))}catch(s){if(s instanceof m)throw s;W("ID-JAG assertion is malformed.")}let o=Be(e.requestUrl,e.requestHeaders),a=[o];e.requestedResource!==void 0&&e.requestedResource!==o&&a.push(e.requestedResource);let i=Dm(e.config,r.iss);a.includes(r.iss)&&W("ID-JAG issuer must be different from the gateway."),fs({claims:r,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),hs(r),gs({claims:r,now:e.now});let c;try{let s=Am(new URL(i.jwksUrl)),{payload:u}=await Um(e.assertion,s,{issuer:i.issuer,audience:a,currentDate:e.now,clockTolerance:ys,typ:Rr});c=ms(u)}catch(s){e.context?.log.warn({event:"oauth_id_jag_verification_failed",issuer:i.issuer,failureKind:qm(s)},"OAuth ID-JAG assertion verification failed"),W("ID-JAG assertion verification failed.")}return fs({claims:c,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),hs(c),gs({claims:c,now:e.now}),{claims:c,trustedIssuer:i,subjectId:bo({issuer:c.iss,subject:c.sub,gatewayIssuer:o,subjectMapping:i.subjectMapping,tenant:c.tenant}),grantedAuthorizationDetails:zm({authorizationDetails:c.authorization_details,allowedTypes:e.config.idJag.enabled?e.config.idJag.authorizationDetailsTypesAllowed:void 0})}}n(_s,"verifyIdJagAssertion");var Lm=new Set(["authorization_code","refresh_token",Re]),Nm=1e4,Jm=32*1024,Gm=2,Fm=60*60,bn=d.object({client_id:d.string().min(1).optional(),client_secret:d.string().min(1).optional(),client_assertion_type:d.string().min(1).optional(),client_assertion:d.string().min(1).optional()}),$m=d.discriminatedUnion("grant_type",[bn.extend({grant_type:d.literal("authorization_code"),code:d.string().min(1),redirect_uri:d.string().min(1),code_verifier:Nt,resource:d.url().optional(),scope:d.literal(E).optional()}),bn.extend({grant_type:d.literal("refresh_token"),refresh_token:d.string().min(1),resource:d.url().optional(),scope:d.literal(E).optional()}),bn.extend({grant_type:d.literal(Re),assertion:d.string().min(1),resource:d.url().optional(),scope:d.literal(E).optional(),authorization_details:d.string().min(1).optional()})]);function Zm(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!Lm.has(t)))throw new m("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}n(Zm,"assertSupportedGrantType");var Km=d.object({token:d.string().min(1),client_id:d.string().min(1).optional(),token_type_hint:d.string().optional(),client_secret:d.string().min(1).optional(),client_assertion_type:d.string().min(1).optional(),client_assertion:d.string().min(1).optional()}),Wm=d.object({keys:d.array(d.record(d.string(),d.unknown())).min(1)}).passthrough();function Rs(){return B().gateway.accessTokenTtlSeconds}n(Rs,"readAccessTokenTtlSeconds");function Vm(){return B().gateway.refreshTokenTtlSeconds}n(Vm,"readRefreshTokenTtlSeconds");function ws(e,t){let r=Rs(),o=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),a=Math.min(r,o);return{expiresAt:I(se(e,a)),expiresIn:a}}n(ws,"calculateAccessTokenExpiresAt");function Ym(e){let t=e.claimedResource===void 0?[]:Array.isArray(e.claimedResource)?e.claimedResource:[e.claimedResource];if(e.requestedResource!==void 0){if(t.length>0&&!t.includes(e.requestedResource))throw new m("invalid_target","Token request resource must match the ID-JAG resource.");return e.requestedResource}if(t.length===0)throw new m("invalid_target","resource is required for the ID-JAG JWT bearer grant.");if(t.length!==1)throw new m("invalid_target","ID-JAG resource arrays require a token request resource.");return t[0]}n(Ym,"readIdJagResource");function Xm(e){if(e.claimAuthorizationDetails===void 0)return;let t=(e.grantedAuthorizationDetails??[]).filter(r=>r.locations?.includes(e.resource)===!0);if(t.length===0)throw new m("invalid_grant","ID-JAG authorization_details must authorize the requested resource.");return t}n(Xm,"readIdJagGrantedAuthorizationDetails");function Qm(e){if(e.claimScope?.split(/\s+/).includes(E)===!0||(e.grantedAuthorizationDetails?.length??0)>0)return E;if(e.claimScope===void 0)throw new m("invalid_grant",`ID-JAG must include ${E} scope or matching authorization_details.`);if(!e.claimScope.split(/\s+/).includes(E))throw new m("invalid_grant",`ID-JAG scope must include ${E}.`);return E}n(Qm,"readIdJagGrantedScope");function ef(e){if(e!==void 0&&e.get("dpop")!==null)throw new m("invalid_request","DPoP proofs are not supported for the ID-JAG JWT bearer grant.")}n(ef,"assertNoDpopProofForIdJag");function bs(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new m("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new m("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new m("invalid_client","Malformed HTTP Basic client authentication.")}}n(bs,"readBasicClientSecret");function Is(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new m("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t!==void 0)return t;if(e.clientAssertion!==void 0){try{let r=Hm(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new m("invalid_client","Malformed private_key_jwt client assertion.")}throw new m("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new m("invalid_client","Client authentication or client_id is required.")}n(Is,"resolveAuthenticatedClientId");function tf(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new m("invalid_request","Use only one client authentication method per request.");return e.basicClientSecret!==void 0?{clientSecret:e.basicClientSecret,clientSecretSource:"basic"}:e.bodyClientSecret!==void 0?{clientSecret:e.bodyClientSecret,clientSecretSource:"post"}:{}}n(tf,"resolveClientSecretInput");function rf(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}n(rf,"hasClientAssertion");function nf(e){if(e.requestUrl===void 0)throw new m("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(j().actionPath(e.pathname),P(e.requestUrl,e.requestHeaders));return t.search="",t.hash="",t.toString()}n(nf,"buildEndpointAudience");function of(e){return e instanceof At.JWTExpired?"expired":e instanceof At.JWTClaimValidationFailed?"claim":e instanceof At.JWSSignatureVerificationFailed?"signature":e instanceof At.JWKSNoMatchingKey?"jwks_no_match":e instanceof At.JWTInvalid?"invalid":e instanceof d.ZodError?"schema":"other"}n(of,"readJwtFailureKind");async function af(e){let{response:t,json:r}=await oa(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:Gm,maxResponseBytes:Jm,timeoutMs:Nm});if(!t.ok)throw new m("invalid_client","Client JWKS could not be fetched.");return Wm.parse(r)}n(af,"fetchClientJwks");async function sf(e){if(e.clientAssertionType!==Lt||e.clientAssertion===void 0)throw new m("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=de.parse(e.clientId),r=await pr(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new m("invalid_client","Client is not registered for private_key_jwt authentication.");let o=r.metadata.jwks_uri;if(o===void 0)throw new m("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let a=nf({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,pathname:e.endpointPathname});try{let i=await af({jwksUri:o,context:e.context}),{payload:c}=await Bm(e.clientAssertion,jm(i),{issuer:t,subject:t,audience:a,currentDate:e.now}),s=Math.floor(e.now.getTime()/1e3)+Fm;if(typeof c.exp!="number"||c.exp>s)throw new m("invalid_client","Client authentication failed.")}catch(i){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:of(i)},"OAuth private_key_jwt client authentication failed"),new m("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}n(sf,"verifyPrivateKeyJwtClientAssertion");async function cf(e){let t=de.parse(e.clientId);if(xo(t))throw new m("invalid_client","Client is registered for private_key_jwt authentication.");return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await x(e.clientSecret)}}n(cf,"buildRuntimeHttpClientAuth");async function Cs(e){if(rf({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new m("invalid_request","Use only one client authentication method per request.");return sf(e)}let t=tf({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return cf({clientId:e.clientId,...t})}n(Cs,"resolveRuntimeHttpClientAuth");async function Ss(e){Zm(e.body);let t=$m.parse(e.body),r=bs(e.authorizationHeader),o=Is({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date,i=await Cs({clientId:o,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,endpointPathname:"/oauth/token",now:a,context:e.context});return df({parsed:t,clientId:o,clientAuth:i,now:a,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,context:e.context})}n(Ss,"exchangeDownstreamToken");async function df(e){if(e.parsed.grant_type==="authorization_code"){et(e.parsed.redirect_uri,"invalid_request"),tt(e.parsed.scope),e.parsed.resource!==void 0&&qe(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let s=ue(),u=ue(),p=I(se(e.now,Vm())),h=ws(e.now,p),y=await b().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await x(e.parsed.code),redirectUri:e.parsed.redirect_uri,resource:e.parsed.resource,codeChallenge:await Oo(e.parsed.code_verifier),currentRefreshTokenHash:await x(s),accessTokenHash:await x(u),grantExpiresAt:p,accessTokenExpiresAt:h.expiresAt,now:I(e.now)});if(y.kind==="invalid_client")throw new m("invalid_client","Client authentication failed.");if(y.kind==="resource_mismatch")throw new m("invalid_target","Token request resource must match the authorization code resource.");if(y.kind!=="exchanged")throw new m("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&v(e.context,{eventType:C.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:u,token_type:"Bearer",expires_in:h.expiresIn,refresh_token:s,scope:y.grant.scope,resource:y.grant.resource}}if(e.parsed.grant_type===Re){tt(e.parsed.scope),ef(e.requestHeaders);let s=await _s({assertion:e.parsed.assertion,authenticatedClientId:e.clientId,clientAuth:e.clientAuth,requestUrl:e.requestUrl??e.parsed.resource??"",requestHeaders:e.requestHeaders,requestedResource:e.parsed.resource,now:e.now,context:e.context,config:B()}),u=Ym({claimedResource:s.claims.resource,requestedResource:e.parsed.resource}),p=qe(e.requestUrl??u,u,e.requestHeaders),h=Xm({claimAuthorizationDetails:s.claims.authorization_details,grantedAuthorizationDetails:s.grantedAuthorizationDetails,resource:u}),y=Qm({claimScope:s.claims.scope,grantedAuthorizationDetails:h}),T=ue(),R=I(new Date(s.claims.exp*1e3)),q=ws(e.now,R),O=await b().issueAccessTokenForIdJag({clientAuth:e.clientAuth,accessTokenHash:await x(T),subjectId:s.subjectId,resource:u,operationId:p.operationId,scope:y,authorizationDetails:h,accessTokenExpiresAt:q.expiresAt,now:I(e.now),idJag:{issuer:s.claims.iss,jti:s.claims.jti,tenant:s.claims.tenant,expiresAt:R}});if(O.kind==="invalid_client")throw new m("invalid_client","Client authentication failed.");if(O.kind==="resource_mismatch")throw new m("invalid_target","Token request resource must match the ID-JAG resource.");return e.context&&v(e.context,{eventType:C.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"jwt-bearer"}}),{access_token:T,token_type:"Bearer",expires_in:q.expiresIn,scope:O.grant.scope,resource:O.grant.resource,...h===void 0?{}:{authorization_details:h}}}tt(e.parsed.scope),e.parsed.resource!==void 0&&qe(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let t=await x(e.parsed.refresh_token),r=e.parsed.refresh_token,o=ue(),a=I(se(e.now,Rs())),i=await b().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:t,nextRefreshTokenHash:t,accessTokenHash:await x(o),resource:e.parsed.resource,accessTokenExpiresAt:a,now:I(e.now)});if(i.kind==="invalid_client")throw new m("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new m("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new m("invalid_grant","Refresh token is invalid, expired, or revoked.");qe(e.requestUrl??i.grant.resource,i.grant.resource,e.requestHeaders);let c=i.accessToken.expiresAt;return e.context&&v(e.context,{eventType:C.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),{access_token:o,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(c).getTime()-e.now.getTime())/1e3)),refresh_token:r,scope:i.grant.scope,resource:i.grant.resource}}n(df,"exchangeDownstreamTokenWithRuntimeHttp");async function vs(e){let t=Km.parse(e.body),r=bs(e.authorizationHeader),o=Is({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date;if((await b().revokeOAuthToken({clientAuth:await Cs({clientId:o,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,endpointPathname:"/oauth/revoke",now:a,context:e.context}),tokenHash:await x(t.token),now:I(a)})).kind==="invalid_client")throw new m("invalid_client","Client authentication failed.");e.context?.log.info({event:"oauth_token_revoked",clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed"),e.context&&v(e.context,{eventType:C.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}n(vs,"revokeDownstreamToken");var uf=64*1024,lf=16*1024,pf="text/html; charset=utf-8";function mf(e){let t={};for(let[r,o]of e.entries())t[r]=o;return t}n(mf,"formDataToObject");async function ff(e){return ci(e,{maxBytes:uf,label:"Request body"})}n(ff,"readJsonBody");async function Cn(e){return mf(await di(e,{maxBytes:lf,label:"Request body"}))}n(Cn,"readFormBody");async function xs(e,t,r){let o=ie(r),a=r instanceof d.ZodError?Ae(r):void 0,i={code:o??(r instanceof d.ZodError?"invalid_request":"internal_server_error")};return a!==void 0&&(i.detail=a),Mt(e,t,i)}n(xs,"handleProblem");function ks(e){return e?.requestId}n(ks,"readBrowserRequestId");function Us(e){if(!(e instanceof f))return;let t=e.extensionMembers?.[je];return typeof t=="string"?t:void 0}n(Us,"readUpstreamHtmlError");function As(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}n(As,"readRuntimeErrorExtensionString");function hf(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}n(hf,"readRuntimeErrorExtensionNumber");function gf(e){try{return new URL(e.url).pathname}catch{return}}n(gf,"readBrowserRequestPath");function Me(e){let t={code:e.code,requestId:e.requestId,routePath:gf(e.request),underlyingError:e.underlyingError};return e.error instanceof f&&(t.httpStatus=hf(e.error,ye),t.contentType=As(e.error,ze),t.upstreamUrl=As(e.error,_e)),t}n(Me,"buildBrowserErrorDiagnostic");function xt(e){let t=new Headers(e.headers);t.set("cache-control","no-store"),t.set("pragma","no-cache");let r={error:e.error};return e.errorDescription!==void 0&&(r.error_description=e.errorDescription),Response.json(r,{status:e.status??400,headers:t})}n(xt,"oauthErrorResponse");function yf(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}n(yf,"readOAuthProtocolHeaders");function _f(e,t){let r=Q("internal_server_error");return xt({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:yf(e,t)})}n(_f,"oauthProtocolErrorResponse");function In(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}n(In,"readZodOAuthErrorCode");function wf(e){let t={error:In(e)},r=Ae(e);return r!==void 0&&(t.errorDescription=r),xt(t)}n(wf,"oauthZodErrorResponse");function Rf(e){let t=ie(e);if(t===void 0)return;let r=Q(t);if(r.oauthError===void 0)return;let o={error:r.oauthError,status:If(r.oauthError)};return r.oauthError==="server_error"?o.errorDescription=r.publicDetail:e instanceof Error?o.errorDescription=e.message:o.errorDescription=r.publicDetail,xt(o)}n(Rf,"oauthGatewayProblemResponse");function bf(){let t={error:"server_error",status:500,errorDescription:Q("internal_server_error").publicDetail};return xt(t)}n(bf,"oauthFallbackErrorResponse");function If(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}n(If,"readOAuthStatus");function Sn(e,t={}){return e instanceof ve?Es(e):e instanceof m?_f(e,t):e instanceof d.ZodError?wf(e):Rf(e)??bf()}n(Sn,"oauthProblemResponse");function vn(e,t,r){let o=Xe(e.url),a=ks(t);if(r instanceof ve)return Es(r);if(r instanceof m){let s=Q("internal_server_error");return re({host:o,kind:Cf(r.errorCode),title:"Authorization failed",detail:r.errorCode==="server_error"?s.publicDetail:r.message,developerDetail:r.errorCode==="server_error"?s.publicDetail:r.message,code:r.errorCode,diagnostic:Me({request:e,requestId:a,code:r.errorCode,underlyingError:r.errorCode==="server_error"?s.publicDetail:r.message,error:r}),requestId:a,status:r.status})}if(r instanceof d.ZodError)return re({host:o,kind:"invalid_request",detail:Ae(r)??"The authorization request was invalid.",developerDetail:Ae(r)??"The authorization request was invalid.",code:In(r),diagnostic:Me({request:e,requestId:a,code:In(r),underlyingError:Ae(r)??"The authorization request was invalid.",error:r}),requestId:a});let i=ie(r);if(i!==void 0){let s=Q(i);return re({host:o,kind:Ps(i),detail:s.publicDetail,developerDetail:s.status>=500||!(r instanceof Error)?s.publicDetail:r.message,code:i,diagnostic:Me({request:e,requestId:a,code:i,underlyingError:s.status>=500||!(r instanceof Error)?s.publicDetail:r.message,error:r}),requestId:a,upstreamHtml:Us(r),status:s.status})}let c=Q("internal_server_error");return re({host:o,kind:"internal_error",detail:c.publicDetail,developerDetail:c.publicDetail,code:"server_error",diagnostic:Me({request:e,requestId:a,code:"server_error",underlyingError:c.publicDetail,error:r}),requestId:a,status:c.status})}n(vn,"browserOAuthProblemResponse");function Ts(e,t,r){let o=Xe(e.url),a=ks(t),i=ie(r);if(i!==void 0){let s=Q(i);return re({host:o,kind:Ps(i),detail:s.publicDetail,developerDetail:s.status>=500||!(r instanceof Error)?s.publicDetail:r.message,code:i,diagnostic:Me({request:e,requestId:a,code:i,underlyingError:s.status>=500||!(r instanceof Error)?s.publicDetail:r.message,error:r}),requestId:a,upstreamHtml:Us(r),status:s.status})}if(r instanceof d.ZodError)return re({host:o,kind:"invalid_request",detail:Ae(r)??"The authorization request was invalid.",developerDetail:Ae(r)??"The authorization request was invalid.",code:"invalid_request",diagnostic:Me({request:e,requestId:a,code:"invalid_request",underlyingError:Ae(r)??"The authorization request was invalid.",error:r}),requestId:a});let c=Q("internal_server_error");return re({host:o,kind:"internal_error",detail:c.publicDetail,developerDetail:c.publicDetail,code:"internal_server_error",diagnostic:Me({request:e,requestId:a,code:"internal_server_error",underlyingError:c.publicDetail,error:r}),requestId:a,status:c.status})}n(Ts,"browserGatewayProblemResponse");function Cf(e){return e==="server_error"?"internal_error":"invalid_request"}n(Cf,"readOAuthBrowserErrorKind");function Ps(e){if(Q(e).status>=500)return"internal_error";switch(e){case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"configuration_error";case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"upstream_oauth_discovery_unavailable":case"upstream_provider_access_denied":case"upstream_client_registration_required":return"admin_required";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"invalid_request":case"authentication_required":case"forbidden":case"not_found":case"too_many_requests":case"identity_context_missing":return"invalid_request";case"upstream_capability_invocation_failed":case"upstream_capability_unavailable":case"upstream_import_failed":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}n(Ps,"readGatewayBrowserErrorKind");function fe(e,t,r){let o={event:t},a=!1;if(r instanceof m)o.oauthError=r.errorCode,o.status=r.status,L(o,"error",r);else if(r instanceof ve)o.oauthError=r.errorCode,L(o,"error",r);else if(r instanceof d.ZodError){o.code="invalid_request",L(o,"error",r);let i=r.issues[0];i&&(o.zodPath=i.path.join("."))}else{let i=ie(r);if(i!==void 0){let c=Q(i);o.code=i,o.status=c.status,c.oauthError!==void 0&&(o.oauthError=c.oauthError),a=c.status>=500||c.oauthError==="server_error",L(o,"error",r)}else a=!0,L(o,"error",r)}if(a){let i=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(o,i.message)}else e.log.warn(o,"OAuth handler rejected the request")}n(fe,"logUnexpectedOAuthHandlerError");function Es(e){let t;try{t=new URL(e.redirectUri)}catch{return xt({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}n(Es,"downstreamAuthorizeRedirectErrorResponse");function Ae(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}n(Ae,"formatZodErrorDetail");function Sf(e,t){let r={event:"browser_login_callback_failed",code:ie(t)??"invalid_request"};L(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}n(Sf,"logBrowserLoginCallbackFailure");function Os(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(null,{status:302,headers:t})}n(Os,"redirectResultResponse");function fr(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":pf,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(e.html,{status:200,headers:t})}return Os(e)}n(fr,"authorizeResultResponse");async function qs(e,t){try{return Response.json(yo(e.url,e.headers))}catch(r){return fe(t,"oauth_authorization_server_metadata_failed",r),xs(e,t,r)}}n(qs,"authorizationServerMetadataHandler");async function Ms(e,t){try{let r=xr(e.params.routePath);return Response.json(_o({operationId:r.operationId,requestUrl:e.url,requestHeaders:e.headers}))}catch(r){return fe(t,"oauth_authorization_server_metadata_failed",r),xs(e,t,r)}}n(Ms,"scopedAuthorizationServerMetadataHandler");async function Ds(e,t){try{let r=await Ni(await ff(e)),o=r.client_id,a=r.client_name,i=r.redirect_uris.length,c=r.token_endpoint_auth_method;return t.log.info({event:"oauth_dcr_client_registered",clientId:o,clientName:a,redirectUriCount:i,tokenEndpointAuthMethod:c},"OAuth Dynamic Client Registration completed"),v(t,{eventType:C.MCP_OAUTH_CLIENT_REGISTERED,outcome:"success",clientName:a,attributes:{clientId:o,redirectUriCount:i,tokenEndpointAuthMethod:c}}),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return fe(t,"oauth_register_failed",r),Sn(r)}}n(Ds,"registerHandler");async function zs(e,t){try{return fr(await Rn(e,{context:t}))}catch(r){return fe(t,"oauth_authorize_failed",r),vn(e,t,r)}}n(zs,"authorizeHandler");async function js(e,t){try{let r=xr(e.params.routePath);return fr(await Rn(e,{operationId:r.operationId,context:t}))}catch(r){return fe(t,"oauth_authorize_scoped_failed",r),vn(e,t,r)}}n(js,"scopedAuthorizeHandler");async function Hs(e,t){try{let r=await us(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),fr(r)}catch(r){return Sf(t,r),Ts(e,t,r)}}n(Hs,"callbackHandler");async function Bs(e,t){try{return Os(await ls(e))}catch(r){return fe(t,"oauth_dev_login_failed",r),vn(e,t,r)}}n(Bs,"devLoginHandler");async function Ls(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await ps({request:e,body:e.method==="POST"?await Cn(e):void 0,context:t});return fr(r)}catch(r){return fe(t,"oauth_setup_failed",r),Ts(e,t,r)}}n(Ls,"setupHandler");async function Ns(e,t){try{return Response.json(await Ss({body:await Cn(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,requestHeaders:e.headers,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return fe(t,"oauth_token_failed",r),Sn(r)}}n(Ns,"tokenHandler");async function Js(e,t){try{return await vs({body:await Cn(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,requestHeaders:e.headers,context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return fe(t,"oauth_revoke_failed",r),Sn(r)}}n(Js,"revokeHandler");function Gs(e){return S`<p data-gateway-error-code="${e.code}">${e.body}</p>`}n(Gs,"renderBrowserResult");var vf="text/html; charset=utf-8",Af="none";function xf(e){let t=Nr(e.host);return Ye({title:e.title,iconHref:t,styles:Ve,headerIcon:mr({iconHref:t,fallbackIconHref:Yt}),heading:e.title,subhead:"",body:Gs({body:e.body,code:e.code??Af}),footer:""})}n(xf,"browserResultHtml");function kf(e,t=200){return new Response(We(e),{status:t,headers:{"content-type":vf,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(kf,"browserResultResponse");function Fs(e){return kf(xf(e))}n(Fs,"browserConnectionSuccessResponse");function hr(e,t,r={}){let o=Kn(t);return re({host:e,kind:Uf(t),detail:o.body,developerDetail:r.developerDetail,code:t,diagnostic:r.diagnostic,upstreamHtml:r.upstreamHtml})}n(hr,"browserConnectionFailureResponse");function Uf(e){switch(e){case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"upstream_oauth_discovery_unavailable":case"upstream_provider_access_denied":case"upstream_client_registration_required":return"admin_required"}}n(Uf,"readCallbackFailureBrowserErrorKind");var Tf={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},$s=Symbol("upstream-request");function kt(e,t){Object.defineProperty(e,$s,{configurable:!0,value:t})}n(kt,"setUpstreamRequestContext");function Pf(e){let t=e[$s];if(!t)throw new V("Upstream request context has not been set");return t}n(Pf,"readUpstreamRequestContext");function Ef(e,t){return t.some(r=>r===e)}n(Ef,"requestContextMatchesKind");function Of(e){return typeof e=="string"?[e]:e}n(Of,"toExpectedKinds");function Ut(e,t){let r=Pf(e),o=Of(t);if(!Ef(r.kind,o)){let a=Tf[o[0]];throw new V(`${a} request context has not been set`)}return r}n(Ut,"requireUpstreamRequestContext");function De(e){if(typeof e=="string"&&e.length!==0)return e}n(De,"readOptionalQueryString");function qf(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new V(`Validated path parameter ${t} is missing`);return Mf(r,t)}n(qf,"requirePathString");function Mf(e,t){try{return decodeURIComponent(e)}catch(r){throw new f({message:`Path parameter "${t}" must be valid URL encoding.`,extensionMembers:{[g]:"invalid_request"}},{cause:r})}}n(Mf,"decodePathString");function Df(e){let t=De(e);return t?Dt.parse(t):void 0}n(Df,"readOptionalOperationId");function zf(e){let t=Y().connectionsById.get(e);if(t!==void 0)return t.authProfileId;throw new f({message:`No upstream connection is registered for ${e}.`,extensionMembers:{[g]:"unknown_upstream_server"}})}n(zf,"readRegisteredAuthProfileId");function jf(e){let t=Df(e);if(!t)throw new f({message:"operationId query parameter is required.",extensionMembers:{[g]:"invalid_request"}});return t}n(jf,"readRequiredOperationId");async function Hf(e,t){let r=ir(t,jf(e.query.operationId));if(r.authMode==="id-jag")throw new f({message:"This upstream uses XAA / ID-JAG and does not support browser OAuth connection flows.",extensionMembers:{[g]:"invalid_request"}});let o=e.query.redirect==="true",a=De(e.query.browserTicket);if(e.user){if(a)throw new f({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[g]:"invalid_request"}});let s=ke(e.user,e.url),u={kind:"connect",...Ke(r,s.subjectId),redirect:o},p=to(De(e.query.returnTo));return p!==void 0&&(u.returnTo=p),u}if(!a)throw new f({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[g]:"authentication_required"}});let i=await ba(a);if(i.ownerMode!==r.ownerMode||i.upstreamServerId!==r.upstreamServerId||i.authProfileId!==r.authProfileId||i.operationId!==r.operationId)throw new f({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[g]:"oauth_callback_mismatch"}});await Ia(i);let c=Ht(i);switch(r.authMode){case"shared-oauth":{if(c.mode!=="shared")throw new f({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[g]:"oauth_callback_mismatch"}});let s={kind:"connect",...r,authMode:"shared-oauth",ownerMode:"shared",owner:c,initiatedBySubjectId:i.initiatedBySubjectId,redirect:o};return i.returnTo!==void 0&&(s.returnTo=i.returnTo),s}case"user-oauth":{if(c.mode!=="user")throw new f({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[g]:"oauth_callback_mismatch"}});let s={kind:"connect",...r,authMode:"user-oauth",ownerMode:"user",owner:c,initiatedBySubjectId:i.initiatedBySubjectId,redirect:o};return i.returnTo!==void 0&&(s.returnTo=i.returnTo),s}}}n(Hf,"resolveConnectContext");async function Bf(e,t,r){let o=Yn.parse(qf(e,"connection"));switch(r){case"connect":kt(e,await Hf(e,o));return;case"callback":{let a=De(e.query.error);if(a){let s={kind:"callback_provider_error",upstreamServerId:o,error:a},u=De(e.query.error_description);u!==void 0&&(s.errorDescription=u),kt(e,s);return}let i=De(e.query.code),c=De(e.query.state);if(i&&c){kt(e,{kind:"callback_authorization_code",upstreamServerId:o,code:i,state:c});return}kt(e,{kind:"callback_invalid",upstreamServerId:o});return}case"client_metadata":kt(e,{kind:"client_metadata",upstreamServerId:o,authProfileId:zf(o)});return}}n(Bf,"resolveUpstreamRequestInbound");async function Lf(e,t,r){try{await Bf(e,t,r);return}catch(o){let a=o instanceof f?o.extensionMembers?.[g]:void 0,i=o instanceof Error?o.message:void 0;switch(a){case"invalid_request":case"unknown_upstream_server":case"oauth_callback_mismatch":return xe.badRequest(e,t,{code:a,detail:i});case"authentication_required":return xe.unauthorized(e,t,{code:a,detail:i});default:throw o}}}n(Lf,"applyUpstreamRequestContext");function gr(e,t){return n(async(o,a)=>{let i=await Lf(o,a,e);return i||t(o,a)},"wrapped")}n(gr,"withUpstreamRequestContext");var Nf=["callback_authorization_code","callback_provider_error","callback_invalid"];function An(e){try{return new URL(e.url).pathname}catch{return}}n(An,"readBrowserRequestPath");function Jf(e){return"cause"in e?e.cause:void 0}n(Jf,"readErrorCause");function Gf(e){return e.stack?.split(`
|
|
49
|
-
`).slice(1,4).map(t=>t.trim()).join(" | ")}n(Gf,"readFirstStackFrame");function Zs(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=Gf(r))}n(Zs,"addErrorAttributes");function xn(e){if(!(e instanceof f))return;let t=e.extensionMembers?.[g];return qt(t)?t:void 0}n(xn,"readRuntimeGatewayCode");function Ks(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}n(Ks,"readRuntimeErrorExtensionString");function Ff(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}n(Ff,"readRuntimeErrorExtensionNumber");function $f(e,t,r,o){switch(r.kind){case"callback_provider_error":return t.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:r.upstreamServerId,providerError:r.error,...r.errorDescription===void 0?{}:{providerErrorDescription:r.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),v(t,{eventType:C.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:r.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:r.error,errorDescription:r.errorDescription}}),hr(o,"provider_access_denied",{developerDetail:r.errorDescription??r.error,diagnostic:{code:"provider_access_denied",requestId:t.requestId,routePath:An(e),upstreamServerId:r.upstreamServerId,providerError:r.error,providerErrorDescription:r.errorDescription,underlyingError:r.errorDescription??r.error}});case"callback_invalid":return t.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:r.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),hr(o,"oauth_state_invalid",{diagnostic:{code:"oauth_state_invalid",requestId:t.requestId,routePath:An(e),upstreamServerId:r.upstreamServerId}});case"callback_authorization_code":return r}}n($f,"requireAuthorizationCallbackRequest");function Zf(e,t){v(e,{eventType:C.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}n(Zf,"emitCallbackReceivedAnalyticsEvent");function Kf(e,t){v(e,{eventType:C.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}n(Kf,"emitTokenExchangeSucceededAnalyticsEvent");function Wf(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return Fs({host:Xe(e.url),title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}n(Wf,"buildSuccessfulCallbackResponse");function Vf(e){let t={detail:e instanceof Error?e.message:void 0};return Zs(t,"error",e),e instanceof Error&&Zs(t,"cause",Jf(e)),t}n(Vf,"buildTokenExchangeFailureAttributes");function Yf(e){v(e.context,{eventType:C.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:xn(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:Vf(e.error)})}n(Yf,"emitTokenExchangeFailedAnalyticsEvent");function Xf(e){let t=e.error,r=xn(t),o=Zn(r)?r:"upstream_token_exchange_failed",a={code:o,requestId:e.context.requestId,routePath:An(e.request),upstreamServerId:e.callbackRequest.upstreamServerId,underlyingError:t instanceof Error?t.message:void 0,...t instanceof f?{httpStatus:Ff(t,ye),contentType:Ks(t,ze),upstreamUrl:Ks(t,_e)}:{}};return hr(e.host,o,{developerDetail:t instanceof Error?t.message:void 0,diagnostic:a,upstreamHtml:Qf(t)})}n(Xf,"tokenExchangeFailureResponse");function Qf(e){if(!(e instanceof f))return;let t=e.extensionMembers?.[je];return typeof t=="string"?t:void 0}n(Qf,"readUpstreamHtmlError");async function kn(e,t){let r=Ut(e,Nf),o=Xe(e.url),a=$f(e,t,r,o);if(a instanceof Response)return a;Zf(t,a);try{let i=await Xa({request:e,callbackRequest:a});return Kf(t,i),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:i.upstreamServerId,operationId:i.operationId,authProfileId:i.authProfileId,ownerMode:i.ownerMode},"Upstream OAuth token exchange completed; user connection established"),Wf(e,i)}catch(i){let c={event:"upstream_oauth_token_exchange_failed",code:xn(i)??"upstream_token_exchange_failed",upstreamServerId:a.upstreamServerId};return L(c,"error",i),t.log.warn(c,"Upstream OAuth token exchange failed; user shown connection-failure page"),Yf({context:t,callbackRequest:a,error:i}),Xf({request:e,context:t,host:o,callbackRequest:a,error:i})}}n(kn,"callbackHandler");function eh(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}n(eh,"clientMetadataProblemDetail");async function Ws(e,t){let r=Ut(e,"connect"),o=await Ya({request:e,connectRequest:r});if(v(t,{eventType:C.MCP_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:o.operationId,upstreamServerTitle:o.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:o.authProfileId,operationId:o.operationId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),r.redirect)return Response.redirect(o.authUrl,302);let a=await nr({requestUrl:e.url,requestHeaders:e.headers,owner:o.owner,initiatedBySubjectId:o.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:o.authProfileId,upstreamDisplayName:o.upstreamDisplayName,operationId:o.operationId,subject:"MCP route",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(a,{status:428})}n(Ws,"connectHandler");async function Vs(e,t){let r=Ut(e,"client_metadata");try{let o=P(e.url,e.headers),a=ka(o,r.upstreamServerId,r.authProfileId);return Response.json(a)}catch(o){if(!(o instanceof H))throw o;let a=o instanceof Error?o.message:String(o);return t.log.warn({event:"oauth_client_metadata_request_failed",upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:a},"Failed to serve OAuth client metadata document for upstream connection"),xe.notFound(e,t,{code:"not_found",detail:eh(o)})}}n(Vs,"oauthClientMetadataHandler");function th(e,t){return e.mount==="root"?e.path:t.actionPath(e.path)}n(th,"resolveInternalRoutePath");var rh={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function nh(){return new Response(null,{status:204,headers:rh})}n(nh,"buildWellKnownPreflightResponse");function oh(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}n(oh,"withWellKnownCorsHeaders");function Un(e){return async(t,r)=>t.method==="OPTIONS"?nh():oh(await e(t,r))}n(Un,"wrapWellKnownHandler");var Qs=[{routeName:"oauth_as_metadata",mount:"root",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:Un(qs),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",mount:"root",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:Un(Ms),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",mount:"root",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:Un(wo),corsPolicy:"anything-goes"},{routeName:"oauth_register",mount:"action",path:"/oauth/register",methods:["POST"],handler:Ds},{routeName:"oauth_authorize",mount:"action",path:"/oauth/authorize",methods:["GET"],handler:zs},{routeName:"oauth_authorize_scoped",mount:"action",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:js},{routeName:"oauth_callback",mount:"action",path:"/oauth/callback",methods:["GET"],handler:Hs},{routeName:"oauth_dev_login",mount:"action",path:"/oauth/dev-login",methods:["GET"],handler:Bs},{routeName:"oauth_setup",mount:"action",path:"/oauth/setup",methods:["GET","POST"],handler:Ls},{routeName:"oauth_token",mount:"action",path:"/oauth/token",methods:["POST"],handler:Ns},{routeName:"oauth_revoke",mount:"action",path:"/oauth/revoke",methods:["POST"],handler:Js},{routeName:"upstream_client_metadata",mount:"action",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:gr("client_metadata",Vs)},{routeName:"upstream_connect",mount:"action",path:"/auth/connections/:connection/connect",methods:["GET"],handler:gr("connect",Ws)},{routeName:"upstream_callback",mount:"action",path:"/auth/connections/:connection/callback",methods:["GET"],handler:gr("callback",kn)}],ah=Qs.filter(e=>!e.routeName.startsWith("upstream_")),ih=Qs.filter(e=>e.routeName.startsWith("upstream_"));function sh(e){let t=io({routes:e.routes,policies:e.policies,gateway:e.gateway});return so(t),t}n(sh,"initializeMcpGatewayConnectionRegistry");function ch(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth!==void 0)}n(ch,"hasDownstreamOAuthRoutes");function dh(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth?.config.idJag.enabled===!0)}n(dh,"hasIdJagDownstreamOAuth");function uh(e){let t=new Map;for(let o of e.byOperationId.values())o.downstreamOAuth&&t.set(o.downstreamOAuth.policyName,o.downstreamOAuth.config);if(t.size===1)return[...t.values()][0];let r=[...t.keys()].map(o=>`"${o}"`).join(", ");throw new H(`MCP gateway found multiple attached OAuth policies: ${r}. Multiple downstream MCP OAuth configs in one gateway are not supported yet; use one MCP OAuth policy across MCP routes or split these routes into separate gateways.`)}n(uh,"readSingletonDownstreamOAuthConfig");function lh(e,t,r){let o=String(t.params.routePath??""),a=e.byRoutePath.get(fo(o));if(a===void 0)return;let i=a?.downstreamOAuth?.config;return i===void 0?Mt(t,r,{code:"not_found",detail:"The requested MCP route does not expose downstream OAuth."}):i}n(lh,"readScopedDownstreamOAuthConfig");function ph(e){return e.path==="/.well-known/oauth-authorization-server/:routePath*"||e.path==="/.well-known/oauth-protected-resource/:routePath*"||e.path==="/oauth/authorize/:routePath*"}n(ph,"routeUsesScopedOAuthConfig");function Ys(e,t,r){return async(o,a)=>{if(a.log.setLogProperties?.({requestId:a.requestId}),r){let u=await r(o,a);if(u instanceof Response)return u;u&&Fn(a,u)}let i=o.method==="OPTIONS",c=Date.now();i||a.log.info({event:`${e}_received`,method:o.method},`MCP gateway: ${e} received`);let s=await t(o,a);return i||a.log.info({event:`${e}_responded`,status:s.status,durationMs:Date.now()-c},`MCP gateway: ${e} responded`),s}}n(Ys,"wrapInternalHandler");function Xs(e,t,r,o){e.addPluginRoute({path:th(t,r),methods:t.methods,handler:o,processors:[Mn],corsPolicy:t.corsPolicy??"none"})}n(Xs,"addInternalRoute");function ec(e,t){let r=sh(t),o=ch(r),a=r.connectionsById.size>0,i,c=n(()=>(i===void 0&&(i=uh(r)),i),"readSingletonOAuthConfig");if(o){G("plugin.mcp-gateway.downstream-oauth"),dh(r)&&G("plugin.mcp-gateway.downstream-oauth.id-jag");for(let s of ah){let u=ph(s)?(p,h)=>lh(r,p,h):c;Xs(e,s,r.gateway,Ys(s.routeName,s.handler,u))}}if(a){G("plugin.mcp-gateway.upstream-auth");for(let s of r.connectionsById.values())G(`plugin.mcp-gateway.upstream-auth.${s.authMode}`);for(let s of ih)Xs(e,s,r.gateway,Ys(s.routeName,s.handler))}}n(ec,"registerMcpGatewayInternalRoutes");var Tn=class extends On{static{n(this,"McpGatewayPlugin")}#e;constructor(t={}){super(),G("plugin.mcp-gateway"),this.#e=$n(t)}registerRoutes(t){let r=t.parsedRouteData;r&&ec(t.router,{routes:r.routes,policies:r.policies,gateway:this.#e})}};var mh=new TextDecoder;function fh(e){if(e)try{return JSON.parse(mh.decode(e))}catch{return}}n(fh,"readBodyJson");function he(e){return e&&typeof e=="object"?e:void 0}n(he,"readRecord");function Tt(e,t){let r=he(e)?.[t];return typeof r=="string"?r:void 0}n(Tt,"readStringProperty");function rc(e,t){let r=he(e)?.[t];return typeof r=="number"?r:void 0}n(rc,"readNumberProperty");function tc(e,t){return rc(e,"code")??(t.status>=400?t.status:void 0)}n(tc,"readErrorCode");function nc(e){return Array.isArray(e)?e.map(nc).find(t=>t?.method):he(e)}n(nc,"readJsonRpcMessage");function oc(e){let t=nc(fh(e)),r=typeof t?.method=="string"?t.method:"",o=t?.params;switch(r){case"tools/list":return{mcpMethod:r,capabilityType:"tool"};case"tools/call":return{mcpMethod:r,capabilityType:"tool",capabilityName:Tt(o,"name")};case"prompts/list":return{mcpMethod:r,capabilityType:"prompt"};case"prompts/get":return{mcpMethod:r,capabilityType:"prompt",capabilityName:Tt(o,"name")};case"resources/list":case"resources/templates/list":return{mcpMethod:r,capabilityType:"resource"};case"resources/read":{let a=Tt(o,"uri");return{mcpMethod:r,capabilityType:"resource",capabilityName:a,resourceUri:a}}default:return null}}n(oc,"buildBaseCapabilityInput");function ac(e){return e==="tools/list"||e==="prompts/list"||e==="resources/list"||e==="resources/templates/list"}n(ac,"isCapabilityListMethod");function hh(e,t,r){let i=he(r)?.[e==="resources/templates/list"?"resourceTemplates":t==="tool"?"tools":t==="prompt"?"prompts":"resources"];return Array.isArray(i)?i.length:void 0}n(hh,"readItemCount");async function gh(e){try{return await e.clone().json()}catch{return}}n(gh,"readResponseJson");function ic(e){let t=oc(e);return!t||ac(t.mcpMethod)?null:{eventType:C.MCP_CAPABILITY_INVOKED,outcome:"success",...t}}n(ic,"buildCapabilityInvokedAnalyticsInput");async function sc(e,t){let r=oc(e);if(!r)return null;let o=he(await gh(t)),a=he(o?.error),i=he(a?.data),c=o?.result,s=r.mcpMethod==="tools/call"&&he(c)?.isError===!0;if(he(i?.connectRequired))return{eventType:C.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",...r,httpStatusCode:t.status,reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required",errorCode:rc(a,"code"),mcpErrorType:Tt(a,"message")};if(ac(r.mcpMethod)){let u=t.status>=400?void 0:hh(r.mcpMethod,r.capabilityType,c);return{eventType:C.MCP_CAPABILITY_LISTED,outcome:t.status>=400||a?"failure":"success",...r,httpStatusCode:t.status,...t.status>=400||a?{reasonCode:"upstream_capability_list_failed",reasonClass:"upstream",errorType:"capability_list_error",errorCode:tc(a,t)}:{},...u===void 0?{}:{attributes:{itemCount:u}}}}return t.status>=400||a?{eventType:C.MCP_CAPABILITY_FAILED,outcome:"failure",...r,httpStatusCode:t.status,reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"capability_error",errorCode:tc(a,t),mcpErrorType:Tt(a,"message")}:{eventType:C.MCP_CAPABILITY_COMPLETED,outcome:s?"application_error":"success",...r,httpStatusCode:t.status,toolResultIsError:s,applicationError:s}}n(sc,"buildCapabilityFinalAnalyticsInput");var yh={Allow:"POST"};async function _h(e){try{return await e.clone().arrayBuffer()}catch{return}}n(_h,"readRequestBody");function cc(e){try{let t=co(e.route.path);return{virtualServerName:t.operationId,upstreamServerName:t.connection?.upstreamServerId,upstreamServerTitle:t.connection?.displayName,authProfileId:t.connection?.authProfileId,upstreamAuthMode:t.connection?.authMode}}catch{return{}}}n(cc,"readRouteAnalyticsFields");function dc(e){return Io(e.user,e.url,e.headers)?.subjectId}n(dc,"readRequestSubjectId");function wh(e){let t=ic(e.requestBody);t&&v(e.context,{...t,...cc(e.context),httpMethod:e.request.method,subjectId:dc(e.request),transport:"http"})}n(wh,"emitCapabilityInvokedAnalytics");async function Rh(e){let t=await sc(e.requestBody,e.response);t&&v(e.context,{...t,...cc(e.context),httpMethod:e.request.method,subjectId:dc(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}n(Rh,"emitCapabilityFinalAnalytics");async function bh(e,t){if(G("handler.mcp-gateway-proxy"),e.method==="GET")return xe.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},yh);let r=Date.now(),o=await _h(e);wh({context:t,request:e,requestBody:o});let a=await Nn(e,t);return await Rh({context:t,request:e,requestBody:o,response:a,startedAt:r}),a}n(bh,"McpProxyHandler");export{Rc as McpAuth0OAuthInboundPolicy,kr as McpCapabilityFilterInboundPolicy,uc as McpClerkOAuthInboundPolicy,lc as McpCognitoOAuthInboundPolicy,pc as McpEntraOAuthInboundPolicy,Tn as McpGatewayPlugin,mc as McpGoogleOAuthInboundPolicy,fc as McpKeycloakOAuthInboundPolicy,hc as McpLogtoOAuthInboundPolicy,bc as McpOAuthInboundPolicy,gc as McpOktaOAuthInboundPolicy,yc as McpOneLoginOAuthInboundPolicy,_c as McpPingOAuthInboundPolicy,bh as McpProxyHandler,nn as McpTokenExchangeInboundPolicy,wc as McpWorkosOAuthInboundPolicy};
|
|
48
|
+
></iframe>`}n(Ql,"renderUpstreamHtml");var ci="application/json",ep="application/x-www-form-urlencoded";function lr(e,t){return new f({message:e,extensionMembers:{[g]:"invalid_request"}},t===void 0?void 0:{cause:t})}n(lr,"invalidRequestError");function tp(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}n(tp,"normalizeContentType");function rp(e,t){return e===t?!0:t===ci&&e.endsWith("+json")}n(rp,"contentTypeMatches");function np(e,t){if(!t||t.length===0)return;let r=tp(e.headers.get("content-type"));if(!t.some(o=>rp(r,o)))throw lr(`Request body must be ${t.join(" or ")}.`)}n(np,"assertExpectedContentType");function op(e,t,r){let o=e.headers.get("content-length");if(!o)return;let a=Number.parseInt(o,10);if(Number.isFinite(a)&&a>t)throw lr(`${r} exceeded the maximum allowed size.`)}n(op,"assertContentLengthWithinLimit");async function di(e,t){let r=t.label??"Request body";np(e,t.expectedContentTypes),op(e,t.maxBytes,r);let o=await nr(e.body,{maxBytes:t.maxBytes,createLimitError:n(()=>lr(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(o)}n(di,"readBoundedTextBody");async function ui(e,t){let r=await di(e,{...t,expectedContentTypes:[ci]});try{return JSON.parse(r)}catch(o){throw lr("Request body must be valid JSON.",o)}}n(ui,"readBoundedJsonBody");async function li(e,t){let r=await di(e,{...t,expectedContentTypes:[ep]});return new URLSearchParams(r)}n(li,"readBoundedFormUrlEncodedBody");F();F();import{errors as mi,jwtVerify as fi,SignJWT as hi}from"jose";import{base64url as ap}from"jose";var ip="mcp-browser-login-pkce:",sp=new TextEncoder;async function cp(e){return crypto.subtle.importKey("raw",Z(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"])}n(cp,"importHmacKey");async function cn(e){let t=await cp(e.signingKey),r=sp.encode(`${ip}${e.stateId}`),o=await crypto.subtle.sign("HMAC",t,Z(r));return je.parse(ap.encode(new Uint8Array(o)))}n(cn,"deriveBrowserLoginPkceVerifier");async function pi(e){let t=await cn(e),r=await Kt(t);return{codeVerifier:t,codeChallenge:r,codeChallengeMethod:He}}n(pi,"deriveBrowserLoginPkceParams");var dp={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},m=class extends Error{static{n(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,o=dp[t],a){super(r,a),this.name="OAuthProtocolError",this.errorCode=t,this.status=o}};var up=300,lp=d.object({purpose:d.literal("gateway_browser_login"),transactionId:vr,stateId:Ar,exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),pp=d.object({purpose:d.literal("gateway_authorization_setup"),transactionId:vr,stateId:Ar,exp:d.number().int().positive(),iat:d.number().int().positive().optional()});async function xt(){return re({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ce(e,"browser-login"),"derive")})}n(xt,"getBrowserLoginKey");async function gi(){return re({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ce(e,"authorization-csrf"),"derive")})}n(gi,"getCsrfKey");function yi(e){return{now:e.now??new Date,ttlSeconds:_i()}}n(yi,"readPendingTransactionDependencies");function _i(){return B().browserLogin.stateTtlSeconds}n(_i,"readBrowserLoginStateTtlSeconds");function mp(e){let t=H();return $(e)&&t.isActionPath(e.pathname,"/oauth/dev-login")}n(mp,"isLoopbackDevLoginUrl");async function fp(e){let t=B().browserLogin,r=H(),o=new URL(Re("url")),a=new URL(r.actionPath("/oauth/callback"),Je(e.requestUrl,e.requestHeaders));if(mp(o))return o.searchParams.set("redirect_uri",a.toString()),o.searchParams.set("state",e.state),o;if(o.searchParams.set("response_type","code"),o.searchParams.set("client_id",Re("clientId")),o.searchParams.set("redirect_uri",a.toString()),o.searchParams.set("scope",t.scope),o.searchParams.set("state",e.state),o.searchParams.set("nonce",e.nonce),t.audience&&o.searchParams.set("audience",t.audience),t.pkce===He){let i=await pi({stateId:e.stateId,signingKey:await xt()});o.searchParams.set("code_challenge",i.codeChallenge),o.searchParams.set("code_challenge_method",i.codeChallengeMethod)}return o}n(fp,"buildBrowserLoginUrl");function hp(e,t){return e.subjectId===t.subjectId}n(hp,"principalsMatch");function wi(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}n(wi,"toPendingPrincipal");function Ri(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,operationId:e.transaction.operationId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:I(e.now),expiresAt:I(ce(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw w("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:wi(e.principal)}}n(Ri,"createTransactionRecord");async function bi(e){let{id:t,...r}=e.record,o=await b().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(o.kind){case"started":return o.transaction;case"already_exists":throw w("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new m("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new m("invalid_request","redirect_uri is not registered for the client.")}}n(bi,"startPendingTransaction");async function gp(e){return new hi({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:W,typ:"JWT"}).setIssuer(J).setAudience(K).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await xt())}n(gp,"signBrowserLoginState");async function Ii(e){return new hi({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:kr()}).setProtectedHeader({alg:W,typ:"JWT"}).setIssuer(J).setAudience(K).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await gi())}n(Ii,"signCsrfToken");async function dn(e){try{let{payload:t}=await fi(e,await xt(),{algorithms:[W],issuer:J,audience:K}),r=lp.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof mi.JWTExpired?w("oauth_state_expired","Browser login state has expired.",t):w("oauth_state_invalid","Browser login state could not be verified.",t)}}n(dn,"verifyBrowserLoginStateToken");async function pr(e){try{let{payload:t}=await fi(e,await gi(),{algorithms:[W],issuer:J,audience:K});return{transactionId:pp.parse(t).transactionId}}catch(t){throw t instanceof mi.JWTExpired?w("oauth_state_expired","Authorization setup state has expired.",t):w("oauth_state_invalid","Authorization setup state could not be verified.",t)}}n(pr,"verifyCsrfToken");function un(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}n(un,"pendingStateErrorCode");function yp(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}n(yp,"toPendingAuthorizationGetResult");function _p(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}n(_p,"toPendingAuthorizationAdvanceResult");function ln(e){return e==="principal_mismatch"?"oauth_callback_mismatch":un(e==="consumed_already"?"consumed_already":e)}n(ln,"setupDecisionErrorCode");async function Ci(e){let t=e.now??new Date,r=await pr(e.csrfToken),o=await b().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await x(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:I(t)});if(o.kind!=="marked")throw w(ln(o.kind),"Authorization setup state is invalid, expired, or already used.");return Si({kind:"available",record:o.transaction})}n(Ci,"markSetupApproved");function Si(e){if(e.kind!=="available")throw w(un(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw w("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}n(Si,"requireAwaitingSetup");function wp(e){if(!hp(e.currentBrowserPrincipal,e.transaction.principal))throw w("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}n(wp,"requireCurrentPrincipalMatches");async function vi(e){let t=e.now??new Date,r=_i(),o=xr(),a=kr(),i=await gp({transactionId:o,stateId:a,ttlSeconds:r}),c=Ri({id:o,transaction:e.transaction,currentStateHash:await x(i),phase:"awaiting_login",now:t,ttlSeconds:r});if(c.phase!=="awaiting_login")throw w("oauth_state_invalid","Authorization transaction did not start in login phase.");let s=await bi({record:c,client:e.transaction.client});if(s.phase!=="awaiting_login")throw w("oauth_state_invalid","Authorization transaction did not start in login phase.");let u=await fp({state:i,nonce:a,stateId:a,requestUrl:e.requestUrl,...e.requestHeaders===void 0?{}:{requestHeaders:e.requestHeaders}});return{transaction:s,browserLoginStateToken:i,browserLoginUrl:u}}n(vi,"startAwaitingLogin");async function Ai(e){let{now:t,ttlSeconds:r}=yi(e),o=xr(),a=await Ii({transactionId:o,ttlSeconds:r}),i=Ri({id:o,transaction:e.transaction,currentStateHash:await x(a),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw w("oauth_state_invalid","Authorization transaction did not start in setup phase.");let c=await bi({record:i,client:e.transaction.client});if(c.phase!=="awaiting_setup")throw w("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:c,csrfToken:a}}n(Ai,"startAwaitingSetup");async function xi(e){let{now:t,ttlSeconds:r}=yi(e),o=await dn(e.browserLoginStateToken),a=await Ii({transactionId:o.transactionId,ttlSeconds:r}),i=_p(await b().advancePendingAuthorization({transactionId:o.transactionId,expectedPhase:"awaiting_login",currentStateHash:await x(e.browserLoginStateToken),nextStateHash:await x(a),nextPhase:"awaiting_setup",principal:wi(e.principal),now:I(t)}));if(i.kind!=="advanced")throw w(un(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw w("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:a}}n(xi,"completeLogin");async function ki(e){let t=await pn(e);return wp({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}n(ki,"getSetup");async function pn(e){let t=e.now??new Date,r=await pr(e.csrfToken);return Si(yp(await b().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await x(e.csrfToken),now:I(t)})))}n(pn,"getSetupTransaction");async function Rp(e){let t=await pr(e.csrfToken),r=le(),o=I(ce(e.now,up)),a=await b().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await x(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await x(r),authorizationCodeExpiresAt:o,grantId:Ro(),now:I(e.now)});if(a.kind!=="approved")throw w(a.kind==="cancelled"?"oauth_state_invalid":ln(a.kind),"Authorization setup state is invalid, expired, or already used.");let i=new URL(a.transaction.redirectUri);return i.searchParams.set("code",r),a.transaction.clientState&&i.searchParams.set("state",a.transaction.clientState),i}n(Rp,"createAuthorizationCodeRedirectWithDecision");async function bp(e){let t=await pr(e.csrfToken),r=await b().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await x(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:I(e.now)});if(r.kind!=="cancelled")throw w(r.kind==="approved"?"oauth_state_invalid":ln(r.kind),"Authorization setup state is invalid, expired, or already used.");return Ip({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}n(bp,"createCancelRedirectWithDecision");function Ip(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),t}n(Ip,"buildClientCancelRedirect");async function Ti(e){let t=e.now??new Date;return Rp({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Ti,"approve");async function Ui(e){let t=e.now??new Date;return bp({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Ui,"cancel");F();import{createRemoteJWKSet as Cp,errors as tt,jwtVerify as Pi,SignJWT as Sp}from"jose";var hn="zuplo_mcp_session",vp=d.object({purpose:d.literal("gateway_browser_session"),sub:it,browserLoginOrigin:d.string().min(1),roles:d.array(d.string().min(1)).optional(),exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),Ap=d.object({id_token:d.string().min(1),token_type:d.string().min(1).optional(),expires_in:d.number().optional(),access_token:d.string().min(1).optional(),refresh_token:d.string().min(1).optional(),scope:d.string().min(1).optional()}),xp=d.object({error:d.string().min(1).optional(),error_description:d.string().min(1).optional(),error_uri:d.string().min(1).optional()}),kp=d.object({sub:it,nonce:d.string().min(1)}).catchall(d.unknown()),mn;function Tp(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let o=r.indexOf("=");if(o<0)continue;let a=r.slice(0,o).trim(),i=r.slice(o+1).trim();if(a)try{t.set(a,decodeURIComponent(i))}catch{t.set(a,i)}}return t}n(Tp,"parseCookieHeader");async function Ei(){return re({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ce(e,"browser-session"),"derive")})}n(Ei,"getBrowserSessionKey");function fn(e,t){let r=new URL(P(e,t)),o=[`${hn}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return r.protocol==="https:"&&o.push("Secure"),o.join("; ")}n(fn,"buildBrowserSessionEvictionCookie");function Up(e){let t=new URL(P(e.requestUrl,e.requestHeaders)),r=[`${hn}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(Up,"serializeSessionCookie");function Oi(){return new URL(Re("url")).origin}n(Oi,"readBrowserLoginOrigin");function Pp(e){let t=xp.safeParse(e);if(!t.success)return{};let r={};return t.data.error!==void 0&&(r.idpError=t.data.error),t.data.error_description!==void 0&&(r.idpErrorDescription=t.data.error_description.slice(0,256)),t.data.error_uri!==void 0&&(r.idpErrorUri=t.data.error_uri.slice(0,256)),r}n(Pp,"readIdpErrorFields");function Ep(e){return e instanceof tt.JWTExpired?"expired":e instanceof tt.JWTClaimValidationFailed?"claim":e instanceof tt.JWSSignatureVerificationFailed?"signature":e instanceof tt.JWKSNoMatchingKey?"jwks_no_match":e instanceof tt.JWTInvalid?"invalid":e instanceof d.ZodError?"schema":"other"}n(Ep,"readJwtFailureKind");function Op(e){return e instanceof Error&&"cause"in e?e.cause:e}n(Op,"readErrorCause");function qp(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}n(qp,"readRuntimeGatewayCode");function Mp(){if(!mn){let e=B();mn=Cp(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return mn}n(Mp,"readFederatedJwks");function qi(e){if(!e.user)throw w("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return Te(e.user,e.url)}n(qi,"resolveCurrentRequestPrincipal");async function mr(e,t={}){let r=Tp(e.headers.get("cookie")).get(hn);if(!r)return{};try{let{payload:o}=await Pi(r,await Ei(),{algorithms:[W],issuer:J,audience:K}),a=vp.parse(o);if(a.browserLoginOrigin!==Oi())return{evictCookie:fn(e.url,e.headers)};let i={subjectId:a.sub};return a.roles&&a.roles.length>0&&(i.roles=a.roles),{principal:i}}catch(o){return o instanceof tt.JWTExpired?{evictCookie:fn(e.url,e.headers)}:(t.context?.log.warn({event:"browser_session_verification_failed",errorName:o instanceof Error?o.name:"unknown",errorMessage:o instanceof Error?o.message:"verification failed"},"Browser session JWT verification failed"),{evictCookie:fn(e.url,e.headers)})}}n(mr,"readBrowserSession");async function fr(e){let t=B().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:Oi()};e.principal.roles&&(r.roles=e.principal.roles);let o=await new Sp(r).setProtectedHeader({alg:W,typ:"JWT"}).setIssuer(J).setAudience(K).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await Ei());return Up({value:o,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t})}n(fr,"createBrowserSessionCookie");async function Dp(e){let t=B(),r=Re("tokenUrl"),o=Re("clientId"),a=Re("clientSecret"),i=new URL(H().actionPath("/oauth/callback"),Je(e.requestUrl,e.requestHeaders)).toString(),c=new URLSearchParams({grant_type:"authorization_code",code:e.code,redirect_uri:i,client_id:o,client_secret:a});if(t.browserLogin.pkce===He){let s=await cn({stateId:e.stateId,signingKey:await xt()});c.set("code_verifier",s)}try{let{response:s,json:u}=await or(r,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:c},{maxResponseBytes:32768,problemCode:"browser_login_verification_failed",timeoutMs:t.browserLogin.remoteTimeoutMs,context:e.context});if(!s.ok){let R=Pp(u);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:T(r),idpStatus:s.status,...R},"Federated browser login token exchange returned non-2xx from the identity provider"),w({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${s.status}${R.idpError?` idp_error=${R.idpError}`:""}${R.idpErrorDescription?` idp_error_description=${R.idpErrorDescription}`:""})`)})}let p=Ap.parse(u),h;try{({payload:h}=await Pi(p.id_token,Mp(),{issuer:t.oidc.issuer,audience:o}))}catch(R){let q={};throw L(q,"error",R),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:Ep(R),idpHost:T(r),expectedIssuer:t.oidc.issuer,...q},"Federated id_token failed jose verification"),R}if(h.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:T(r),nonceMissingFromIdToken:h.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),w("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let y=kp.parse(h);return{principal:Te({sub:y.sub,data:y},e.requestUrl),subjectToken:{token:p.id_token,tokenType:ct,expiresAt:typeof h.exp=="number"?I(new Date(h.exp*1e3)):void 0}}}catch(s){let u=se(s)??qp(s);throw u!==void 0&&u!=="browser_login_verification_failed"?s:w("browser_login_verification_failed","Federated browser login callback could not be verified.",Op(s))}}n(Dp,"exchangeFederatedAuthorizationCode");async function Mi(e){let t=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(t)return Dp({code:t,nonce:e.stateId,stateId:e.stateId,requestUrl:e.request.url,requestHeaders:e.request.headers,context:e.context});let r=await mr(e.request,{context:e.context});if(r.principal)return{principal:r.principal};throw w("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.")}n(Mi,"resolveBrowserLoginCallbackIdentity");F();var zp=new Set(["about","blob","data","file","ftp","ftps","javascript","mailto","urn","ws","wss"]);function Hp(e){return e.protocol.replace(/:$/u,"").toLowerCase()}n(Hp,"readScheme");function jp(e){return e.protocol==="https:"}n(jp,"isSpecCompliantRedirectUri");function Bp(e){let t=Hp(e);return t.length>0&&t!=="http"&&t!=="https"&&!zp.has(t)}n(Bp,"isNativeAppCustomSchemeRedirectUri");var zi=[{id:"oauth.redirect_uri.https",mode:"strict",accepts:n(e=>jp(e),"accepts")},{id:"oauth.redirect_uri.loopback_http",mode:"native_app",accepts:n(e=>$(e),"accepts"),matches:n((e,t)=>$(e)&&$(t)&&e.pathname===t.pathname&&e.search===t.search,"matches")},{id:"oauth.redirect_uri.custom_scheme",mode:"native_app",accepts:n(e=>Bp(e),"accepts")}];function Hi(e){let t=zi.find(r=>r.accepts(e.url));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}n(Hi,"evaluateBuiltInRedirectUriCompatibility");function Di(e){try{return new URL(e)}catch{return}}n(Di,"parseUrl");function ji(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=Di(e.registeredRedirectUri),r=Di(e.requestedRedirectUri);return t===void 0||r===void 0?!1:zi.some(o=>o.matches?.(t,r))}n(ji,"redirectUriMatchesBuiltInCompatibility");var Lp=1e4,Np=5*1024,Jp=0,Gp=2160*60*60,Bi=["authorization_code","refresh_token",Jt,be],Fp=["authorization_code","refresh_token"],Li=[yo],$p=["code"],Zp=d.object({client_name:d.string().min(1).optional(),redirect_uris:d.array(d.string().min(1)).min(1),grant_types:d.array(d.enum(Bi)).min(1).max(Bi.length).optional(),authorization_grant_profiles_supported:d.array(d.enum(Li)).min(1).max(Li.length).optional(),response_types:d.array(d.enum($p)).min(1).max(1).optional(),scope:d.literal(E).optional(),token_endpoint_auth_method:wo.optional(),jwks_uri:d.string().min(1).optional()});function Kp(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&$(t))&&t.pathname!=="/"}catch{return!1}}n(Kp,"isCimdClientIdCandidate");function Ni(e,t){throw new m("invalid_client",ko({clientId:e})??"OAuth client is not registered.",void 0,t===void 0?void 0:{cause:t})}n(Ni,"invalidCimdClientError");function rt(e,t="invalid_request"){if(Wp(e))throw new m(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new m(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new m(t,"redirect_uris must not include credentials or fragments.");if(Hi({url:r}).kind==="rejected")throw new m(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}n(rt,"assertValidRedirectUri");function Wp(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}n(Wp,"hasForbiddenRawRedirectUriCharacter");async function Vp(e){let{response:t,json:r}=await ia(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:Jp,maxResponseBytes:Np,timeoutMs:Lp});if(!t.ok)throw w("invalid_request","CIMD metadata could not be fetched.");let o=Ft(r);for(let a of o.redirect_uris)rt(a,"invalid_request");if(o.jwks_uri!==void 0&&ut(o.jwks_uri),o.client_id!==e.clientId)throw w("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return o}n(Vp,"fetchCimdMetadata");async function Yp(e){let t=$t(e),r=await Vp({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}n(Yp,"resolveCimdClient");async function hr(e,t){let r=ue.parse(e);if(Kp(r)){B().gateway.downstreamCimdEnabled||Ni(r);try{return await Yp(r)}catch(a){Ni(r,a)}}let o=await b().readClient({clientId:r});if(o.kind==="found"){let a=o.client,i=Uo(a.clientId),c=i===void 0?a.tokenEndpointAuthMethod:"private_key_jwt",s=a.jwksUri??i;if(c==="private_key_jwt"&&s===void 0)throw new m("invalid_client","Dynamic private_key_jwt client is missing JWKS metadata. Re-run client registration before authorization.");let u=Ft({client_id:a.clientId,client_name:a.clientName,redirect_uris:a.redirectUris,token_endpoint_auth_method:c,...s===void 0?{}:{jwks_uri:s}}),p={kind:"dcr",clientId:r,metadata:u};return a.hashedClientSecret&&(p.hashedClientSecret=a.hashedClientSecret),p}throw new m("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}n(hr,"resolveClient");function Ji(e,t){if(!e.metadata.redirect_uris.some(r=>ji({registeredRedirectUri:r,requestedRedirectUri:t})))throw w("invalid_request","redirect_uri is not registered for the client.")}n(Ji,"assertRedirectRegistered");function Xp(e){return e===void 0?[...Fp]:Array.from(new Set(e))}n(Xp,"normalizeGrantTypes");function Qp(e){try{ut(e)}catch(t){throw new m("invalid_client_metadata","jwks_uri must be an HTTPS URL with a path, no credentials or fragment, and must not point at a blocked host.",void 0,{cause:t})}}n(Qp,"assertValidDcrJwksUri");function em(e){return e.tokenEndpointAuthMethod==="private_key_jwt"&&e.jwksUri!==void 0?ue.parse(To({clientId:crypto.randomUUID(),jwksUri:e.jwksUri})):ue.parse(`dcr:${crypto.randomUUID()}`)}n(em,"createDcrClientId");function nt(e){if(e===void 0||e===E)return E;throw new m("invalid_request",`Only the ${E} scope is supported.`)}n(nt,"assertSupportedOAuthScope");function Me(e,t,r){let o;try{o=new URL(t)}catch{throw new m("invalid_target","resource must be an absolute URI.")}if(o.hash)throw new m("invalid_target","resource must not include a fragment.");if(o.protocol!=="https:"&&!$(o))throw new m("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let a=P(e,r),i=ho(),c=i?[...i.byOperationId.values()].find(s=>new URL(s.routePath,a).toString()===t):void 0;if(!c)throw new m("invalid_target","resource must match a published MCP route.");return c}n(Me,"resolveResource");async function Gi(e){let t;try{t=Zp.parse(e)}catch(R){if(R instanceof d.ZodError){let q=R.issues.some(O=>O.path[0]==="redirect_uris");throw new m(q?"invalid_redirect_uri":"invalid_client_metadata",R.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:R})}throw R}for(let R of t.redirect_uris)rt(R,"invalid_redirect_uri");if(t.token_endpoint_auth_method==="private_key_jwt"&&t.jwks_uri===void 0)throw new m("invalid_client_metadata","jwks_uri is required for private_key_jwt clients.");t.jwks_uri!==void 0&&Qp(t.jwks_uri);let r=new Date,o=t.token_endpoint_auth_method??"none",a=o==="private_key_jwt"?"none":o,i=em({tokenEndpointAuthMethod:o,jwksUri:t.jwks_uri}),c=Ft({client_id:i,client_name:t.client_name??"Dynamically registered MCP client",redirect_uris:t.redirect_uris,token_endpoint_auth_method:o,...t.jwks_uri===void 0?{}:{jwks_uri:t.jwks_uri}}),s=ce(r,Gp),u=Math.floor(r.getTime()/1e3),p=Math.floor(s.getTime()/1e3),h={client_id:c.client_id,client_name:c.client_name,redirect_uris:c.redirect_uris,grant_types:Xp(t.grant_types),authorization_grant_profiles_supported:t.authorization_grant_profiles_supported,response_types:["code"],scope:E,token_endpoint_auth_method:c.token_endpoint_auth_method,client_id_issued_at:u,jwks_uri:c.jwks_uri},y={clientId:c.client_id,clientName:c.client_name,redirectUris:c.redirect_uris,tokenEndpointAuthMethod:a,createdAt:I(r),clientExpiresAt:I(s)};if(o==="client_secret_basic"||o==="client_secret_post"){let R=le();y.hashedClientSecret=await x(R),y.clientSecretExpiresAt=I(s),h.client_secret=R,h.client_secret_expires_at=p,h.client_secret_issued_at=u}if((await b().registerClient(y)).kind==="already_exists")throw w("invalid_request","OAuth client is already registered.");return h}n(Gi,"registerDownstreamClient");function tm(e){return e?.metadata?.idpSubjectTokenType!==Ge&&e?.metadata?.idpSubjectTokenExpiresAt!==void 0&&new Date(e.metadata.idpSubjectTokenExpiresAt).getTime()<=Date.now()?!1:e?.status==="active"&&e.metadata?.encryptedIdpSubjectToken!==void 0&&e.metadata.idpSubjectTokenType!==void 0}n(tm,"hasStoredIdJagSubjectTokenBinding");async function Fi(e){let t=Ne(e.principal.subjectId);return(await b().batchGetUpstreamConnections([{owner:t,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId}]))[0]}n(Fi,"readIdJagSubjectConnection");async function gn(e){let t=X().byOperationId.get(e.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag")return!1;let r=await Fi({connection:t.connection,principal:e.principal});return!tm(r)}n(gn,"requiresIdJagSubjectTokenBinding");async function $i(e){if(e.subjectToken===void 0)return;let t=X().byOperationId.get(e.transaction.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag"||e.principal.subjectId!==e.transaction.principal.subjectId)return;let r=await Fi({connection:t.connection,principal:e.principal});return b().upsertUpstreamConnection({id:r?.id??Zt(),ownerMode:"user",subjectId:e.transaction.principal.subjectId,upstreamServerId:t.connection.upstreamServerId,authProfileId:t.connection.authProfileId,status:"active",encryptedAccessToken:r?.encryptedAccessToken,encryptedRefreshToken:r?.encryptedRefreshToken,scopes:r?.scopes??[],expiresAt:r?.expiresAt,metadata:{...r?.metadata??{},encryptedIdpSubjectToken:await me(e.subjectToken.token),idpSubjectTokenType:e.subjectToken.tokenType,idpSubjectTokenExpiresAt:e.subjectToken.expiresAt}})}n($i,"bindIdJagSubjectTokenForAuthorizationTransaction");function gr(e){return S`<img class="card__icon" src="${e.iconHref}" alt="" width="48" height="48" referrerpolicy="no-referrer" onerror=" this.onerror = null; this.src = '${e.fallbackIconHref}'; " />`}n(gr,"renderShellIcon");function Zi(e){return S`<form class="actions" method="post" action="${e.setupAction}" ${e.submitOnceAttrs}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate >Cancel</button><button class="button button--primary" type="submit" name="decision" value="approve" ${e.authorizeAttrs} >Authorize</button></form>`}n(Zi,"renderActions");var Ki=fe('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="4.6" x2="8" y2="8.4"/><circle cx="8" cy="11" r=".7" fill="currentColor" stroke="none"/></svg>');function Wi(e){return S`<div class="banner banner--warning" role="status"><span class="banner__icon" aria-hidden="true">${e.icon}</span><div class="banner__body"><p class="banner__title">Setup required</p><p class="banner__message">${e.message}</p></div></div>`}n(Wi,"renderBannerWarning");var BR=fe('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),LR=fe('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>');var NR=fe('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var rm="data:,",Vi=S`data-submit-once="true" onsubmit="if (this.dataset.submitted === 'true') return false; this.dataset.submitted = 'true'; setTimeout(() => this.querySelectorAll('button').forEach((button) => { button.disabled = true; }), 0);"`,Yi=S`data-activate-once="true" onclick="if (this.dataset.activated === 'true') return false; this.dataset.activated = 'true'; this.setAttribute('aria-disabled', 'true'); this.style.pointerEvents = 'none';"`;function nm(e,t,r){if(e)try{let o=new URL(t).origin,a=new URL(e,o);return a.origin!==o||!a.pathname.startsWith(r.actionPath("/auth/connections/"))?void 0:a.toString()}catch{return}}n(nm,"safeGatewayConnectHref");function om(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}n(om,"deriveMode");function am(e){return Zi({state:e.state,setupAction:e.gateway.actionPath("/oauth/setup"),submitOnceAttrs:Vi,authorizeAttrs:Q})}n(am,"renderActions");function yn(e,t,r,o){for(let a of e){if(a.ownerMode!=="user"||a.status!==r)continue;let i=nm(a.connectUrl,t,o);if(i)return i}}n(yn,"firstUserConnectHref");function im(e){let t=e.connectHref===void 0?Q:S`<a class="button button--primary" href="${e.connectHref}" ${Yi}>Connect</a>`;return S`<form class="actions" method="post" action="${e.gateway.actionPath("/oauth/setup")}" ${Vi}><input type="hidden" name="state" value="${e.state}" /><button class="button button--secondary" type="submit" name="decision" value="cancel" formnovalidate>Cancel</button>${t}</form>`}n(im,"renderSetupActions");function sm(e){return e?S`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${Yi}>Re-connect<span class="tooltip" tabindex="0" aria-label="Reset or change how the gateway connects to the upstream service, including changing scopes.">?</span></a></span>`:Q}n(sm,"renderReconnectAction");function cm(e){try{let t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?!0:t.protocol==="data:"&&/^data:image\/(?:png|jpe?g|webp|svg\+xml);/i.test(e)}catch{return!1}}n(cm,"isRenderableIconHref");function Xi(e){return e?.find(t=>cm(t.src))?.src}n(Xi,"readIconHref");function dm(e){return Xi(e.serverIcons)??(e.transportHost===void 0?void 0:$r(e.transportHost).src)}n(dm,"readUpstreamIconHref");function um(e){let t=Xi(e.routeIcons);if(t!==void 0)return t;for(let r of e.upstreams){let o=dm(r);if(o!==void 0)return o}}n(um,"readHeaderIconHref");function lm(e){let t=e.setupMessage===void 0?Q:Wi({icon:Ki,message:e.setupMessage});return S`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>${t}`}n(lm,"renderBody");function _n(e){let t=om(e.upstreams),r=yn(e.upstreams,e.gatewayOrigin,"not_connected",e.gateway),o=yn(e.upstreams,e.gatewayOrigin,"reconsent_required",e.gateway),a=yn(e.upstreams,e.gatewayOrigin,"active",e.gateway),i=t==="setup"?r??o:void 0,c=t==="setup"?e.upstreams.find(p=>p.ownerMode==="user"&&p.status!=="active"&&p.connectUrl===void 0&&p.setupMessage!==void 0)?.setupMessage:void 0,s=um({routeIcons:e.routeIcons,upstreams:e.upstreams}),u=t==="setup"?S`<footer class="card__footer">${im({state:e.state,connectHref:i,gateway:e.gateway})}</footer>`:S`<footer class="card__footer">${sm(a)}${am({state:e.state,gateway:e.gateway})}</footer>`;return Ye(Qe({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:s??rm,styles:Xe,headerIcon:s===void 0?Q:gr({iconHref:s,fallbackIconHref:er}),heading:"Authorize access",subhead:Q,body:lm({routeDisplayName:e.routeDisplayName,clientDisplayName:e.clientDisplayName,setupMessage:c}),footer:u}))}n(_n,"renderConsentPage");var pm=1e4,Qi="mcp-session-id",mm;function os(){return{tools:[],prompts:[],resources:[]}}n(os,"emptyCapabilities");function es(){return new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":Tr})}n(es,"buildReadinessHeaders");async function ts(e){if(e.type==="bearer_token"){let o=es();return o.set("authorization",`Bearer ${e.token}`),o}let t=await e.provider.tokens();if(!t)return;let r=es();return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}n(ts,"buildAsyncCredentialHeaders");function rs(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(Lt.parse({jsonrpc:Bt,id:1,method:"initialize",params:{protocolVersion:Tr,capabilities:{},clientInfo:{name:"zuplo-mcp-gateway-readiness",version:"0.0.0"}}}))})}n(rs,"buildInitializePreflight");async function wn(e){dt(e.url);let t=new AbortController,r=setTimeout(()=>t.abort(),pm);try{let o=new Request(e,{redirect:"manual",signal:t.signal});return await qt.fetch(o)}finally{clearTimeout(r)}}n(wn,"runPreflight");function Rn(e){e.body?.cancel().catch(()=>{})}n(Rn,"releasePreflightBody");async function fm(e){let t=e.response.headers.get(Qi);if(!t)return;let r=new Headers(e.headers);r.set(Qi,t),r.delete("content-type");try{let o=await wn(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));Rn(o)}catch{}}n(fm,"terminatePreflightSession");async function as(e){let{response:t}=e;return Rn(t),t.status>=200&&t.status<300?(await fm(e),{kind:"ready",upstreamStatus:t.status,capabilities:os()}):t.status===401||t.status===403?{kind:"upstream_auth_rejected",status:t.status,message:"Upstream MCP server rejected the configured credential."}:{kind:"upstream_unavailable",status:t.status,message:"Upstream MCP server did not accept the readiness preflight."}}n(as,"classifyResponse");function ns(e){let t={status:e.state==="reconsent_required"?"reconsent_required":"not_connected",connected:!1};return e.nextAction==="admin_setup_required"?{kind:"admin_setup_required",payload:e,connectionStatus:t}:{kind:"connect_required",payload:e,connectionStatus:t}}n(ns,"connectRequiredResult");async function hm(e){try{return as({response:await wn(e.request),upstreamUrl:e.upstreamUrl,headers:e.headers})}catch(t){return{kind:"upstream_unavailable",message:t instanceof Error?t.message:"Upstream MCP server readiness preflight failed."}}}n(hm,"classifyPreflight");async function gm(e){let t=e.route.connection;if(t===void 0)return{kind:"ready",upstreamStatus:204,capabilities:os()};let r=dr(t.upstreamServerId,e.route.operationId),o=Ve(r,e.subjectId),a=e.returnTo===void 0?o:{...o,returnTo:e.returnTo},i=new Request(e.requestUrl,{headers:e.requestHeaders}),c=await We({request:i,routeAuth:a,preloadedConnection:e.preloadedConnection});if(c.kind==="connect_required")return ns(c.payload);let s=await ts(c.credential);if(s===void 0)return{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens."};let u=rs({upstreamUrl:t.mcpUrl,headers:s}),p;try{p=await wn(u)}catch(U){return{kind:"upstream_unavailable",message:U instanceof Error?U.message:"Upstream MCP server readiness preflight failed."}}if(p.status!==401)return as({response:p,upstreamUrl:t.mcpUrl,headers:s});Rn(p);let h=await We({request:i,routeAuth:a,forceRefresh:!0,preloadedConnection:e.preloadedConnection});if(h.kind==="connect_required")return ns(h.payload);let y=await ts(h.credential);return y===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:hm({request:rs({upstreamUrl:t.mcpUrl,headers:y}),upstreamUrl:t.mcpUrl,headers:y})}n(gm,"checkUpstreamRouteReadinessImpl");function is(e){return(mm??gm)(e)}n(is,"checkUpstreamRouteReadiness");function ym(e){try{return new URL(e).host}catch{return}}n(ym,"safeUrlHost");function ss(e){return e!==void 0&&e.length>0}n(ss,"hasItems");function _m(e){let t=e.serverInfo?.icons;if(ss(t))return t;let r=tr(e.mcpUrl);return r===void 0?void 0:[r]}n(_m,"readServerIcons");async function wm(e){let{authConfig:t,authMode:r,description:o,displayName:a,mcpUrl:i,ownerMode:c,upstreamServerId:s,authProfileId:u}=e.registeredConnection,p=c==="user",h=p&&r!=="id-jag",y=e.readiness??(p?qo(e.connection):{connected:!0,status:"active"}),U=h?e.readiness?.connectUrl??(e.returnTo!==void 0?await Wr({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:s,authProfileId:u,operationId:e.route.operationId,returnTo:e.returnTo}):void 0):void 0,R=t.mode==="id-jag"?t.idJag.scopes:t.oauth.scopes;return{upstreamServerId:s,authProfileId:u,authMode:r,ownerMode:c,upstreamDisplayName:a,description:o,transportHost:ym(i),scopesRequested:ss(R)?R:void 0,serverIcons:_m(e.registeredConnection),status:y.status,connected:y.connected,capabilities:{tools:[],prompts:[],resources:[]},connectUrl:U,setupMessage:e.setupMessage,updatedAt:p&&"updatedAt"in y&&y.updatedAt!==void 0?y.updatedAt:void 0,expiresAt:e.readiness?.expiresAt??e.connection?.expiresAt}}n(wm,"buildSetupRequirement");function cs(e){let t=X().byOperationId.get(e);if(!t)throw w("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}n(cs,"requireRoute");async function bn(e){let t=cs(e.transaction.operationId),r=Ne(e.transaction.principal.subjectId),o=t.connection;if(o===void 0)return[];let i=o.ownerMode==="user"?(await b().batchGetUpstreamConnections([{owner:r,upstreamServerId:o.upstreamServerId,authProfileId:o.authProfileId}]))[0]:void 0,c=await is({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,route:t,subjectId:e.transaction.principal.subjectId,preloadedConnection:i,returnTo:e.returnTo}),s="connectionStatus"in c?c.connectionStatus:void 0,u=(c.kind==="connect_required"||c.kind==="admin_setup_required")&&c.payload.authUrl!==void 0?c.payload.authUrl:void 0,p=c.kind==="admin_setup_required"?c.payload.message:void 0;return[await wm({connection:i,registeredConnection:o,route:t,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:e.returnTo,transaction:e.transaction,userOwner:r,setupMessage:p,readiness:s===void 0?void 0:{...s,connectUrl:u}})]}n(bn,"requirementsForSetup");async function In(e){let t=cs(e.transaction.operationId),r=await b().readClient({clientId:e.transaction.clientId}),o=r.kind==="found"?r.client:void 0,a={gatewayOrigin:P(e.requestUrl,e.requestHeaders),routeDisplayName:t.connection?.displayName??t.operationId,clientDisplayName:o?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},i=t.connection?.description;return i!==void 0&&(a.routeDescription=i),a}n(In,"consentContext");function Cn(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}n(Cn,"hasUnresolvedUserUpstream");var Rm=["mcp_user"],bm="dev-browser-user",Im=["resource is required for /oauth/authorize.","MCP clients should start at the MCP server URL and follow its WWW-Authenticate resource_metadata link.","If your client reached this endpoint directly, use /oauth/authorize/{routePath} where {routePath} is the published MCP route path without a leading slash and each segment is URL-encoded as needed, for example /oauth/authorize/mcp/linear, or add resource={protected resource URI from protected-resource metadata}."].join(" "),Cm=d.object({response_type:d.literal("code"),client_id:d.string().min(1),redirect_uri:d.string().min(1),resource:d.url(),code_challenge:d.string().min(43),code_challenge_method:Yn,state:d.string().min(1).optional(),scope:d.literal(E).default(E)}),Sm=d.enum(["continue","approve","cancel"]).default("continue"),vm=d.object({state:d.string().min(1),decision:Sm}),Ae=class extends Error{static{n(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription}};function ds(e){return typeof e=="string"&&e.length>0?e:void 0}n(ds,"readQueryString");function Am(e,t){let r=ds(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new m("invalid_target",Im)}let o=So(t,e.url,e.headers);if(r===void 0||r===o)return o;throw new m("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}n(Am,"requireAuthorizeResource");async function xm(e,t){let r={};t!==void 0&&(r.context=t);let o=await mr(e,r);if(o.principal)return{principal:o.principal};if(!e.user)return o.evictCookie===void 0?{}:{setCookie:o.evictCookie};let a=qi(e);return{principal:a,setCookie:await fr({principal:a,requestUrl:e.url,requestHeaders:e.headers})}}n(xm,"resolveBrowserPrincipal");async function km(e,t){let r={};t!==void 0&&(r.context=t);let o=await mr(e,r);if(!o.principal)throw w("authentication_required","Authorization setup requires a current browser session.");return o.principal}n(km,"requireSetupPrincipal");function us(e){return`${H().actionPath("/oauth/setup")}?state=${encodeURIComponent(e)}`}n(us,"buildSetupReturnTo");async function ls(e){let t=await bn({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:us(e.csrfToken)}),r=await In({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders}),o={kind:"setup_page",html:_n({state:e.csrfToken,operationId:e.transaction.operationId,gateway:H(),upstreams:t,...r})};return e.setCookie!==void 0&&(o.setCookie=e.setCookie),o}n(ls,"renderSetup");function Tm(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}n(Tm,"toAuthorizationTransactionClient");async function Sn(e,t={}){let r=Cm.parse({...e.query,resource:Am(e,t.operationId),state:ds(e.query.state)}),o=nt(r.scope);rt(r.redirect_uri,"invalid_request");let a=new Date,i=ue.parse(r.client_id),c=await hr(r.client_id,a);Ji(c,r.redirect_uri);try{let s=Me(e.url,r.resource,e.headers),u=Tm(c);t.context?.log.info({event:"oauth_authorize_request_parsed",clientId:i,operationId:s.operationId,scope:o,hasClientState:r.state!==void 0},"Downstream OAuth authorize: request parsed and client resolved"),t.context&&v(t.context,{eventType:C.MCP_OAUTH_AUTHORIZE_STARTED,outcome:"success",virtualServerName:s.operationId,attributes:{clientId:i,scope:o,responseType:r.response_type}});let p={clientId:c?.clientId??i,...u===void 0?{}:{client:u},redirectUri:r.redirect_uri,resource:r.resource,operationId:s.operationId,scope:o,codeChallenge:r.code_challenge,codeChallengeMethod:r.code_challenge_method,...r.state===void 0?{}:{clientState:r.state}},{principal:h,setCookie:y}=await xm(e,t.context),U=h===void 0?!1:await gn({operationId:s.operationId,principal:h});if(!h||U){let q=await vi({transaction:p,requestUrl:e.url,requestHeaders:e.headers,now:a});t.context?.log.info({event:"oauth_authorize_awaiting_login",clientId:i,operationId:s.operationId,reason:h?"id_jag_subject_binding_missing":"no_browser_session"},"Downstream OAuth authorize: redirecting to browser login");let O={kind:"redirect",location:q.browserLoginUrl};return y!==void 0&&(O.setCookie=y),O}let R=await Ai({transaction:p,principal:h,now:a});return t.context?.log.info({event:"oauth_authorize_awaiting_setup",clientId:i,operationId:s.operationId,subjectId:h.subjectId},"Downstream OAuth authorize: rendering consent/setup page"),t.context&&v(t.context,{eventType:C.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:s.operationId,attributes:{clientId:i,scope:o,responseType:r.response_type,subjectId:h.subjectId}}),ls({transaction:R.transaction,csrfToken:R.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookie:y})}catch(s){throw Um({redirectUri:r.redirect_uri,clientState:r.state,cause:s})}}n(Sn,"authorizeDownstreamClient");function Um(e){if(e.cause instanceof Ae)return e.cause;let t=Pm(e.cause);return t?new Ae({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}n(Um,"toDownstreamAuthorizeRedirectError");function Pm(e){if(e instanceof m)return{errorCode:e.errorCode,errorDescription:e.message};if(e instanceof d.ZodError){let t=e.issues[0];return{errorCode:t?.path.includes("resource")?"invalid_target":"invalid_request",errorDescription:t?.message}}}n(Pm,"mapToOAuthRedirectError");async function ps(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let p=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,h=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...p===void 0?{}:{idpErrorDescription:p},...h===void 0?{}:{idpErrorUri:h}},"Identity provider redirected browser-login callback with an error"),w("provider_access_denied",p??"The delegated browser login was not completed.")}let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),w("oauth_state_invalid","Browser login callback is missing state.");let a=await dn(o),i={request:e,stateId:a.stateId};t.context!==void 0&&(i.context=t.context);let c=await Mi(i),s=await xi({browserLoginStateToken:o,principal:c.principal});if(await $i({transaction:s.transaction,principal:c.principal,subjectToken:c.subjectToken}),await gn({operationId:s.transaction.operationId,principal:c.principal}))throw w("browser_login_verification_failed","The identity provider did not return the subject token required for XAA / ID-JAG.");let u=await ls({transaction:s.transaction,csrfToken:s.csrfToken,requestUrl:e.url,requestHeaders:e.headers});return u.setCookie=await fr({principal:c.principal,requestUrl:e.url,requestHeaders:e.headers}),u}n(ps,"completeBrowserLoginCallback");async function ms(e){let t=B(),r=new URL(e.url);if(!$(r))throw w("forbidden","Local browser login is only available on loopback HTTP origins.");let o=typeof e.query.state=="string"?e.query.state:void 0;if(!o)throw w("oauth_state_invalid","Local browser login is missing state.");let a=H().actionPath("/oauth/callback"),i=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:a,P(e.url)),c=new URL(P(e.url)).origin;if(i.origin!==c||i.pathname!==a)throw w("oauth_callback_mismatch",`Local browser login redirect_uri must target this gateway's ${a} route.`);i.searchParams.set("state",o);let s={subjectId:it.parse(bm),roles:Rm};return{kind:"redirect",location:i,setCookie:await fr({principal:s,requestUrl:e.url,requestHeaders:e.headers})}}n(ms,"completeLocalDevBrowserLogin");function Em(e){let t=e.method==="POST"?e.body:e.query;return vm.parse(t)}n(Em,"readSetupContinueRequest");async function fs(e){let{state:t,decision:r}=Em({method:e.request.method,query:e.request.query,body:e.body}),o=new Date,a=await pn({csrfToken:t,now:o}),i=await km(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await Ui({csrfToken:t,currentBrowserPrincipal:i,now:o})};let c=await ki({csrfToken:t,currentBrowserPrincipal:i,now:o}),s=await bn({transaction:c,requestUrl:e.request.url,requestHeaders:e.request.headers,returnTo:us(t)});if(r==="approve"&&Cn(s)&&await Ci({csrfToken:t,currentBrowserPrincipal:i,now:o}),Cn(s)){let u=await In({transaction:c,requestUrl:e.request.url,requestHeaders:e.request.headers});return{kind:"setup_page",html:_n({state:t,operationId:c.operationId,gateway:H(),upstreams:s,...u})}}return{kind:"redirect",location:await Ti({csrfToken:t,currentBrowserPrincipal:i,now:o})}}n(fs,"continueDownstreamAuthorizeSetup");F();import{createLocalJWKSet as Fm,decodeJwt as $m,errors as Tt,jwtVerify as Zm}from"jose";F();import{createRemoteJWKSet as Om,decodeJwt as qm,decodeProtectedHeader as Mm,errors as kt,jwtVerify as Dm}from"jose";var ws=30,k=d.string().min(1),zm=d.union([k,d.array(k).min(1)]),Hm=d.union([k,d.array(k).min(1)]),jm=d.object({type:k,locations:d.array(k).optional(),actions:d.array(k).optional(),datatypes:d.array(k).optional(),identifier:k.optional(),privileges:d.array(k).optional()}).passthrough(),Bm=d.object({iss:d.url(),sub:k,aud:zm,client_id:k,resource:Hm.optional(),scope:k.optional(),authorization_details:d.array(jm).optional(),jti:k,iat:d.number().int(),nbf:d.number().int().optional(),exp:d.number().int(),tenant:k.optional(),aud_tenant:k.optional(),aud_sub:k.optional(),sub_id:k.optional(),act:d.unknown().optional(),email:k.optional(),auth_time:d.number().int().optional(),acr:k.optional(),amr:d.array(k).optional(),cnf:d.unknown().optional()}).passthrough();function V(e){throw new m("invalid_grant",e)}n(V,"throwInvalidGrant");function Lm(e){return e instanceof kt.JWTExpired?"expired":e instanceof kt.JWTClaimValidationFailed?"claim":e instanceof kt.JWSSignatureVerificationFailed?"signature":e instanceof kt.JWKSNoMatchingKey?"jwks_no_match":e instanceof kt.JWTInvalid?"invalid":e instanceof d.ZodError?"schema":"other"}n(Lm,"readJwtFailureKind");function Nm(e){return Array.isArray(e.aud)?(e.aud.length!==1&&V("ID-JAG audience must contain exactly one value."),e.aud[0]):e.aud}n(Nm,"readSingleAudience");function hs(e){try{let t=Bm.parse(e);return Nm(t),t}catch(t){if(t instanceof m)throw t;V("ID-JAG claims are invalid.")}}n(hs,"parseIdJagClaims");function Jm(e,t){e.idJag.enabled||V("ID-JAG grant is not enabled.");let r=e.idJag.trustedIssuers.find(o=>o.issuer===t);return r===void 0&&V("ID-JAG issuer is not trusted."),r}n(Jm,"readTrustedIssuer");function Gm(e){let t=e.authorizationDetails;if(t===void 0)return;if(e.allowedTypes===void 0)return t;let r=new Set(e.allowedTypes);return t.filter(o=>r.has(o.type))}n(Gm,"readGrantedAuthorizationDetails");function gs(e){if(e.clientAuth.method==="none")throw new m("invalid_client","Client authentication failed.");e.claims.client_id!==e.authenticatedClientId&&V("ID-JAG client_id must match the authenticated client."),e.trustedIssuer.expectedClientIds!==void 0&&!e.trustedIssuer.expectedClientIds.includes(e.claims.client_id)&&V("ID-JAG client_id is not allowed for this issuer.")}n(gs,"assertClientBinding");function ys(e){e.cnf!==void 0&&V("ID-JAG cnf-bound assertions require DPoP support.")}n(ys,"assertProofOfPossessionNotDeferred");function _s(e){let t=Math.floor(e.now.getTime()/1e3)+ws;e.claims.iat>t&&V("ID-JAG iat must not be in the future.")}n(_s,"assertIssuedAtNotInFuture");async function Rs(e){let t;try{t=Mm(e.assertion)}catch{V("ID-JAG assertion is malformed.")}t.typ!==Cr&&V('ID-JAG header typ must be "oauth-id-jag+jwt".');let r;try{r=hs(qm(e.assertion))}catch(s){if(s instanceof m)throw s;V("ID-JAG assertion is malformed.")}let o=Je(e.requestUrl,e.requestHeaders),a=[o];e.requestedResource!==void 0&&e.requestedResource!==o&&a.push(e.requestedResource);let i=Jm(e.config,r.iss);a.includes(r.iss)&&V("ID-JAG issuer must be different from the gateway."),gs({claims:r,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),ys(r),_s({claims:r,now:e.now});let c;try{let s=Om(new URL(i.jwksUrl)),{payload:u}=await Dm(e.assertion,s,{issuer:i.issuer,audience:a,currentDate:e.now,clockTolerance:ws,typ:Cr});c=hs(u)}catch(s){e.context?.log.warn({event:"oauth_id_jag_verification_failed",issuer:i.issuer,failureKind:Lm(s)},"OAuth ID-JAG assertion verification failed"),V("ID-JAG assertion verification failed.")}return gs({claims:c,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),ys(c),_s({claims:c,now:e.now}),{claims:c,trustedIssuer:i,subjectId:vo({issuer:c.iss,subject:c.sub,gatewayIssuer:o,subjectMapping:i.subjectMapping,tenant:c.tenant}),grantedAuthorizationDetails:Gm({authorizationDetails:c.authorization_details,allowedTypes:e.config.idJag.enabled?e.config.idJag.authorizationDetailsTypesAllowed:void 0})}}n(Rs,"verifyIdJagAssertion");var Km=new Set(["authorization_code","refresh_token",be]),Wm=1e4,Vm=32*1024,Ym=2,Xm=3600,vn=d.object({client_id:d.string().min(1).optional(),client_secret:d.string().min(1).optional(),client_assertion_type:d.string().min(1).optional(),client_assertion:d.string().min(1).optional()}),Qm=d.discriminatedUnion("grant_type",[vn.extend({grant_type:d.literal("authorization_code"),code:d.string().min(1),redirect_uri:d.string().min(1),code_verifier:je,resource:d.url().optional(),scope:d.literal(E).optional()}),vn.extend({grant_type:d.literal("refresh_token"),refresh_token:d.string().min(1),resource:d.url().optional(),scope:d.literal(E).optional()}),vn.extend({grant_type:d.literal(be),assertion:d.string().min(1),resource:d.url().optional(),scope:d.literal(E).optional(),authorization_details:d.string().min(1).optional()})]);function ef(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!Km.has(t)))throw new m("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}n(ef,"assertSupportedGrantType");var tf=d.object({token:d.string().min(1),client_id:d.string().min(1).optional(),token_type_hint:d.string().optional(),client_secret:d.string().min(1).optional(),client_assertion_type:d.string().min(1).optional(),client_assertion:d.string().min(1).optional()}),rf=d.object({keys:d.array(d.record(d.string(),d.unknown())).min(1)}).passthrough();function Is(){return B().gateway.accessTokenTtlSeconds}n(Is,"readAccessTokenTtlSeconds");function nf(){return B().gateway.refreshTokenTtlSeconds}n(nf,"readRefreshTokenTtlSeconds");function bs(e,t){let r=Is(),o=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),a=Math.min(r,o);return{expiresAt:I(ce(e,a)),expiresIn:a}}n(bs,"calculateAccessTokenExpiresAt");function of(e){let t=e.claimedResource===void 0?[]:Array.isArray(e.claimedResource)?e.claimedResource:[e.claimedResource];if(e.requestedResource!==void 0){if(t.length>0&&!t.includes(e.requestedResource))throw new m("invalid_target","Token request resource must match the ID-JAG resource.");return e.requestedResource}if(t.length===0)throw new m("invalid_target","resource is required for the ID-JAG JWT bearer grant.");if(t.length!==1)throw new m("invalid_target","ID-JAG resource arrays require a token request resource.");return t[0]}n(of,"readIdJagResource");function af(e){if(e.claimAuthorizationDetails===void 0)return;let t=(e.grantedAuthorizationDetails??[]).filter(r=>r.locations?.includes(e.resource)===!0);if(t.length===0)throw new m("invalid_grant","ID-JAG authorization_details must authorize the requested resource.");return t}n(af,"readIdJagGrantedAuthorizationDetails");function sf(e){if(e.claimScope?.split(/\s+/).includes(E)===!0||(e.grantedAuthorizationDetails?.length??0)>0)return E;if(e.claimScope===void 0)throw new m("invalid_grant",`ID-JAG must include ${E} scope or matching authorization_details.`);if(!e.claimScope.split(/\s+/).includes(E))throw new m("invalid_grant",`ID-JAG scope must include ${E}.`);return E}n(sf,"readIdJagGrantedScope");function cf(e){if(e!==void 0&&e.get("dpop")!==null)throw new m("invalid_request","DPoP proofs are not supported for the ID-JAG JWT bearer grant.")}n(cf,"assertNoDpopProofForIdJag");function Cs(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new m("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new m("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new m("invalid_client","Malformed HTTP Basic client authentication.")}}n(Cs,"readBasicClientSecret");function Ss(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new m("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t!==void 0)return t;if(e.clientAssertion!==void 0){try{let r=$m(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new m("invalid_client","Malformed private_key_jwt client assertion.")}throw new m("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new m("invalid_client","Client authentication or client_id is required.")}n(Ss,"resolveAuthenticatedClientId");function df(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new m("invalid_request","Use only one client authentication method per request.");return e.basicClientSecret!==void 0?{clientSecret:e.basicClientSecret,clientSecretSource:"basic"}:e.bodyClientSecret!==void 0?{clientSecret:e.bodyClientSecret,clientSecretSource:"post"}:{}}n(df,"resolveClientSecretInput");function uf(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}n(uf,"hasClientAssertion");function lf(e){if(e.requestUrl===void 0)throw new m("invalid_request","Request URL is required for private_key_jwt client authentication.");let t=new URL(H().actionPath(e.pathname),P(e.requestUrl,e.requestHeaders));return t.search="",t.hash="",t.toString()}n(lf,"buildEndpointAudience");function pf(e){return e instanceof Tt.JWTExpired?"expired":e instanceof Tt.JWTClaimValidationFailed?"claim":e instanceof Tt.JWSSignatureVerificationFailed?"signature":e instanceof Tt.JWKSNoMatchingKey?"jwks_no_match":e instanceof Tt.JWTInvalid?"invalid":e instanceof d.ZodError?"schema":"other"}n(pf,"readJwtFailureKind");async function mf(e){let{response:t,json:r}=await sa(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:Ym,maxResponseBytes:Vm,timeoutMs:Wm});if(!t.ok)throw new m("invalid_client","Client JWKS could not be fetched.");return rf.parse(r)}n(mf,"fetchClientJwks");async function ff(e){if(e.clientAssertionType!==Gt||e.clientAssertion===void 0)throw new m("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=ue.parse(e.clientId),r=await hr(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new m("invalid_client","Client is not registered for private_key_jwt authentication.");let o=r.metadata.jwks_uri;if(o===void 0)throw new m("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let a=lf({requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,pathname:e.endpointPathname});try{let i=await mf({jwksUri:o,context:e.context}),{payload:c}=await Zm(e.clientAssertion,Fm(i),{issuer:t,subject:t,audience:a,currentDate:e.now}),s=Math.floor(e.now.getTime()/1e3)+Xm;if(typeof c.exp!="number"||c.exp>s)throw new m("invalid_client","Client authentication failed.")}catch(i){throw e.context?.log.warn({event:"oauth_private_key_jwt_client_auth_failed",clientId:t,failureKind:pf(i)},"OAuth private_key_jwt client authentication failed"),new m("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}n(ff,"verifyPrivateKeyJwtClientAssertion");async function hf(e){let t=ue.parse(e.clientId);if(Po(t))throw new m("invalid_client","Client is registered for private_key_jwt authentication.");return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await x(e.clientSecret)}}n(hf,"buildRuntimeHttpClientAuth");async function vs(e){if(uf({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new m("invalid_request","Use only one client authentication method per request.");return ff(e)}let t=df({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return hf({clientId:e.clientId,...t})}n(vs,"resolveRuntimeHttpClientAuth");async function As(e){ef(e.body);let t=Qm.parse(e.body),r=Cs(e.authorizationHeader),o=Ss({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date,i=await vs({clientId:o,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,endpointPathname:"/oauth/token",now:a,context:e.context});return gf({parsed:t,clientId:o,clientAuth:i,now:a,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,context:e.context})}n(As,"exchangeDownstreamToken");async function gf(e){if(e.parsed.grant_type==="authorization_code"){rt(e.parsed.redirect_uri,"invalid_request"),nt(e.parsed.scope),e.parsed.resource!==void 0&&Me(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let s=le(),u=le(),p=I(ce(e.now,nf())),h=bs(e.now,p),y=await b().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await x(e.parsed.code),redirectUri:e.parsed.redirect_uri,resource:e.parsed.resource,codeChallenge:await Kt(e.parsed.code_verifier),currentRefreshTokenHash:await x(s),accessTokenHash:await x(u),grantExpiresAt:p,accessTokenExpiresAt:h.expiresAt,now:I(e.now)});if(y.kind==="invalid_client")throw new m("invalid_client","Client authentication failed.");if(y.kind==="resource_mismatch")throw new m("invalid_target","Token request resource must match the authorization code resource.");if(y.kind!=="exchanged")throw new m("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&v(e.context,{eventType:C.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:u,token_type:"Bearer",expires_in:h.expiresIn,refresh_token:s,scope:y.grant.scope,resource:y.grant.resource}}if(e.parsed.grant_type===be){nt(e.parsed.scope),cf(e.requestHeaders);let s=await Rs({assertion:e.parsed.assertion,authenticatedClientId:e.clientId,clientAuth:e.clientAuth,requestUrl:e.requestUrl??e.parsed.resource??"",requestHeaders:e.requestHeaders,requestedResource:e.parsed.resource,now:e.now,context:e.context,config:B()}),u=of({claimedResource:s.claims.resource,requestedResource:e.parsed.resource}),p=Me(e.requestUrl??u,u,e.requestHeaders),h=af({claimAuthorizationDetails:s.claims.authorization_details,grantedAuthorizationDetails:s.grantedAuthorizationDetails,resource:u}),y=sf({claimScope:s.claims.scope,grantedAuthorizationDetails:h}),U=le(),R=I(new Date(s.claims.exp*1e3)),q=bs(e.now,R),O=await b().issueAccessTokenForIdJag({clientAuth:e.clientAuth,accessTokenHash:await x(U),subjectId:s.subjectId,resource:u,operationId:p.operationId,scope:y,authorizationDetails:h,accessTokenExpiresAt:q.expiresAt,now:I(e.now),idJag:{issuer:s.claims.iss,jti:s.claims.jti,tenant:s.claims.tenant,expiresAt:R}});if(O.kind==="invalid_client")throw new m("invalid_client","Client authentication failed.");if(O.kind==="resource_mismatch")throw new m("invalid_target","Token request resource must match the ID-JAG resource.");return e.context&&v(e.context,{eventType:C.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"jwt-bearer"}}),{access_token:U,token_type:"Bearer",expires_in:q.expiresIn,scope:O.grant.scope,resource:O.grant.resource,...h===void 0?{}:{authorization_details:h}}}nt(e.parsed.scope),e.parsed.resource!==void 0&&Me(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let t=await x(e.parsed.refresh_token),r=e.parsed.refresh_token,o=le(),a=I(ce(e.now,Is())),i=await b().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:t,nextRefreshTokenHash:t,accessTokenHash:await x(o),resource:e.parsed.resource,accessTokenExpiresAt:a,now:I(e.now)});if(i.kind==="invalid_client")throw new m("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new m("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new m("invalid_grant","Refresh token is invalid, expired, or revoked.");Me(e.requestUrl??i.grant.resource,i.grant.resource,e.requestHeaders);let c=i.accessToken.expiresAt;return e.context&&v(e.context,{eventType:C.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),{access_token:o,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(c).getTime()-e.now.getTime())/1e3)),refresh_token:r,scope:i.grant.scope,resource:i.grant.resource}}n(gf,"exchangeDownstreamTokenWithRuntimeHttp");async function xs(e){let t=tf.parse(e.body),r=Cs(e.authorizationHeader),o=Ss({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date;if((await b().revokeOAuthToken({clientAuth:await vs({clientId:o,basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret,clientAssertion:t.client_assertion,clientAssertionType:t.client_assertion_type,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,endpointPathname:"/oauth/revoke",now:a,context:e.context}),tokenHash:await x(t.token),now:I(a)})).kind==="invalid_client")throw new m("invalid_client","Client authentication failed.");e.context?.log.info({event:"oauth_token_revoked",clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}},"OAuth token revocation request processed"),e.context&&v(e.context,{eventType:C.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}n(xs,"revokeDownstreamToken");var yf=64*1024,_f=16*1024,wf="text/html; charset=utf-8";function Rf(e){let t={};for(let[r,o]of e.entries())t[r]=o;return t}n(Rf,"formDataToObject");async function bf(e){return ui(e,{maxBytes:yf,label:"Request body"})}n(bf,"readJsonBody");async function xn(e){return Rf(await li(e,{maxBytes:_f,label:"Request body"}))}n(xn,"readFormBody");async function Ts(e,t,r){let o=se(r),a=r instanceof d.ZodError?xe(r):void 0,i={code:o??(r instanceof d.ZodError?"invalid_request":"internal_server_error")};return a!==void 0&&(i.detail=a),Ht(e,t,i)}n(Ts,"handleProblem");function Us(e){return e?.requestId}n(Us,"readBrowserRequestId");function Ps(e){if(!(e instanceof f))return;let t=e.extensionMembers?.[Le];return typeof t=="string"?t:void 0}n(Ps,"readUpstreamHtmlError");function ks(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}n(ks,"readRuntimeErrorExtensionString");function If(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}n(If,"readRuntimeErrorExtensionNumber");function Cf(e){try{return new URL(e.url).pathname}catch{return}}n(Cf,"readBrowserRequestPath");function De(e){let t={code:e.code,requestId:e.requestId,routePath:Cf(e.request),underlyingError:e.underlyingError};return e.error instanceof f&&(t.httpStatus=If(e.error,_e),t.contentType=ks(e.error,Be),t.upstreamUrl=ks(e.error,we)),t}n(De,"buildBrowserErrorDiagnostic");function Ut(e){let t=new Headers(e.headers);t.set("cache-control","no-store"),t.set("pragma","no-cache");let r={error:e.error};return e.errorDescription!==void 0&&(r.error_description=e.errorDescription),Response.json(r,{status:e.status??400,headers:t})}n(Ut,"oauthErrorResponse");function Sf(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}n(Sf,"readOAuthProtocolHeaders");function vf(e,t){let r=ee("internal_server_error");return Ut({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:Sf(e,t)})}n(vf,"oauthProtocolErrorResponse");function An(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}n(An,"readZodOAuthErrorCode");function Af(e){let t={error:An(e)},r=xe(e);return r!==void 0&&(t.errorDescription=r),Ut(t)}n(Af,"oauthZodErrorResponse");function xf(e){let t=se(e);if(t===void 0)return;let r=ee(t);if(r.oauthError===void 0)return;let o={error:r.oauthError,status:Tf(r.oauthError)};return r.oauthError==="server_error"?o.errorDescription=r.publicDetail:e instanceof Error?o.errorDescription=e.message:o.errorDescription=r.publicDetail,Ut(o)}n(xf,"oauthGatewayProblemResponse");function kf(){let t={error:"server_error",status:500,errorDescription:ee("internal_server_error").publicDetail};return Ut(t)}n(kf,"oauthFallbackErrorResponse");function Tf(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}n(Tf,"readOAuthStatus");function kn(e,t={}){return e instanceof Ae?qs(e):e instanceof m?vf(e,t):e instanceof d.ZodError?Af(e):xf(e)??kf()}n(kn,"oauthProblemResponse");function Tn(e,t,r){let o=et(e.url),a=Us(t);if(r instanceof Ae)return qs(r);if(r instanceof m){let s=ee("internal_server_error");return ne({host:o,kind:Uf(r.errorCode),title:"Authorization failed",detail:r.errorCode==="server_error"?s.publicDetail:r.message,developerDetail:r.errorCode==="server_error"?s.publicDetail:r.message,code:r.errorCode,diagnostic:De({request:e,requestId:a,code:r.errorCode,underlyingError:r.errorCode==="server_error"?s.publicDetail:r.message,error:r}),requestId:a,status:r.status})}if(r instanceof d.ZodError)return ne({host:o,kind:"invalid_request",detail:xe(r)??"The authorization request was invalid.",developerDetail:xe(r)??"The authorization request was invalid.",code:An(r),diagnostic:De({request:e,requestId:a,code:An(r),underlyingError:xe(r)??"The authorization request was invalid.",error:r}),requestId:a});let i=se(r);if(i!==void 0){let s=ee(i);return ne({host:o,kind:Os(i),detail:s.publicDetail,developerDetail:s.status>=500||!(r instanceof Error)?s.publicDetail:r.message,code:i,diagnostic:De({request:e,requestId:a,code:i,underlyingError:s.status>=500||!(r instanceof Error)?s.publicDetail:r.message,error:r}),requestId:a,upstreamHtml:Ps(r),status:s.status})}let c=ee("internal_server_error");return ne({host:o,kind:"internal_error",detail:c.publicDetail,developerDetail:c.publicDetail,code:"server_error",diagnostic:De({request:e,requestId:a,code:"server_error",underlyingError:c.publicDetail,error:r}),requestId:a,status:c.status})}n(Tn,"browserOAuthProblemResponse");function Es(e,t,r){let o=et(e.url),a=Us(t),i=se(r);if(i!==void 0){let s=ee(i);return ne({host:o,kind:Os(i),detail:s.publicDetail,developerDetail:s.status>=500||!(r instanceof Error)?s.publicDetail:r.message,code:i,diagnostic:De({request:e,requestId:a,code:i,underlyingError:s.status>=500||!(r instanceof Error)?s.publicDetail:r.message,error:r}),requestId:a,upstreamHtml:Ps(r),status:s.status})}if(r instanceof d.ZodError)return ne({host:o,kind:"invalid_request",detail:xe(r)??"The authorization request was invalid.",developerDetail:xe(r)??"The authorization request was invalid.",code:"invalid_request",diagnostic:De({request:e,requestId:a,code:"invalid_request",underlyingError:xe(r)??"The authorization request was invalid.",error:r}),requestId:a});let c=ee("internal_server_error");return ne({host:o,kind:"internal_error",detail:c.publicDetail,developerDetail:c.publicDetail,code:"internal_server_error",diagnostic:De({request:e,requestId:a,code:"internal_server_error",underlyingError:c.publicDetail,error:r}),requestId:a,status:c.status})}n(Es,"browserGatewayProblemResponse");function Uf(e){return e==="server_error"?"internal_error":"invalid_request"}n(Uf,"readOAuthBrowserErrorKind");function Os(e){if(ee(e).status>=500)return"internal_error";switch(e){case"mcp_route_not_enabled":case"unknown_upstream_server":case"unknown_mcp_route":case"unknown_auth_profile":case"mcp_route_upstream_mismatch":return"configuration_error";case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"upstream_oauth_discovery_unavailable":case"upstream_provider_access_denied":case"upstream_client_registration_required":return"admin_required";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"invalid_request":case"authentication_required":case"forbidden":case"not_found":case"too_many_requests":case"identity_context_missing":return"invalid_request";case"upstream_capability_invocation_failed":case"upstream_capability_unavailable":case"upstream_import_failed":return"connection_failed";case"internal_server_error":return"internal_error"}return"authorization_failed"}n(Os,"readGatewayBrowserErrorKind");function he(e,t,r){let o={event:t},a=!1;if(r instanceof m)o.oauthError=r.errorCode,o.status=r.status,L(o,"error",r);else if(r instanceof Ae)o.oauthError=r.errorCode,L(o,"error",r);else if(r instanceof d.ZodError){o.code="invalid_request",L(o,"error",r);let i=r.issues[0];i&&(o.zodPath=i.path.join("."))}else{let i=se(r);if(i!==void 0){let c=ee(i);o.code=i,o.status=c.status,c.oauthError!==void 0&&(o.oauthError=c.oauthError),a=c.status>=500||c.oauthError==="server_error",L(o,"error",r)}else a=!0,L(o,"error",r)}if(a){let i=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(o,i.message)}else e.log.warn(o,"OAuth handler rejected the request")}n(he,"logUnexpectedOAuthHandlerError");function qs(e){let t;try{t=new URL(e.redirectUri)}catch{return Ut({error:e.errorCode,...e.errorDescription===void 0?{}:{errorDescription:e.errorDescription}})}t.searchParams.set("error",e.errorCode),e.errorDescription!==void 0&&t.searchParams.set("error_description",e.errorDescription),e.clientState!==void 0&&t.searchParams.set("state",e.clientState);let r=new Headers({location:t.toString(),"cache-control":"no-store"});return new Response(null,{status:302,headers:r})}n(qs,"downstreamAuthorizeRedirectErrorResponse");function xe(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}n(xe,"formatZodErrorDetail");function Pf(e,t){let r={event:"browser_login_callback_failed",code:se(t)??"invalid_request"};L(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}n(Pf,"logBrowserLoginCallbackFailure");function Ms(e){e.location.hash||(e.location.hash="#");let t=new Headers({location:e.location.toString(),"cache-control":"no-store"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(null,{status:302,headers:t})}n(Ms,"redirectResultResponse");function yr(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":wf,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"});return e.setCookie&&t.append("set-cookie",e.setCookie),new Response(e.html,{status:200,headers:t})}return Ms(e)}n(yr,"authorizeResultResponse");async function Ds(e,t){try{return Response.json(bo(e.url,e.headers))}catch(r){return he(t,"oauth_authorization_server_metadata_failed",r),Ts(e,t,r)}}n(Ds,"authorizationServerMetadataHandler");async function zs(e,t){try{let r=Ur(e.params.routePath);return Response.json(Io({operationId:r.operationId,requestUrl:e.url,requestHeaders:e.headers}))}catch(r){return he(t,"oauth_authorization_server_metadata_failed",r),Ts(e,t,r)}}n(zs,"scopedAuthorizationServerMetadataHandler");async function Hs(e,t){try{let r=await Gi(await bf(e)),o=r.client_id,a=r.client_name,i=r.redirect_uris.length,c=r.token_endpoint_auth_method;return t.log.info({event:"oauth_dcr_client_registered",clientId:o,clientName:a,redirectUriCount:i,tokenEndpointAuthMethod:c},"OAuth Dynamic Client Registration completed"),v(t,{eventType:C.MCP_OAUTH_CLIENT_REGISTERED,outcome:"success",clientName:a,attributes:{clientId:o,redirectUriCount:i,tokenEndpointAuthMethod:c}}),Response.json(r,{status:201,headers:{"cache-control":"no-store"}})}catch(r){return he(t,"oauth_register_failed",r),kn(r)}}n(Hs,"registerHandler");async function js(e,t){try{return yr(await Sn(e,{context:t}))}catch(r){return he(t,"oauth_authorize_failed",r),Tn(e,t,r)}}n(js,"authorizeHandler");async function Bs(e,t){try{let r=Ur(e.params.routePath);return yr(await Sn(e,{operationId:r.operationId,context:t}))}catch(r){return he(t,"oauth_authorize_scoped_failed",r),Tn(e,t,r)}}n(Bs,"scopedAuthorizeHandler");async function Ls(e,t){try{let r=await ps(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),yr(r)}catch(r){return Pf(t,r),Es(e,t,r)}}n(Ls,"callbackHandler");async function Ns(e,t){try{return Ms(await ms(e))}catch(r){return he(t,"oauth_dev_login_failed",r),Tn(e,t,r)}}n(Ns,"devLoginHandler");async function Js(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await fs({request:e,body:e.method==="POST"?await xn(e):void 0,context:t});return yr(r)}catch(r){return he(t,"oauth_setup_failed",r),Es(e,t,r)}}n(Js,"setupHandler");async function Gs(e,t){try{return Response.json(await As({body:await xn(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,requestHeaders:e.headers,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return he(t,"oauth_token_failed",r),kn(r)}}n(Gs,"tokenHandler");async function Fs(e,t){try{return await xs({body:await xn(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,requestHeaders:e.headers,context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return he(t,"oauth_revoke_failed",r),kn(r)}}n(Fs,"revokeHandler");function $s(e){return S`<p data-gateway-error-code="${e.code}">${e.body}</p>`}n($s,"renderBrowserResult");var Ef="text/html; charset=utf-8",Of="none";function qf(e){let t=Fr(e.host);return Qe({title:e.title,iconHref:t,styles:Xe,headerIcon:gr({iconHref:t,fallbackIconHref:er}),heading:e.title,subhead:"",body:$s({body:e.body,code:e.code??Of}),footer:""})}n(qf,"browserResultHtml");function Mf(e,t=200){return new Response(Ye(e),{status:t,headers:{"content-type":Ef,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(Mf,"browserResultResponse");function Zs(e){return Mf(qf(e))}n(Zs,"browserConnectionSuccessResponse");function _r(e,t,r={}){let o=Qn(t);return ne({host:e,kind:Df(t),detail:o.body,developerDetail:r.developerDetail,code:t,diagnostic:r.diagnostic,upstreamHtml:r.upstreamHtml})}n(_r,"browserConnectionFailureResponse");function Df(e){switch(e){case"provider_access_denied":return"access_denied";case"oauth_state_invalid":case"oauth_state_expired":case"oauth_state_reused":case"oauth_callback_mismatch":return"session_expired";case"browser_login_verification_failed":case"upstream_token_exchange_failed":case"upstream_token_response_invalid":return"connection_failed";case"upstream_oauth_discovery_unavailable":case"upstream_provider_access_denied":case"upstream_client_registration_required":return"admin_required"}}n(Df,"readCallbackFailureBrowserErrorKind");var zf={connect:"Connect",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},Ks=Symbol("upstream-request");function Pt(e,t){Object.defineProperty(e,Ks,{configurable:!0,value:t})}n(Pt,"setUpstreamRequestContext");function Hf(e){let t=e[Ks];if(!t)throw new Y("Upstream request context has not been set");return t}n(Hf,"readUpstreamRequestContext");function jf(e,t){return t.some(r=>r===e)}n(jf,"requestContextMatchesKind");function Bf(e){return typeof e=="string"?[e]:e}n(Bf,"toExpectedKinds");function Et(e,t){let r=Hf(e),o=Bf(t);if(!jf(r.kind,o)){let a=zf[o[0]];throw new Y(`${a} request context has not been set`)}return r}n(Et,"requireUpstreamRequestContext");function ze(e){if(typeof e=="string"&&e.length!==0)return e}n(ze,"readOptionalQueryString");function Lf(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw new Y(`Validated path parameter ${t} is missing`);return Nf(r,t)}n(Lf,"requirePathString");function Nf(e,t){try{return decodeURIComponent(e)}catch(r){throw new f({message:`Path parameter "${t}" must be valid URL encoding.`,extensionMembers:{[g]:"invalid_request"}},{cause:r})}}n(Nf,"decodePathString");function Jf(e){let t=ze(e);return t?jt.parse(t):void 0}n(Jf,"readOptionalOperationId");function Gf(e){let t=X().connectionsById.get(e);if(t!==void 0)return t.authProfileId;throw new f({message:`No upstream connection is registered for ${e}.`,extensionMembers:{[g]:"unknown_upstream_server"}})}n(Gf,"readRegisteredAuthProfileId");function Ff(e){let t=Jf(e);if(!t)throw new f({message:"operationId query parameter is required.",extensionMembers:{[g]:"invalid_request"}});return t}n(Ff,"readRequiredOperationId");async function $f(e,t){let r=dr(t,Ff(e.query.operationId));if(r.authMode==="id-jag")throw new f({message:"This upstream uses XAA / ID-JAG and does not support browser OAuth connection flows.",extensionMembers:{[g]:"invalid_request"}});let o=e.query.redirect==="true",a=ze(e.query.browserTicket);if(e.user){if(a)throw new f({message:"Use either an authenticated gateway request or a browser connect ticket, not both.",extensionMembers:{[g]:"invalid_request"}});let s=Te(e.user,e.url),u={kind:"connect",...Ve(r,s.subjectId),redirect:o},p=io(ze(e.query.returnTo));return p!==void 0&&(u.returnTo=p),u}if(!a)throw new f({message:"Authentication is required to start the upstream connection flow.",extensionMembers:{[g]:"authentication_required"}});let i=await Ca(a);if(i.ownerMode!==r.ownerMode||i.upstreamServerId!==r.upstreamServerId||i.authProfileId!==r.authProfileId||i.operationId!==r.operationId)throw new f({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[g]:"oauth_callback_mismatch"}});await Sa(i);let c=Nt(i);switch(r.authMode){case"shared-oauth":{if(c.mode!=="shared")throw new f({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[g]:"oauth_callback_mismatch"}});let s={kind:"connect",...r,authMode:"shared-oauth",ownerMode:"shared",owner:c,initiatedBySubjectId:i.initiatedBySubjectId,redirect:o};return i.returnTo!==void 0&&(s.returnTo=i.returnTo),s}case"user-oauth":{if(c.mode!=="user")throw new f({message:"Browser connect ticket did not match the requested upstream flow",extensionMembers:{[g]:"oauth_callback_mismatch"}});let s={kind:"connect",...r,authMode:"user-oauth",ownerMode:"user",owner:c,initiatedBySubjectId:i.initiatedBySubjectId,redirect:o};return i.returnTo!==void 0&&(s.returnTo=i.returnTo),s}}}n($f,"resolveConnectContext");async function Zf(e,t,r){let o=ro.parse(Lf(e,"connection"));switch(r){case"connect":Pt(e,await $f(e,o));return;case"callback":{let a=ze(e.query.error);if(a){let s={kind:"callback_provider_error",upstreamServerId:o,error:a},u=ze(e.query.error_description);u!==void 0&&(s.errorDescription=u),Pt(e,s);return}let i=ze(e.query.code),c=ze(e.query.state);if(i&&c){Pt(e,{kind:"callback_authorization_code",upstreamServerId:o,code:i,state:c});return}Pt(e,{kind:"callback_invalid",upstreamServerId:o});return}case"client_metadata":Pt(e,{kind:"client_metadata",upstreamServerId:o,authProfileId:Gf(o)});return}}n(Zf,"resolveUpstreamRequestInbound");async function Kf(e,t,r){try{await Zf(e,t,r);return}catch(o){let a=o instanceof f?o.extensionMembers?.[g]:void 0,i=o instanceof Error?o.message:void 0;switch(a){case"invalid_request":case"unknown_upstream_server":case"oauth_callback_mismatch":return ke.badRequest(e,t,{code:a,detail:i});case"authentication_required":return ke.unauthorized(e,t,{code:a,detail:i});default:throw o}}}n(Kf,"applyUpstreamRequestContext");function wr(e,t){return n(async(o,a)=>{let i=await Kf(o,a,e);return i||t(o,a)},"wrapped")}n(wr,"withUpstreamRequestContext");var Wf=["callback_authorization_code","callback_provider_error","callback_invalid"];function Un(e){try{return new URL(e.url).pathname}catch{return}}n(Un,"readBrowserRequestPath");function Vf(e){return"cause"in e?e.cause:void 0}n(Vf,"readErrorCause");function Yf(e){return e.stack?.split(`
|
|
49
|
+
`).slice(1,4).map(t=>t.trim()).join(" | ")}n(Yf,"readFirstStackFrame");function Ws(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=Yf(r))}n(Ws,"addErrorAttributes");function Pn(e){if(!(e instanceof f))return;let t=e.extensionMembers?.[g];return zt(t)?t:void 0}n(Pn,"readRuntimeGatewayCode");function Vs(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}n(Vs,"readRuntimeErrorExtensionString");function Xf(e,t){let r=e.extensionMembers?.[t];return typeof r=="number"?r:void 0}n(Xf,"readRuntimeErrorExtensionNumber");function Qf(e,t,r,o){switch(r.kind){case"callback_provider_error":return t.log.warn({event:"upstream_oauth_provider_error",code:"provider_access_denied",upstreamServerId:r.upstreamServerId,providerError:r.error,...r.errorDescription===void 0?{}:{providerErrorDescription:r.errorDescription.slice(0,256)}},"Upstream identity provider returned an error to the OAuth callback"),v(t,{eventType:C.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:r.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:r.error,errorDescription:r.errorDescription}}),_r(o,"provider_access_denied",{developerDetail:r.errorDescription??r.error,diagnostic:{code:"provider_access_denied",requestId:t.requestId,routePath:Un(e),upstreamServerId:r.upstreamServerId,providerError:r.error,providerErrorDescription:r.errorDescription,underlyingError:r.errorDescription??r.error}});case"callback_invalid":return t.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:r.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),_r(o,"oauth_state_invalid",{diagnostic:{code:"oauth_state_invalid",requestId:t.requestId,routePath:Un(e),upstreamServerId:r.upstreamServerId}});case"callback_authorization_code":return r}}n(Qf,"requireAuthorizationCallbackRequest");function eh(e,t){v(e,{eventType:C.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}n(eh,"emitCallbackReceivedAnalyticsEvent");function th(e,t){v(e,{eventType:C.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.operationId})}n(th,"emitTokenExchangeSucceededAnalyticsEvent");function rh(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return Zs({host:et(e.url),title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}n(rh,"buildSuccessfulCallbackResponse");function nh(e){let t={detail:e instanceof Error?e.message:void 0};return Ws(t,"error",e),e instanceof Error&&Ws(t,"cause",Vf(e)),t}n(nh,"buildTokenExchangeFailureAttributes");function oh(e){v(e.context,{eventType:C.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:Pn(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:nh(e.error)})}n(oh,"emitTokenExchangeFailedAnalyticsEvent");function ah(e){let t=e.error,r=Pn(t),o=Xn(r)?r:"upstream_token_exchange_failed",a={code:o,requestId:e.context.requestId,routePath:Un(e.request),upstreamServerId:e.callbackRequest.upstreamServerId,underlyingError:t instanceof Error?t.message:void 0,...t instanceof f?{httpStatus:Xf(t,_e),contentType:Vs(t,Be),upstreamUrl:Vs(t,we)}:{}};return _r(e.host,o,{developerDetail:t instanceof Error?t.message:void 0,diagnostic:a,upstreamHtml:ih(t)})}n(ah,"tokenExchangeFailureResponse");function ih(e){if(!(e instanceof f))return;let t=e.extensionMembers?.[Le];return typeof t=="string"?t:void 0}n(ih,"readUpstreamHtmlError");async function En(e,t){let r=Et(e,Wf),o=et(e.url),a=Qf(e,t,r,o);if(a instanceof Response)return a;eh(t,a);try{let i=await ei({request:e,callbackRequest:a});return th(t,i),t.log.info({event:"upstream_oauth_token_exchange_succeeded",upstreamServerId:i.upstreamServerId,operationId:i.operationId,authProfileId:i.authProfileId,ownerMode:i.ownerMode},"Upstream OAuth token exchange completed; user connection established"),rh(e,i)}catch(i){let c={event:"upstream_oauth_token_exchange_failed",code:Pn(i)??"upstream_token_exchange_failed",upstreamServerId:a.upstreamServerId};return L(c,"error",i),t.log.warn(c,"Upstream OAuth token exchange failed; user shown connection-failure page"),oh({context:t,callbackRequest:a,error:i}),ah({request:e,context:t,host:o,callbackRequest:a,error:i})}}n(En,"callbackHandler");function sh(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}n(sh,"clientMetadataProblemDetail");async function Ys(e,t){let r=Et(e,"connect"),o=await Qa({request:e,connectRequest:r});if(v(t,{eventType:C.MCP_AUTH_UPSTREAM_CONNECT_STARTED,outcome:"success",upstreamServerName:r.upstreamServerId,virtualServerName:o.operationId,upstreamServerTitle:o.upstreamDisplayName}),t.log.info({event:"upstream_connect_started",upstreamServerId:r.upstreamServerId,authProfileId:o.authProfileId,operationId:o.operationId,ownerMode:r.ownerMode,redirect:r.redirect,hasReturnTo:r.returnTo!==void 0},"Upstream OAuth connect flow started"),r.redirect)return Response.redirect(o.authUrl,302);let a=await ir({requestUrl:e.url,requestHeaders:e.headers,owner:o.owner,initiatedBySubjectId:o.initiatedBySubjectId,upstreamServerId:r.upstreamServerId,authProfileId:o.authProfileId,upstreamDisplayName:o.upstreamDisplayName,operationId:o.operationId,subject:"MCP route",...r.returnTo===void 0?{}:{returnTo:r.returnTo}});return Response.json(a,{status:428})}n(Ys,"connectHandler");async function Xs(e,t){let r=Et(e,"client_metadata");try{let o=P(e.url,e.headers),a=Ua(o,r.upstreamServerId,r.authProfileId);return Response.json(a)}catch(o){if(!(o instanceof j))throw o;let a=o instanceof Error?o.message:String(o);return t.log.warn({event:"oauth_client_metadata_request_failed",upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:a},"Failed to serve OAuth client metadata document for upstream connection"),ke.notFound(e,t,{code:"not_found",detail:sh(o)})}}n(Xs,"oauthClientMetadataHandler");function ch(e,t){return e.mount==="root"?e.path:t.actionPath(e.path)}n(ch,"resolveInternalRoutePath");var dh={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function uh(){return new Response(null,{status:204,headers:dh})}n(uh,"buildWellKnownPreflightResponse");function lh(e){let t=new Headers(e.headers);return t.set("access-control-allow-origin","*"),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}n(lh,"withWellKnownCorsHeaders");function On(e){return async(t,r)=>t.method==="OPTIONS"?uh():lh(await e(t,r))}n(On,"wrapWellKnownHandler");var tc=[{routeName:"oauth_as_metadata",mount:"root",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:On(Ds),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",mount:"root",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:On(zs),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",mount:"root",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:On(Co),corsPolicy:"anything-goes"},{routeName:"oauth_register",mount:"action",path:"/oauth/register",methods:["POST"],handler:Hs},{routeName:"oauth_authorize",mount:"action",path:"/oauth/authorize",methods:["GET"],handler:js},{routeName:"oauth_authorize_scoped",mount:"action",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:Bs},{routeName:"oauth_callback",mount:"action",path:"/oauth/callback",methods:["GET"],handler:Ls},{routeName:"oauth_dev_login",mount:"action",path:"/oauth/dev-login",methods:["GET"],handler:Ns},{routeName:"oauth_setup",mount:"action",path:"/oauth/setup",methods:["GET","POST"],handler:Js},{routeName:"oauth_token",mount:"action",path:"/oauth/token",methods:["POST"],handler:Gs},{routeName:"oauth_revoke",mount:"action",path:"/oauth/revoke",methods:["POST"],handler:Fs},{routeName:"upstream_client_metadata",mount:"action",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:wr("client_metadata",Xs)},{routeName:"upstream_connect",mount:"action",path:"/auth/connections/:connection/connect",methods:["GET"],handler:wr("connect",Ys)},{routeName:"upstream_callback",mount:"action",path:"/auth/connections/:connection/callback",methods:["GET"],handler:wr("callback",En)}],ph=tc.filter(e=>!e.routeName.startsWith("upstream_")),mh=tc.filter(e=>e.routeName.startsWith("upstream_"));function fh(e){let t=po({routes:e.routes,policies:e.policies,gateway:e.gateway});return mo(t),t}n(fh,"initializeMcpGatewayConnectionRegistry");function hh(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth!==void 0)}n(hh,"hasDownstreamOAuthRoutes");function gh(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth?.config.idJag.enabled===!0)}n(gh,"hasIdJagDownstreamOAuth");function yh(e){let t=new Map;for(let o of e.byOperationId.values())o.downstreamOAuth&&t.set(o.downstreamOAuth.policyName,o.downstreamOAuth.config);if(t.size===1)return[...t.values()][0];let r=[...t.keys()].map(o=>`"${o}"`).join(", ");throw new j(`MCP gateway found multiple attached OAuth policies: ${r}. Multiple downstream MCP OAuth configs in one gateway are not supported yet; use one MCP OAuth policy across MCP routes or split these routes into separate gateways.`)}n(yh,"readSingletonDownstreamOAuthConfig");function _h(e,t,r){let o=String(t.params.routePath??""),a=e.byRoutePath.get(_o(o));if(a===void 0)return;let i=a?.downstreamOAuth?.config;return i===void 0?Ht(t,r,{code:"not_found",detail:"The requested MCP route does not expose downstream OAuth."}):i}n(_h,"readScopedDownstreamOAuthConfig");function wh(e){return e.path==="/.well-known/oauth-authorization-server/:routePath*"||e.path==="/.well-known/oauth-protected-resource/:routePath*"||e.path==="/oauth/authorize/:routePath*"}n(wh,"routeUsesScopedOAuthConfig");function Qs(e,t,r){return async(o,a)=>{if(a.log.setLogProperties?.({requestId:a.requestId}),r){let u=await r(o,a);if(u instanceof Response)return u;u&&Wn(a,u)}let i=o.method==="OPTIONS",c=Date.now();i||a.log.info({event:`${e}_received`,method:o.method},`MCP gateway: ${e} received`);let s=await t(o,a);return i||a.log.info({event:`${e}_responded`,status:s.status,durationMs:Date.now()-c},`MCP gateway: ${e} responded`),s}}n(Qs,"wrapInternalHandler");function ec(e,t,r,o){e.addPluginRoute({path:ch(t,r),methods:t.methods,handler:o,processors:[jn],corsPolicy:t.corsPolicy??"none"})}n(ec,"addInternalRoute");function rc(e,t){let r=fh(t),o=hh(r),a=r.connectionsById.size>0,i,c=n(()=>(i===void 0&&(i=yh(r)),i),"readSingletonOAuthConfig");if(o){G("plugin.mcp-gateway.downstream-oauth"),gh(r)&&G("plugin.mcp-gateway.downstream-oauth.id-jag");for(let s of ph){let u=wh(s)?(p,h)=>_h(r,p,h):c;ec(e,s,r.gateway,Qs(s.routeName,s.handler,u))}}if(a){G("plugin.mcp-gateway.upstream-auth");for(let s of r.connectionsById.values())G(`plugin.mcp-gateway.upstream-auth.${s.authMode}`);for(let s of mh)ec(e,s,r.gateway,Qs(s.routeName,s.handler))}}n(rc,"registerMcpGatewayInternalRoutes");var qn=class extends zn{static{n(this,"McpGatewayPlugin")}#e;constructor(t={}){super(),G("plugin.mcp-gateway"),this.#e=Vn(t)}registerRoutes(t){let r=t.parsedRouteData;r&&rc(t.router,{routes:r.routes,policies:r.policies,gateway:this.#e})}};var Rh=new TextDecoder;function bh(e){if(e)try{return JSON.parse(Rh.decode(e))}catch{return}}n(bh,"readBodyJson");function ge(e){return e&&typeof e=="object"?e:void 0}n(ge,"readRecord");function Ot(e,t){let r=ge(e)?.[t];return typeof r=="string"?r:void 0}n(Ot,"readStringProperty");function oc(e,t){let r=ge(e)?.[t];return typeof r=="number"?r:void 0}n(oc,"readNumberProperty");function nc(e,t){return oc(e,"code")??(t.status>=400?t.status:void 0)}n(nc,"readErrorCode");function ac(e){return Array.isArray(e)?e.map(ac).find(t=>t?.method):ge(e)}n(ac,"readJsonRpcMessage");function ic(e){let t=ac(bh(e)),r=typeof t?.method=="string"?t.method:"",o=t?.params;switch(r){case"tools/list":return{mcpMethod:r,capabilityType:"tool"};case"tools/call":return{mcpMethod:r,capabilityType:"tool",capabilityName:Ot(o,"name")};case"prompts/list":return{mcpMethod:r,capabilityType:"prompt"};case"prompts/get":return{mcpMethod:r,capabilityType:"prompt",capabilityName:Ot(o,"name")};case"resources/list":case"resources/templates/list":return{mcpMethod:r,capabilityType:"resource"};case"resources/read":{let a=Ot(o,"uri");return{mcpMethod:r,capabilityType:"resource",capabilityName:a,resourceUri:a}}default:return null}}n(ic,"buildBaseCapabilityInput");function sc(e){return e==="tools/list"||e==="prompts/list"||e==="resources/list"||e==="resources/templates/list"}n(sc,"isCapabilityListMethod");function Ih(e,t,r){let i=ge(r)?.[e==="resources/templates/list"?"resourceTemplates":t==="tool"?"tools":t==="prompt"?"prompts":"resources"];return Array.isArray(i)?i.length:void 0}n(Ih,"readItemCount");async function Ch(e){try{return await e.clone().json()}catch{return}}n(Ch,"readResponseJson");function cc(e){let t=ic(e);return!t||sc(t.mcpMethod)?null:{eventType:C.MCP_CAPABILITY_INVOKED,outcome:"success",...t}}n(cc,"buildCapabilityInvokedAnalyticsInput");async function dc(e,t){let r=ic(e);if(!r)return null;let o=ge(await Ch(t)),a=ge(o?.error),i=ge(a?.data),c=o?.result,s=r.mcpMethod==="tools/call"&&ge(c)?.isError===!0;if(ge(i?.connectRequired))return{eventType:C.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",...r,httpStatusCode:t.status,reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required",errorCode:oc(a,"code"),mcpErrorType:Ot(a,"message")};if(sc(r.mcpMethod)){let u=t.status>=400?void 0:Ih(r.mcpMethod,r.capabilityType,c);return{eventType:C.MCP_CAPABILITY_LISTED,outcome:t.status>=400||a?"failure":"success",...r,httpStatusCode:t.status,...t.status>=400||a?{reasonCode:"upstream_capability_list_failed",reasonClass:"upstream",errorType:"capability_list_error",errorCode:nc(a,t)}:{},...u===void 0?{}:{attributes:{itemCount:u}}}}return t.status>=400||a?{eventType:C.MCP_CAPABILITY_FAILED,outcome:"failure",...r,httpStatusCode:t.status,reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"capability_error",errorCode:nc(a,t),mcpErrorType:Ot(a,"message")}:{eventType:C.MCP_CAPABILITY_COMPLETED,outcome:s?"application_error":"success",...r,httpStatusCode:t.status,toolResultIsError:s,applicationError:s}}n(dc,"buildCapabilityFinalAnalyticsInput");var Sh={Allow:"POST"};async function vh(e){try{return await e.clone().arrayBuffer()}catch{return}}n(vh,"readRequestBody");function uc(e){try{let t=fo(e.route.path);return{virtualServerName:t.operationId,upstreamServerName:t.connection?.upstreamServerId,upstreamServerTitle:t.connection?.displayName,authProfileId:t.connection?.authProfileId,upstreamAuthMode:t.connection?.authMode}}catch{return{}}}n(uc,"readRouteAnalyticsFields");function lc(e){return Ao(e.user,e.url,e.headers)?.subjectId}n(lc,"readRequestSubjectId");function Ah(e){let t=cc(e.requestBody);t&&v(e.context,{...t,...uc(e.context),httpMethod:e.request.method,subjectId:lc(e.request),transport:"http"})}n(Ah,"emitCapabilityInvokedAnalytics");async function xh(e){let t=await dc(e.requestBody,e.response);t&&v(e.context,{...t,...uc(e.context),httpMethod:e.request.method,subjectId:lc(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}n(xh,"emitCapabilityFinalAnalytics");async function kh(e,t){if(G("handler.mcp-gateway-proxy"),e.method==="GET")return ke.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},Sh);let r=Date.now(),o=await vh(e);Ah({context:t,request:e,requestBody:o});let a=await $n(e,t);return await xh({context:t,request:e,requestBody:o,response:a,startedAt:r}),a}n(kh,"McpProxyHandler");export{Ic as McpAuth0OAuthInboundPolicy,Pr as McpCapabilityFilterInboundPolicy,pc as McpClerkOAuthInboundPolicy,mc as McpCognitoOAuthInboundPolicy,fc as McpEntraOAuthInboundPolicy,qn as McpGatewayPlugin,hc as McpGoogleOAuthInboundPolicy,gc as McpKeycloakOAuthInboundPolicy,yc as McpLogtoOAuthInboundPolicy,Cc as McpOAuthInboundPolicy,_c as McpOktaOAuthInboundPolicy,wc as McpOneLoginOAuthInboundPolicy,Rc as McpPingOAuthInboundPolicy,kh as McpProxyHandler,sn as McpTokenExchangeInboundPolicy,bc as McpWorkosOAuthInboundPolicy};
|
|
50
50
|
//# sourceMappingURL=index.js.map
|