@zuplo/cli 6.70.69 → 6.70.70

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.
Files changed (35) hide show
  1. package/node_modules/@zuplo/core/package.json +1 -1
  2. package/node_modules/@zuplo/graphql/package.json +1 -1
  3. package/node_modules/@zuplo/openapi-tools/package.json +1 -1
  4. package/node_modules/@zuplo/otel/package.json +1 -1
  5. package/node_modules/@zuplo/runtime/out/esm/{chunk-YLRLRHUN.js → chunk-MJPI3GFA.js} +93 -92
  6. package/node_modules/@zuplo/runtime/out/esm/chunk-MJPI3GFA.js.map +1 -0
  7. package/node_modules/@zuplo/runtime/out/esm/index.js +1 -1
  8. package/node_modules/@zuplo/runtime/out/esm/index.js.map +1 -1
  9. package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +7 -7
  10. package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js.map +1 -1
  11. package/node_modules/@zuplo/runtime/out/types/index.d.ts +323 -0
  12. package/node_modules/@zuplo/runtime/out/types/mcp-gateway/index.d.ts +3 -1
  13. package/node_modules/@zuplo/runtime/package.json +1 -1
  14. package/node_modules/protobufjs/dist/light/protobuf.js +18 -17
  15. package/node_modules/protobufjs/dist/light/protobuf.js.map +1 -1
  16. package/node_modules/protobufjs/dist/light/protobuf.min.js +3 -3
  17. package/node_modules/protobufjs/dist/light/protobuf.min.js.map +1 -1
  18. package/node_modules/protobufjs/dist/minimal/protobuf.js +3 -3
  19. package/node_modules/protobufjs/dist/minimal/protobuf.js.map +1 -1
  20. package/node_modules/protobufjs/dist/minimal/protobuf.min.js +3 -3
  21. package/node_modules/protobufjs/dist/minimal/protobuf.min.js.map +1 -1
  22. package/node_modules/protobufjs/dist/protobuf.js +18 -17
  23. package/node_modules/protobufjs/dist/protobuf.js.map +1 -1
  24. package/node_modules/protobufjs/dist/protobuf.min.js +3 -3
  25. package/node_modules/protobufjs/dist/protobuf.min.js.map +1 -1
  26. package/node_modules/protobufjs/package.json +1 -1
  27. package/node_modules/protobufjs/src/converter.js +5 -4
  28. package/node_modules/protobufjs/src/decoder.js +1 -1
  29. package/node_modules/protobufjs/src/service.js +5 -7
  30. package/node_modules/protobufjs/src/type.js +3 -1
  31. package/node_modules/protobufjs/src/util/minimal.js +1 -1
  32. package/node_modules/protobufjs/src/verifier.js +1 -1
  33. package/package.json +6 -6
  34. package/node_modules/@zuplo/runtime/out/esm/chunk-YLRLRHUN.js.map +0 -1
  35. /package/node_modules/@zuplo/runtime/out/esm/{chunk-YLRLRHUN.js.LEGAL.txt → chunk-MJPI3GFA.js.LEGAL.txt} +0 -0
@@ -22,11 +22,11 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$b as ot,$c as Uo,Ab as fc,Ac as ho,Bb as hc,Bc as se,Cb as gc,Cc as Ir,Db as yc,Dc as Sr,Eb as _c,Ec as go,Fb as wc,Fc as Gt,G as zn,Gb as Rc,Gc as Cr,H as l,Hb as bc,Hc as vr,I as jn,Ib as Ic,Ic as yo,J as yr,Jb as Sc,Jc as E,K as oe,Kb as Vn,Kc as _o,L as Hn,Lb as Yn,Lc as wo,M as _,Mb as Xn,Mc as Ar,N as fe,Nb as zt,Nc as Ro,O as qt,Ob as _r,Oc as bo,P as Bn,Pb as jt,Pc as xr,Q as Ln,Qb as Ht,Qc as Io,R as Nn,Rb as rt,Rc as xe,S as d,Sb as Qn,Sc as So,T as G,Tb as eo,Tc as it,Ub as to,Uc as Co,Vb as nt,Vc as Ft,Wb as ro,Wc as st,Xb as je,Xc as vo,Yb as no,Yc as Ao,Z as Jn,Zb as wr,Zc as xo,_b as oo,_c as ko,a as Et,ac as Bt,ad as To,bc as ao,bd as Po,cc as io,cd as $t,dc as so,dd as Eo,ec as co,ed as Oo,fc as Y,fd as b,gb as Gn,gc as j,gd as v,hb as F,hc as uo,hd as ce,i as Ae,ib as Fn,ic as lo,id as A,j as qn,jb as $n,jc as I,jd as qo,kb as P,kc as ie,kd as Cc,l as Mn,lb as Zn,lc as He,ld as vc,mb as g,mc as L,nb as De,nc as U,ob as ze,oc as po,p as Dn,pb as he,pc as _e,qb as ge,qc as mo,r as Ot,rb as Mt,rc as we,sb as Kn,sc as Rr,tb as Q,tc as Lt,ub as Wn,uc as br,vb as ae,vc as Nt,wb as w,wc as at,xb as Dt,xc as Be,yb as B,yc as fo,zb as ye,zc as Jt}from"../chunk-YLRLRHUN.js";import"../chunk-JRXZBVXH.js";import{a as S}from"../chunk-GEVKFSKR.js";import{$ as V,a as n,aa as f,ba as H,ca as On,da as Pt}from"../chunk-ZIKV2LUM.js";G();function Ac(e){let t=Ht.safeParse(e);return t.success?t.data.id:void 0}n(Ac,"parseJsonRpcRequestId");function Mo(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Ac(t)}catch{return}}n(Mo,"readJsonRpcRequestIdFromBody");function Zt(e){return Qn.parse({jsonrpc:jt,...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(Zt,"jsonRpcErrorResponse");function Do(e){return new to([eo.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Do,"urlElicitationRequiredError");var Kt=d.record(d.string(),d.unknown()),xc=d.record(d.string(),d.unknown()),kc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),annotations:xc.optional(),_meta:Kt.optional()}).strict(),Uc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),_meta:Kt.optional()}).strict(),Tc=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:Kt.optional()}).strict(),Pc=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:Kt.optional()}).strict(),Ec=d.array(d.union([d.string(),kc])),Oc=d.array(d.union([d.string(),Uc])),qc=d.array(d.union([d.string(),Tc])),Mc=d.array(d.union([d.string(),Pc])),Dc=d.object({tools:Ec.optional(),prompts:Oc.optional(),resources:qc.optional(),resourceTemplates:Mc.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 zc(e,t){return Fn(Dc,e,`MCP capability filter policy "${t}"`)}n(zc,"parseMcpCapabilityFilterOptions");function N(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(N,"isRecord");function jc(e,t){if(!N(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(jc,"readParamString");function Tr(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(Tr,"readRequestId");function Bo(e){return e===void 0?void 0:JSON.stringify(e)}n(Bo,"requestIdKey");function Hc(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=Jc(i,r.itemProperty);c!==void 0&&a.set(c.key,c)}t[r.option]=a}return t}n(Hc,"buildProjectionMaps");function Pr(e){return Ur.find(t=>t.listMethod===e)}n(Pr,"findListRule");function Bc(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(Bc,"shouldFilterListResponses");function Lc(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=jc(e.request.params,o.paramProperty);if(a!==void 0&&!r.has(a))return{id:Tr(e.request)}}}}n(Lc,"findDisallowedDirectAccess");function Nc(e){return Response.json(Zt({id:e,error:{code:rt.MethodNotFound,message:"Method not found"}}))}n(Nc,"methodNotFoundResponse");function Jc(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(Jc,"buildProjection");function zo(e){let t=e.base[e.property],r=e.overlay[e.property];return N(r)?N(t)?{...t,...r}:r:t}n(zo,"mergeRecordProperty");function Gc(e,t){let r={...e,...t.overlay},o=zo({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let a=zo({base:e,overlay:t.overlay,property:"_meta"});return a!==void 0&&(r._meta=a),r}n(Gc,"applyProjection");function jo(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?[]:[Gc(i,s)]})}}}n(jo,"filterAndProjectItems");function Fc(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=Bo(a);o!==void 0&&i!==void 0&&t.set(i,o)}return t}n(Fc,"buildListRulesByResponseId");function $c(e){if(Array.isArray(e.responseBody)){let o=Fc(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(a=>{if(!N(a)||"error"in a)return a;let i=Bo(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:jo(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:jo(e.responseBody,t,r)}n($c,"filterJsonRpcResponse");async function Ho(e){return e.clone().json()}n(Ho,"readJson");function Zc(e){return e.headers.get("content-type")?.includes("json")??!1}n(Zc,"isJsonResponse");var kr=class extends Ot{static{n(this,"McpCapabilityFilterInboundPolicy")}#e;constructor(t,r){let o=zc(t,r);super(o,r),this.#e=Hc(o)}async handler(t,r){Et("policy.inbound.mcp-capability-filter");let o;try{o=await Ho(t)}catch{return t}let a=Array.isArray(o)?o:[o];for(let i of a){if(!N(i))continue;let c=Lc({request:i,projectionMaps:this.#e});if(c!==void 0)return Nc(c.id)}return Bc({requests:a,projectionMaps:this.#e})&&r.addResponseSendingHook(async i=>{if(!Zc(i))return i;let c;try{c=await Ho(i)}catch{return i}let s=$c({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 Kc(e){return(await Er).getRandomValues(new Uint8Array(e))}n(Kc,"getRandomValues");async function Wc(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let a=await Kc(e-o.length);for(let i of a)i<r&&(o+=t[i%t.length])}return o}n(Wc,"random");async function Vc(e){return await Wc(e)}n(Vc,"generateVerifier");async function Yc(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(Yc,"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 Vc(e),r=await Yc(t);return{code_verifier:t,code_challenge:r}}n(Or,"pkceChallenge");G();var D=jn().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Ln.custom,message:"URL must be parseable",fatal:!0}),zn}).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"}),Wt=qt({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:oe().optional(),authorization_details_types_supported:_(l()).optional(),dpop_signing_alg_values_supported:_(l()).optional(),dpop_bound_access_tokens_required:oe().optional()}),ct=qt({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:oe().optional()}),Xc=qt({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:oe().optional(),request_parameter_supported:oe().optional(),request_uri_parameter_supported:oe().optional(),require_request_uri_registration:oe().optional(),op_policy_uri:D.optional(),op_tos_uri:D.optional(),client_id_metadata_document_supported:oe().optional()}),Vt=fe({...Xc.shape,...ct.pick({code_challenge_methods_supported:!0}).shape}),Le=fe({access_token:l(),id_token:l().optional(),token_type:l(),expires_in:Nn.number().optional(),scope:l().optional(),refresh_token:l().optional()}).strip(),No=fe({error:l(),error_description:l().optional(),error_uri:l().optional()}),Lo=D.optional().or(Bn("").transform(()=>{})),Qc=fe({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:Lo,scope:l().optional(),contacts:_(l()).optional(),tos_uri:Lo,policy_uri:l().optional(),jwks_uri:D.optional(),jwks:Hn().optional(),software_id:l().optional(),software_version:l().optional(),software_statement:l().optional()}).strip(),Yt=fe({client_id:l(),client_secret:l().optional(),client_id_issued_at:yr().optional(),client_secret_expires_at:yr().optional()}).strip(),dt=Qc.merge(Yt),Mh=fe({error:l(),error_description:l().optional()}).strip(),Dh=fe({token:l(),token_type_hint:l().optional()}).strip();function Jo(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(Jo,"resourceUrlFromServerUrl");function Go({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(Go,"checkResourceAllowed");var x=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}},ut=class extends x{static{n(this,"InvalidRequestError")}};ut.errorCode="invalid_request";var ke=class extends x{static{n(this,"InvalidClientError")}};ke.errorCode="invalid_client";var Ue=class extends x{static{n(this,"InvalidGrantError")}};Ue.errorCode="invalid_grant";var Te=class extends x{static{n(this,"UnauthorizedClientError")}};Te.errorCode="unauthorized_client";var lt=class extends x{static{n(this,"UnsupportedGrantTypeError")}};lt.errorCode="unsupported_grant_type";var pt=class extends x{static{n(this,"InvalidScopeError")}};pt.errorCode="invalid_scope";var mt=class extends x{static{n(this,"AccessDeniedError")}};mt.errorCode="access_denied";var de=class extends x{static{n(this,"ServerError")}};de.errorCode="server_error";var ft=class extends x{static{n(this,"TemporarilyUnavailableError")}};ft.errorCode="temporarily_unavailable";var ht=class extends x{static{n(this,"UnsupportedResponseTypeError")}};ht.errorCode="unsupported_response_type";var gt=class extends x{static{n(this,"UnsupportedTokenTypeError")}};gt.errorCode="unsupported_token_type";var yt=class extends x{static{n(this,"InvalidTokenError")}};yt.errorCode="invalid_token";var _t=class extends x{static{n(this,"MethodNotAllowedError")}};_t.errorCode="method_not_allowed";var wt=class extends x{static{n(this,"TooManyRequestsError")}};wt.errorCode="too_many_requests";var Pe=class extends x{static{n(this,"InvalidClientMetadataError")}};Pe.errorCode="invalid_client_metadata";var Rt=class extends x{static{n(this,"InsufficientScopeError")}};Rt.errorCode="insufficient_scope";var bt=class extends x{static{n(this,"InvalidTargetError")}};bt.errorCode="invalid_target";var Fo={[ut.errorCode]:ut,[ke.errorCode]:ke,[Ue.errorCode]:Ue,[Te.errorCode]:Te,[lt.errorCode]:lt,[pt.errorCode]:pt,[mt.errorCode]:mt,[de.errorCode]:de,[ft.errorCode]:ft,[ht.errorCode]:ht,[gt.errorCode]:gt,[yt.errorCode]:yt,[_t.errorCode]:_t,[wt.errorCode]:wt,[Pe.errorCode]:Pe,[Rt.errorCode]:Rt,[bt.errorCode]:bt};function ed(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(ed,"isClientAuthMethod");var qr="code",Mr="S256";function td(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&ed(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(td,"selectClientAuthMethod");function rd(e,t,r,o){let{client_id:a,client_secret:i}=t;switch(e){case"client_secret_basic":nd(a,i,r);return;case"client_secret_post":od(a,i,o);return;case"none":ad(a,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(rd,"applyClientAuthentication");function nd(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(nd,"applyBasicAuth");function od(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(od,"applyPostAuth");function ad(e,t){t.set("client_id",e)}n(ad,"applyPublicAuth");async function Zo(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=No.parse(JSON.parse(r)),{error:a,error_description:i,error_uri:c}=o,s=Fo[a]||de;return new s(i||"",c)}catch(o){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new de(a)}}n(Zo,"parseErrorResponse");async function jr(e,t){try{return await Dr(e,t)}catch(r){if(r instanceof ke||r instanceof Te)return await e.invalidateCredentials?.("all"),await Dr(e,t);if(r instanceof Ue)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 Vo(u,{fetchFn:i}),!s)try{s=await Wo(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 ld(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 id(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 Pe(`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 En=await gd(u,{metadata:p,clientMetadata:e.clientMetadata,scope:T,fetchFn:i});await e.saveClientInformation(En),R=En}}let q=!e.redirectUrl;if(r!==void 0||q){let M=await hd(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 fd(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 x)||M instanceof de))throw M}let re=e.state?await e.state():void 0,{authorizationUrl:tt,codeVerifier:ne}=await pd(u,{metadata:p,clientInformation:R,state:re,redirectUrl:e.redirectUrl,scope:T,resource:y});return await e.saveCodeVerifier(ne),await e.redirectToAuthorization(tt),"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 id(e,t,r){let o=Jo(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!Go({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(id,"selectResourceURL");function Ko(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(Ko,"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 Wo(e,t,r=fetch){let o=await dd(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 Wt.parse(await o.json())}n(Wo,"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 sd(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(sd,"buildWellKnownPath");async function $o(e,t,r=fetch){return await Br(e,{"MCP-Protocol-Version":t},r)}n($o,"tryMetadataDiscovery");function cd(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(cd,"shouldAttemptFallback");async function dd(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=sd(t,a.pathname);c=new URL(u,o?.metadataServerUrl??a),c.search=a.search}let s=await $o(c,i,r);if(!o?.metadataUrl&&cd(s,a.pathname)){let u=new URL(`/.well-known/${t}`,a);s=await $o(u,i,r)}return s}n(dd,"discoverMetadataWithFallback");function ud(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(ud,"buildDiscoveryUrls");async function Vo(e,{fetchFn:t=fetch,protocolVersion:r=_r}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},a=ud(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"?ct.parse(await s.json()):Vt.parse(await s.json())}}}n(Vo,"discoverAuthorizationServerMetadata");async function ld(e,t){let r,o;try{r=await Wo(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 Vo(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:a,resourceMetadata:r}}n(ld,"discoverOAuthServerInfo");async function pd(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(pd,"startAuthorization");function md(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(md,"prepareAuthorizationCodeRequest");async function Yo(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=td(o,h);rd(y,o,u,r)}let p=await(c??fetch)(s,{method:"POST",headers:u,body:r});if(!p.ok)throw await Zo(p);return Le.parse(await p.json())}n(Yo,"executeTokenRequest");async function fd(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 Yo(e,{metadata:t,tokenRequestParams:s,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:c});return{refresh_token:o,...u}}n(fd,"refreshAuthorization");async function hd(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=md(a,p,e.redirectUrl)}let u=await e.clientInformation();return Yo(t,{metadata:r,tokenRequestParams:s,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:i})}n(hd,"fetchToken");async function gd(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 Zo(c);return dt.parse(await c.json())}n(gd,"registerClient");var Lr="zuplo.com",yd=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),_d=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Xo(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(Xo,"s2FaviconHref");function wd(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(wd,"strictFaviconHref");var Xt=Xo(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")?Xo(Lr):wd(e)}n(Nr,"resolveIconHref");function Rd(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(Rd,"hostnameFromHost");function bd(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(bd,"isLocalOrAddressHost");function Id(e){let t=Rd(e).toLowerCase().replace(/\.$/,"");if(bd(t)||_d.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=yd.has(o)?3:2;return r.slice(-a).join(".")}n(Id,"inferFaviconDomain");function Jr(e){return{src:Nr(Id(e)),mimeType:"image/png",sizes:["128x128"]}}n(Jr,"resolveMcpFaviconIcon");function Qt(e){try{return Jr(new URL(e).host)}catch{return}}n(Qt,"resolveMcpFaviconIconFromUrl");function Re(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(Re,"getUpstreamServerConfig");function er(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(er,"getUpstreamAuthConfig");function Ne(e,t){let r=er({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(Ne,"requireUpstreamOAuthConfig");function Qo(e,t){let r=er({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(Qo,"requireUpstreamIdJagConfig");function ea(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(ea,"mergeAbortSignals");async function Sd(e){try{await e.cancel()}catch{}}n(Sd,"cancelReader");async function tr(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 Sd(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(tr,"readBoundedByteStream");var Cd=2,vd=1024*1024,Ad=1e4,xd=new Set([301,302,303,307,308]),kd=["authorization","proxy-authorization","cookie","cookie2"];function Gr(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Gr,"readRequestUrl");function Je(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(Je,"readRequestMethod");function Ud(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(Ud,"assertContentLengthWithinLimit");async function Td(e,t,r){return Ud(e,t,r),tr(e.body,{maxBytes:t,createLimitError:n(()=>new f({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}}),"createLimitError")})}n(Td,"readBoundedResponseBody");function Pd(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(Pd,"responseFromBufferedBody");function Ed(e,t){if(!xd.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(Ed,"resolveRedirectUrl");function ta(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(ta,"validateOutboundUrl");function Od(e,t){throw e instanceof f&&Mt(e.extensionMembers?.[g])?e:new f({message:"Outbound fetch failed.",extensionMembers:{[g]:t}},{cause:e})}n(Od,"normalizeFetchError");function It(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(It,"logOutboundFailure");async function qd(e,t,r,o,a,i,c){let s=Je(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";It(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:s,host:U(i),error:u,extra:{abortReason:c()}}),Od(u,a)}}n(qd,"fetchWithNormalizedError");function Md(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(Md,"assertRedirectAllowed");function Dd(e,t){let r=new Headers(e);for(let o of kd)r.delete(o);for(let o of t)r.delete(o);return r}n(Dd,"stripCrossOriginHeaders");function zd(e,t,r,o,a){let i={...e,method:t,redirect:"manual",signal:r};return o&&(i.headers=Dd(e.headers,a)),i}n(zd,"buildRedirectInit");function jd(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(jd,"buildInitialRequestInit");function Hd(e){let t=Je(e.currentInput,e.currentInit);Md({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=ta(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:zd(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(Hd,"followRedirect");async function Fr(e,t,r){let o=r.problemCode??"invalid_request",a=r.maxRedirects??Cd,i=r.maxResponseBytes??vd,c=r.timeoutMs??Ad,s=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,h=new AbortController,y=ea(h,t.signal),T=!1,R=setTimeout(()=>{T=!0,h.abort()},c),q=e,O=jd(e,t,h.signal),re;try{re=ta(Gr(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(ne){throw It(p,{event:"outbound_url_blocked",problemCode:o,method:Je(e,t),host:U(Gr(e)),error:ne}),clearTimeout(R),y?.(),ne}let tt=0;try{for(;;){let ne=await qd(p,s,q,O,o,re,()=>T?`timeout_after_${c}ms`:void 0),M=Ed(ne,re);if(M!==void 0)try{let z=Hd({currentInput:q,currentInit:O,currentUrl:re,redirectUrl:M,redirects:tt,maxRedirects:a,problemCode:o,validateUrl:r.validateUrl,signal:h.signal,additionalCrossOriginStrippedHeaders:u});q=z.currentInput,O=z.currentInit,re=z.currentUrl,tt=z.redirects;continue}catch(z){throw It(p,{event:"outbound_redirect_blocked",problemCode:o,method:Je(q,O),host:U(re),error:z,extra:{redirects:tt,maxRedirects:a,redirectTargetHost:U(M)}}),z}try{return Pd(ne,await Td(ne,i,o))}catch(z){throw It(p,{event:"outbound_response_size_exceeded",problemCode:o,method:Je(q,O),host:U(re),error:z,extra:{maxResponseBytes:i,status:ne.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 It(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Je(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 ra(e,t={},r={}){return Fr(e,t,{...r,validateUrl:it})}n(ra,"fetchConfiguredOutbound");function na(e,t={},r={}){return St(e,t,{...r,validateUrl:it})}n(na,"fetchConfiguredOutboundJson");function rr(e,t={},r={}){return St(e,t,{...r,validateUrl:Co})}n(rr,"fetchIdentityProviderJson");function oa(e,t={},r={}){return St(e,t,{...r,validateUrl:Ft})}n(oa,"fetchCimdClientMetadataJson");function aa(e,t={},r={}){return St(e,t,{...r,validateUrl:st})}n(aa,"fetchCimdClientJwksJson");G();import{errors as pa,jwtVerify as ma,SignJWT as fa}from"jose";var J="zuplo-mcp-gateway",$=J,Z="HS256";import{base64url as Bd}from"jose";var Ld=new TextEncoder,Nd="MCP gateway could not initialize secure key material.",Jd=32,ia=new Map,sa=new Map,Gd;function Fd(){return Gd??On.instance.authPrivateKey}n(Fd,"readAuthPrivateKey");function ca(e){return new V(Nd,e===void 0?void 0:{cause:e})}n(ca,"createGeneratedKeyMaterialError");function da(e,t){let r=Bd.decode(t);if(r.byteLength!==Jd)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(da,"decodeJwkKeyField");function $d(e){let t=Fd();if(!t)throw ca();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=da("d",r.d);da("x",r.x);let a=Ld.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 ca(r)}}n($d,"decodeGeneratedKeyMaterial");function Zd(e){let t=ia.get(e);return t||(t=$d(e),ia.set(e,t)),t}n(Zd,"getMasterKeyMaterial");async function ee(e){let t=sa.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Zd(e.keyMaterialPurpose));return sa.set(e.purpose,r),r}n(ee,"readCachedDerivedKey");var Kd="SHA-256";var Wd="zuplo-mcp-gateway:",Vd=new TextEncoder,ua=new WeakMap;async function be(e,t){let r=ua.get(e);r||(r=new Map,ua.set(e,r));let o=r.get(t);if(o)return o;let a=await Yd(e,t);return r.set(t,a),a}n(be,"deriveGatewaySigningKey");async function Yd(e,t){let r=la(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=Vd.encode(`${Wd}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:Kd,salt:new Uint8Array,info:la(a)},o,32*8);return new Uint8Array(i)}n(Yd,"hkdfExpand");function la(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(la,"copyToArrayBuffer");var ha=15*60,Xd=15*60,Qd=oo.extend({id:Uo}),eu=Qd.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ga=wr.extend({id:To,purpose:d.literal("browser_connect")}),tu=wr.extend({purpose:d.literal("browser_connect")}),ru=ga.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ya=ha*1e3;async function _a(){return ee({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>be(e,"oauth-state"),"derive")})}n(_a,"getOAuthStateKey");async function wa(){return ee({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>be(e,"browser-connect"),"derive")})}n(wa,"getBrowserConnectKey");async function Ra(e){let t=Math.floor(Date.now()/1e3)+ha;return new fa(e).setProtectedHeader({alg:Z,typ:"JWT"}).setIssuer(J).setAudience($).setIssuedAt().setExpirationTime(t).sign(await _a())}n(Ra,"signOAuthState");async function nr(e){try{let{payload:t}=await ma(e,await _a(),{algorithms:[Z],issuer:J,audience:$});return eu.parse(t)}catch(t){throw t instanceof pa.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(nr,"verifyOAuthState");async function ba(e){let t=Math.floor(Date.now()/1e3)+Xd,r=tu.parse(e),o=ga.parse({...r,id:Oo()});return new fa(o).setProtectedHeader({alg:Z,typ:"JWT"}).setIssuer(J).setAudience($).setIssuedAt().setExpirationTime(t).sign(await wa())}n(ba,"signBrowserConnectTicket");async function Ia(e){try{let{payload:t}=await ma(e,await wa(),{algorithms:[Z],issuer:J,audience:$});return ru.parse(t)}catch(t){throw t instanceof pa.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(Ia,"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 nu(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(nu,"buildConnectRequiredMessage");async function ou(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 ba({...ot(e),purpose:"browser_connect"})),r.toString()}n(ou,"buildGatewayBrowserTicketUrl");function au(e){return j().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(au,"buildGatewayConnectPath");async function $r(e){return ou({...e,path:au(e.upstreamServerId),redirect:!0})}n($r,"buildGatewayConnectUrl");async function or(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:nu(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(or,"buildRedirectConnectRequiredResponse");function Ca(e){return iu({...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 iu(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(iu,"buildAdminSetupRequiredResponse");G();var va=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function su(e,t){return e&&e.length>0?e.join(t):void 0}n(su,"joinOAuthScopes");function cu(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of va)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(cu,"sanitizeAuthorizationServerMetadata");function Zr(e){let t=cu(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(Zr,"sanitizeOAuthDiscoveryState");function Aa(e){let t=new URL(e);for(let r of va){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(Aa,"normalizeDuplicateSingletonAuthorizationRequestParams");function ar(e){let t=new URL(e);return F(t)&&Gn(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(ar,"normalizeLoopbackOAuthRedirectUri");function xa(e){return su(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(xa,"readProtectedResourceMetadataScope");function du(e){return`Zuplo MCP Gateway - ${e}`}n(du,"buildGatewayOAuthClientName");function uu(e,t){return e&&e.length>0?e.join(t):void 0}n(uu,"joinOAuthScopeList");function lu(e){if(e.clientRegistration.mode!=="auto")return uu(e.scopes,e.scopeDelimiter)}n(lu,"readPublicClientMetadataScope");function Kr(e){return new URL(j().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Kr,"buildOAuthClientMetadataDocumentUrl");function Wr(e){let t=Re(e.upstreamServerId);return{client_name:du(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(Wr,"buildGatewayOAuthClientMetadata");function ka(e,t,r){let o=Ne(t,r),a=lu(o);return{client_id:Kr({origin:e,upstreamServerId:t}),...Wr({origin:e,upstreamServerId:t,redirectUri:ar(new URL(o.redirectPath,e)).toString(),scope:a})}}n(ka,"buildOAuthClientMetadataDocument");G();import{base64url as Ie}from"jose";var pu="SHA-256",Fe="AES-GCM",mu=12,Yr="zuplo-secret",Xr=1,Ua="generated:auth_private_key:token-encryption",fu=d.object({version:d.literal(Xr),keyId:d.literal(Ua),algorithm:d.literal(Fe),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();function Ge(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(Ge,"copyToArrayBuffer");async function Vr(){return ee({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(pu,Ge(e));return crypto.subtle.importKey("raw",t,{name:Fe},!1,["encrypt","decrypt"])},"derive")})}n(Vr,"getEncryptionKey");function Ta(e){return Ge(new TextEncoder().encode(`${Yr}:v${e.version}:${e.keyId}`))}n(Ta,"getAssociatedData");function hu(e){return`${Yr}:v${e.version}:${Ie.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(hu,"encodeEnvelope");function gu(e){let t=`${Yr}:v${Xr}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(Ie.decode(r));return fu.parse(JSON.parse(o))}n(gu,"decodeEnvelope");async function ue(e){let t=await Vr(),r=crypto.getRandomValues(new Uint8Array(mu)),o={version:Xr,keyId:Ua},a=await crypto.subtle.encrypt({name:Fe,iv:r,additionalData:Ta(o)},t,new TextEncoder().encode(e));return hu({...o,algorithm:Fe,iv:Ie.encode(r),ciphertext:Ie.encode(new Uint8Array(a))})}n(ue,"encryptSecret");async function Se(e){let t=gu(e);if(t){let c=await Vr(),s=await crypto.subtle.decrypt({name:Fe,iv:Ge(Ie.decode(t.iv)),additionalData:Ta(t)},c,Ge(Ie.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 Vr(),i=await crypto.subtle.decrypt({name:Fe,iv:Ge(Ie.decode(r))},a,Ge(Ie.decode(o)));return new TextDecoder().decode(i)}n(Se,"decryptSecret");var yu=d.union([dt,Yt]),Pa=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:Wt.optional(),authorizationServerMetadata:d.union([ct,Vt]).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 Jt.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 Ea(e){if(e!==void 0)return ue(JSON.stringify(e))}n(Ea,"encryptJson");async function Oa(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(Oa,"decryptJson");function Su(e){if(e===void 0)return;e=Zr(e);let t={authorizationServerUrl:e.authorizationServerUrl};return e.resourceMetadataUrl!==void 0&&(t.resourceMetadataUrl=e.resourceMetadataUrl),e.resourceMetadata!==void 0&&(t.resourceMetadata=e.resourceMetadata),e.authorizationServerMetadata!==void 0&&(t.authorizationServerMetadata=e.authorizationServerMetadata),t}n(Su,"toOAuthDiscoveryState");function Cu(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(Cu,"clientInformationAllowsRedirectUri");function vu(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(vu,"clientInformationMatchesCurrentClientMetadataUrl");function Au(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(Au,"isUrlBasedClientInformation");function xu(e,t){return t===void 0?e:{...e,scope:t}}n(xu,"applyOAuthClientMetadataScope");function qa(e,t){return xa({state:e,delimiter:t})}n(qa,"readResourceMetadataScope");function ku(e,t){return e&&e.length>0?e.join(t):void 0}n(ku,"joinOAuthScopeList");function Uu(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 dt.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(Uu,"buildManualOAuthClientInformation");function Tu(e,t){let r=Kr({origin:new URL(t).origin,upstreamServerId:e});return Hr(r)?r:void 0}n(Tu,"buildClientMetadataUrl");function Ma(e){for(let t of e)if(t!==void 0)return t}n(Ma,"firstDefined");function Pu(e){let t=Ne(e.target.upstreamServerId,e.target.authProfileId),r=ku(t.scopes,t.scopeDelimiter),o=Wr({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:Uu({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let a=Tu(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 Ma([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(Eu,"readEncryptedClientInformation");function Ou(e){return Ma([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}n(Ou,"readEncryptedDiscoveryState");var Ee=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredScope;scopeDelimiter;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;connection;pendingState;encryptedClientInformation;encryptedDiscoveryState;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),this.encryptedDiscoveryState=Ou(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return xu(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return Ra({id:t.id,...ot({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,_e()?.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"),!Au({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Ea(t),await this.syncPendingState(!1)))}async discoveryState(){return this.loadPersistedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=Zr(Pa.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,_e()?.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=qa(r,this.scopeDelimiter),this.encryptedDiscoveryState=await Ea(r),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Le.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,a=r.refresh_token?await ue(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:Le.parse({...r,refresh_token:await Se(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let i={id:this.connection?.id??$t(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await ue(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),_e()?.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: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.encryptedDiscoveryState=void 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:Eo(),...ot({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()+ya)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await 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,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await Oa(this.encryptedClientInformation,yu)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&(!Cu(t,this.redirectUriValue)||!vu({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=Yt.parse({client_id:this.clientMetadataUrl})),this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async loadPersistedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;try{this.cachedDiscoveryState=Su(await Oa(this.encryptedDiscoveryState,Pa))}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1)}return this.discoveryStateLoaded=!0,this.inferredScope=qa(this.cachedDiscoveryState,this.scopeDelimiter),this.cachedDiscoveryState}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=Le.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&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var qu=3e4,Mu=256*1024,Du=2;function zu(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(zu,"hasUsableAccessToken");var ju="does not support dynamic client registration",Hu=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],Bu=["HTTP 403 Forbidden","Access Denied","permission to access"];function Lu(e){return e instanceof Error&&e.message.includes(ju)}n(Lu,"isDynamicClientRegistrationUnsupported");function Nu(e){return e instanceof Error&&Hu.some(t=>e.message.includes(t))}n(Nu,"isProtectedResourceMetadataUnavailable");function Ju(e){return e instanceof Error&&Bu.some(t=>e.message.includes(t))}n(Ju,"isUpstreamProviderAccessDenied");function Gu(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(Gu,"mapUpstreamOAuthSetupError");function Fu(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(Fu,"readOAuthFetchRequest");function $u(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n($u,"responseLooksJson");function Zu(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(Zu,"responseLooksHtml");function Ku(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",[he]:e.response.status,[De]:r,[ge]:e.request.url.toString(),[ze]:e.body}})}n(Ku,"throwUpstreamHtmlError");function Wu(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(Wu,"readUpstreamOAuthErrorBody");function Vu(e){let{error:t,errorDescription:r}=Wu(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(Vu,"logUpstreamOAuthHttpError");function Da(e){return async(t,r)=>{let o=Fu(t),a=_e(),i=Date.now(),c=await ra(t,r,{maxRedirects:Du,maxResponseBytes:Mu,problemCode:"upstream_token_exchange_failed",timeoutMs:qu}),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||Vu({log:a,upstreamServerId:e,request:o,response:c,body:s}),!c.ok&&Zu(c,s)&&Ku({upstreamServerId:e,request:o,response:c,body:s}),!$u(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(Da,"createUpstreamOAuthFetch");function za(e){_e()?.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(za,"logUpstreamOAuthFlowStarted");function ja(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),_e()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(ja,"logUpstreamOAuthFlowFailed");async function Ha(e,t){e.applyChallengeScope(t.requestedScope),za({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Da(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),await jr(e,r)}catch(r){ja({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=Gu({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(Ha,"runUpstreamOAuth");async function Yu(e,t){e.applyChallengeScope(t.requestedScope),za({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Da(t.upstreamServerId)};t.requestedScope!==void 0&&(r.scope=t.requestedScope);try{return await jr(e,r)}catch(o){throw ja({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:o}),o}}n(Yu,"exchangeUpstreamAuthorizationCode");async function Ba(e,t){let r=await Ha(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(Ba,"requireUpstreamAuthorizationRedirect");async function La(e){if(!e.forceRefresh&&zu(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await Ha(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}});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 rl({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(La,"authorizeUpstreamOAuthSession");async function Xu(e){let t=await nr(e.stateToken),r=await b().consumeUpstreamOAuthState({id:t.id,now:I(new Date)}),o=Qu(r);return el({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),tl(o),o}n(Xu,"consumeStoredCallbackState");function Qu(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(Qu,"readConsumedCallbackState");function el(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(el,"assertStoredCallbackStateMatches");function tl(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new f({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}})}n(tl,"assertStoredCallbackStateFresh");async function rl(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),or(t)}n(rl,"buildOAuthConnectRequiredResponse");async function Na(e){let t=await Xu({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Bt(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 Ee(a),c=await Yu(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(Na,"finishUpstreamOAuthCallback");G();import{importPKCS8 as nl,SignJWT as ol}from"jose";var Ga=1e4,Fa=64*1024,$a=2,al=300,K=d.string().min(1),il=d.object({access_token:K,issued_token_type:K,token_type:K,expires_in:d.number().int().positive().optional(),scope:K.optional()}).passthrough(),sl=d.object({id_token:K,token_type:K.optional(),expires_in:d.number().int().positive().optional(),refresh_token:K.optional(),scope:K.optional()}).passthrough(),cl=d.object({access_token:K,token_type:K,expires_in:d.number().int().positive().optional(),scope:K.optional(),resource:K.optional(),refresh_token:K.optional()}).passthrough();function Ja(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(Ja,"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=Ja(e.clientAuth.clientId),r=Ja(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",Nt),e.form.set("client_assertion",await ul({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}n(ll,"appendClientAuthentication");async function Qr(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(Qr,"buildFormRequest");function Za(e){return(t,r)=>rr(t,r,{context:e,maxRedirects:$a,maxResponseBytes:Fa,problemCode:"upstream_token_exchange_failed",timeoutMs:Ga})}n(Za,"defaultIdpFetchJson");function pl(e){return(t,r)=>na(t,r,{context:e,maxRedirects:$a,maxResponseBytes:Fa,problemCode:"upstream_token_exchange_failed",timeoutMs:Ga})}n(pl,"defaultResourceAsFetchJson");function Ct(e){let t={[g]:e.code,[ge]:e.tokenUrl};return e.response!==void 0&&(t[he]=e.response.status),new f({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}n(Ct,"runtimeError");function en(e){if(!e.response.ok)throw Ct({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(en,"assertTokenEndpointSucceeded");function ml(e){let t=sl.safeParse(e.json);if(!t.success)throw Ct({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 Ct({code:"upstream_token_response_invalid",message:"IdP token exchange returned an invalid ID-JAG response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});if(t.data.issued_token_type!==br||t.data.token_type.toLowerCase()!=="n_a")throw Ct({code:"upstream_token_response_invalid",message:"IdP token exchange response did not contain an ID-JAG assertion.",tokenUrl:e.tokenUrl,response:e.response});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 Ct({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 Ka(e){let t=new URLSearchParams({grant_type:Lt,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??Za(e.context),{response:o,json:a}=await r(e.idp.tokenUrl,await Qr({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return en({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),fl({json:a,response:o,tokenUrl:e.idp.tokenUrl})}n(Ka,"requestIdJag");async function Wa(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??Za(e.context),{response:o,json:a}=await r(e.idp.tokenUrl,await Qr({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return en({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),ml({json:a,response:o,tokenUrl:e.idp.tokenUrl})}n(Wa,"refreshIdpSubjectToken");async function Va(e){let t=new URLSearchParams({grant_type:we,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 Qr({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return en({response:o,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),hl({json:a,response:o,tokenUrl:e.resourceAs.tokenUrl})}n(Va,"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===Be)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!==Be)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await Wa({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});return r.refreshToken===void 0?{connection:e.connection,subjectToken:r.idToken,subjectTokenType:at}:{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 ue(r.refreshToken),idpSubjectTokenType:Be,idpSubjectTokenExpiresAt:void 0}}),subjectToken:r.idToken,subjectTokenType:at}}n(wl,"resolveIdJagSubjectToken");async function Ya(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=Re(e.upstreamServerId),i=Qo(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 Ka({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 Va({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 ue(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(Ya,"authorizeUpstreamIdJagRequest");function Rl(e){return ar(new URL(e.callbackPath,P(e.requestUrl,e.requestHeaders))).toString()}n(Rl,"buildGatewayOAuthRedirectUri");async function Xa(e){let t=Re(e.upstreamServerId),r=Ne(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(Xa,"prepareUpstreamOAuthRequest");async function Qa(e){let t=await Xa(e),r=new Ee({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Ba(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Qa,"startUpstreamConnect");async function ei(e){let t=await Xa(e),r=new Ee({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return La({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(ei,"authorizeUpstreamRequest");async function $e(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return ei({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 Ya({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($e,"resolveUpstreamCredentialForRoute");async function ti(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 Qa({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(ti,"startUpstreamConnectForRequest");async function ri(e){let r=(await nr(e.callbackRequest.state)).authProfileId;if(er({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 Na({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:Re(e.callbackRequest.upstreamServerId)})}n(ri,"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 ni(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:ao(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(ni,"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 tn(e,t){switch(e){case"user":return je(t);case"shared":return no()}}n(tn,"buildOwnerForSubject");function Ze(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:tn("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:tn("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:tn("user",t),initiatedBySubjectId:t}}}n(Ze,"resolveRouteAuthForSubject");var Il=rt.InvalidRequest,Sl=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function Cl(e,t){return{credentialType:e.type,forceRefresh:t}}n(Cl,"buildCredentialResolvedAttributes");function vl(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(vl,"connectRequiredReasonCode");function oi(e){v(e.context,{eventType:S.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:Cl(e.credential,e.forceRefresh===!0)})}n(oi,"emitCredentialResolvedAnalyticsEvent");function ai(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(v(e.context,{eventType:S.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:S.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}v(e.context,{eventType:S.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:vl(e.payload.state),reasonClass:"auth",attributes:t})}n(ai,"emitCredentialMissingAnalyticsEvents");function Al(e){let t=e.route.raw();return zt.parse(t?.operationId)}n(Al,"readOperationId");async function xl(e,t,r,o){let a=await $e({request:e,context:o,routeAuth:t});if(a.kind==="connect_required")return ai({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(oi({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 rn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(rn,"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=Qt(Vn(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(El,"readFallbackServerIcons");function Ol(e){if(!rn(e.body))return e.body;let t=e.body.result;if(!rn(t))return e.body;let r=t.serverInfo;return!rn(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 Mn(e,{headers:r})}n(ql,"applyUpstreamHeaders");function Ml(e){let t=new Headers(e.headers);for(let r of Sl)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 ii(e,t){let r=t.authUrl===void 0?void 0:Do({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(Zt({id:Mo(e),error:{code:r?.code??Il,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(ii,"connectRequiredJsonRpcResponse");async function zl(e){let{scope:t}=Ko(e.upstreamResponse),r=await $e({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="connect_required")return ai({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(oi({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 ii(e.requestBody,o.payload);if(o.kind==="response")return o.response;let a=Yn({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 nn(e,t,r){let o=Al(t),a=await Dl(e),i=ni({connection:r,operationId:o}),c=xe(e.user,e.url,e.headers);t.log.setLogProperties?.({requestId:t.requestId}),po(t,c);let s=Ze(i,c.subjectId),u=await xl(e,s,r,t);if(!(u instanceof Response)&&u.kind==="connect_required")return ii(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(nn,"mcpTokenExchangePolicy");var on=class extends Ot{static{n(this,"McpTokenExchangeInboundPolicy")}constructor(t,r){let o=io(t,r);super(o,r)}async handler(t,r){return Et("policy.inbound.mcp-token-exchange"),nn(t,r,this.options)}};G();var si=Symbol("Html");function Bl(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n(Bl,"escapeHtml");function Ll(e){return e===null||typeof e!="object"?!1:e[si]===!0}n(Ll,"isHtml");function ci(e){return e==null||e===!1?"":Array.isArray(e)?e.map(ci).join(""):Ll(e)?e.value:Bl(String(e))}n(ci,"renderValue");function le(e){return{[si]:!0,value:e}}n(le,"trustedHtml");var X=le("");function C(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=ci(t[o]),r+=e[o+1]??"";return le(r)}n(C,"html");function Ke(e){return e.value}n(Ke,"renderHtml");function di(e){return C`<p class="card__description">${e.detail}</p>${e.guidance} ${e.technicalDetails} ${e.action}`}n(di,"renderBrowserErrorPage");var We=le('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;justify-content:center;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;min-height:40px;padding:8px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.reconnect-action{align-items:center;margin-right:auto;display:inline-flex;position:relative}.reconnect-button{gap:7px}.tooltip{width:16px;height:16px;color:var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);cursor:help;border:1.5px solid;border-radius:50%;justify-content:center;align-items:center;font-size:10.5px;font-weight:700;line-height:1;display:inline-flex;position:relative}.tooltip:after{content:attr(aria-label);z-index:10;border-radius:var(--radius-sm);background:var(--accent);width:280px;max-width:min(280px,100vw - 48px);color:var(--accent-text);box-shadow:var(--shadow);text-align:left;white-space:normal;opacity:0;pointer-events:none;padding:12px 14px;font-size:13px;font-weight:600;line-height:1.45;transition:opacity .12s;position:absolute;bottom:calc(100% + 12px);left:50%;transform:translate(-50%)}.tooltip:before{content:"";z-index:11;border-left:7px solid #0000;border-right:7px solid #0000;border-top:8px solid var(--accent);opacity:0;pointer-events:none;transition:opacity .12s;position:absolute;bottom:calc(100% + 5px);left:50%;transform:translate(-50%)}.tooltip:hover:after,.tooltip:hover:before,.tooltip:focus-visible:after,.tooltip:focus-visible:before{opacity:1}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}.reconnect-action{justify-content:center;width:100%;margin-right:0}.reconnect-action .button{flex:1}.tooltip:after{left:auto;right:0;transform:none}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function Ve(e){return C`<!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 wr,$c as xo,Ab as B,Ac as fo,Bb as _e,Bc as Jt,Cb as fc,Cc as ho,Db as hc,Dc as ce,Eb as gc,Ec as Ir,Fb as yc,Fc as Sr,G as zn,Gb as _c,Gc as go,H as l,Hb as wc,Hc as Gt,I as jn,Ib as Rc,Ic as Cr,J as yr,Jb as bc,Jc as vr,K as ae,Kb as Ic,Kc as yo,L as Hn,Lb as Sc,Lc as E,M as _,Mb as Vn,Mc as _o,N as he,Nb as Yn,Nc as wo,O as qt,Ob as Xn,Oc as Ar,P as Bn,Pb as zt,Pc as Ro,Q as Ln,Qb as _r,Qc as bo,R as Nn,Rb as jt,Rc as xr,S as d,Sb as Ht,Sc as Io,T as F,Tb as nt,Tc as ke,Ub as Qn,Uc as So,Vb as eo,Vc as st,Wb as to,Wc as Co,Xb as ot,Xc as Ft,Yb as ro,Yc as ct,Z as Jn,Zb as He,Zc as vo,_b as no,_c as Ao,a as G,ac as oo,ad as ko,bc as at,bd as Uo,cc as Bt,cd as To,dc as ao,dd as Po,ec as io,ed as $t,fc as so,fd as Eo,gc as co,gd as Oo,hc as X,hd as b,i as xe,ib as Gn,ic as j,id as v,j as qn,jb as $,jc as uo,jd as de,kb as Fn,kc as lo,kd as A,l as Mn,lb as $n,lc as I,ld as qo,mb as P,mc as se,md as Cc,nb as Zn,nc as Be,nd as vc,ob as g,oc as L,p as Dn,pb as ze,pc as U,qb as je,qc as po,r as Ot,rb as ge,rc as we,sb as ye,sc as mo,tb as Mt,tc as Re,ub as Kn,uc as Rr,vb as ee,vc as Lt,wb as Wn,wc as br,xb as ie,xc as Nt,yb as w,yc as it,zb as Dt,zc as Le}from"../chunk-MJPI3GFA.js";import"../chunk-JRXZBVXH.js";import{a as S}from"../chunk-GEVKFSKR.js";import{$ as Y,a as n,aa as f,ba as H,ca as On,da as Et}from"../chunk-ZIKV2LUM.js";F();function Ac(e){let t=Ht.safeParse(e);return t.success?t.data.id:void 0}n(Ac,"parseJsonRpcRequestId");function Mo(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Ac(t)}catch{return}}n(Mo,"readJsonRpcRequestIdFromBody");function Zt(e){return Qn.parse({jsonrpc:jt,...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(Zt,"jsonRpcErrorResponse");function Do(e){return new to([eo.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Do,"urlElicitationRequiredError");var Kt=d.record(d.string(),d.unknown()),xc=d.record(d.string(),d.unknown()),kc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),annotations:xc.optional(),_meta:Kt.optional()}).strict(),Uc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),_meta:Kt.optional()}).strict(),Tc=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:Kt.optional()}).strict(),Pc=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:Kt.optional()}).strict(),Ec=d.array(d.union([d.string(),kc])),Oc=d.array(d.union([d.string(),Uc])),qc=d.array(d.union([d.string(),Tc])),Mc=d.array(d.union([d.string(),Pc])),Dc=d.object({tools:Ec.optional(),prompts:Oc.optional(),resources:qc.optional(),resourceTemplates:Mc.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 zc(e,t){return Fn(Dc,e,`MCP capability filter policy "${t}"`)}n(zc,"parseMcpCapabilityFilterOptions");function N(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(N,"isRecord");function jc(e,t){if(!N(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(jc,"readParamString");function Tr(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(Tr,"readRequestId");function Bo(e){return e===void 0?void 0:JSON.stringify(e)}n(Bo,"requestIdKey");function Hc(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=Jc(i,r.itemProperty);c!==void 0&&a.set(c.key,c)}t[r.option]=a}return t}n(Hc,"buildProjectionMaps");function Pr(e){return Ur.find(t=>t.listMethod===e)}n(Pr,"findListRule");function Bc(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(Bc,"shouldFilterListResponses");function Lc(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=jc(e.request.params,o.paramProperty);if(a!==void 0&&!r.has(a))return{id:Tr(e.request)}}}}n(Lc,"findDisallowedDirectAccess");function Nc(e){return Response.json(Zt({id:e,error:{code:nt.MethodNotFound,message:"Method not found"}}))}n(Nc,"methodNotFoundResponse");function Jc(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(Jc,"buildProjection");function zo(e){let t=e.base[e.property],r=e.overlay[e.property];return N(r)?N(t)?{...t,...r}:r:t}n(zo,"mergeRecordProperty");function Gc(e,t){let r={...e,...t.overlay},o=zo({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let a=zo({base:e,overlay:t.overlay,property:"_meta"});return a!==void 0&&(r._meta=a),r}n(Gc,"applyProjection");function jo(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?[]:[Gc(i,s)]})}}}n(jo,"filterAndProjectItems");function Fc(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=Bo(a);o!==void 0&&i!==void 0&&t.set(i,o)}return t}n(Fc,"buildListRulesByResponseId");function $c(e){if(Array.isArray(e.responseBody)){let o=Fc(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(a=>{if(!N(a)||"error"in a)return a;let i=Bo(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:jo(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:jo(e.responseBody,t,r)}n($c,"filterJsonRpcResponse");async function Ho(e){return e.clone().json()}n(Ho,"readJson");function Zc(e){return e.headers.get("content-type")?.includes("json")??!1}n(Zc,"isJsonResponse");var kr=class extends Ot{static{n(this,"McpCapabilityFilterInboundPolicy")}#e;constructor(t,r){let o=zc(t,r);super(o,r),this.#e=Hc(o)}async handler(t,r){G("policy.inbound.mcp-capability-filter");let o;try{o=await Ho(t)}catch{return t}let a=Array.isArray(o)?o:[o];for(let i of a){if(!N(i))continue;let c=Lc({request:i,projectionMaps:this.#e});if(c!==void 0)return Nc(c.id)}return Bc({requests:a,projectionMaps:this.#e})&&r.addResponseSendingHook(async i=>{if(!Zc(i))return i;let c;try{c=await Ho(i)}catch{return i}let s=$c({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 Kc(e){return(await Er).getRandomValues(new Uint8Array(e))}n(Kc,"getRandomValues");async function Wc(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let a=await Kc(e-o.length);for(let i of a)i<r&&(o+=t[i%t.length])}return o}n(Wc,"random");async function Vc(e){return await Wc(e)}n(Vc,"generateVerifier");async function Yc(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(Yc,"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 Vc(e),r=await Yc(t);return{code_verifier:t,code_challenge:r}}n(Or,"pkceChallenge");F();var D=jn().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Ln.custom,message:"URL must be parseable",fatal:!0}),zn}).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"}),Wt=qt({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=qt({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()}),Xc=qt({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()}),Vt=he({...Xc.shape,...dt.pick({code_challenge_methods_supported:!0}).shape}),Ne=he({access_token:l(),id_token:l().optional(),token_type:l(),expires_in:Nn.number().optional(),scope:l().optional(),refresh_token:l().optional()}).strip(),No=he({error:l(),error_description:l().optional(),error_uri:l().optional()}),Lo=D.optional().or(Bn("").transform(()=>{})),Qc=he({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:Lo,scope:l().optional(),contacts:_(l()).optional(),tos_uri:Lo,policy_uri:l().optional(),jwks_uri:D.optional(),jwks:Hn().optional(),software_id:l().optional(),software_version:l().optional(),software_statement:l().optional()}).strip(),Yt=he({client_id:l(),client_secret:l().optional(),client_id_issued_at:yr().optional(),client_secret_expires_at:yr().optional()}).strip(),ut=Qc.merge(Yt),Dh=he({error:l(),error_description:l().optional()}).strip(),zh=he({token:l(),token_type_hint:l().optional()}).strip();function Jo(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(Jo,"resourceUrlFromServerUrl");function Go({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(Go,"checkResourceAllowed");var x=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 x{static{n(this,"InvalidRequestError")}};lt.errorCode="invalid_request";var Ue=class extends x{static{n(this,"InvalidClientError")}};Ue.errorCode="invalid_client";var Te=class extends x{static{n(this,"InvalidGrantError")}};Te.errorCode="invalid_grant";var Pe=class extends x{static{n(this,"UnauthorizedClientError")}};Pe.errorCode="unauthorized_client";var pt=class extends x{static{n(this,"UnsupportedGrantTypeError")}};pt.errorCode="unsupported_grant_type";var mt=class extends x{static{n(this,"InvalidScopeError")}};mt.errorCode="invalid_scope";var ft=class extends x{static{n(this,"AccessDeniedError")}};ft.errorCode="access_denied";var ue=class extends x{static{n(this,"ServerError")}};ue.errorCode="server_error";var ht=class extends x{static{n(this,"TemporarilyUnavailableError")}};ht.errorCode="temporarily_unavailable";var gt=class extends x{static{n(this,"UnsupportedResponseTypeError")}};gt.errorCode="unsupported_response_type";var yt=class extends x{static{n(this,"UnsupportedTokenTypeError")}};yt.errorCode="unsupported_token_type";var _t=class extends x{static{n(this,"InvalidTokenError")}};_t.errorCode="invalid_token";var wt=class extends x{static{n(this,"MethodNotAllowedError")}};wt.errorCode="method_not_allowed";var Rt=class extends x{static{n(this,"TooManyRequestsError")}};Rt.errorCode="too_many_requests";var Ee=class extends x{static{n(this,"InvalidClientMetadataError")}};Ee.errorCode="invalid_client_metadata";var bt=class extends x{static{n(this,"InsufficientScopeError")}};bt.errorCode="insufficient_scope";var It=class extends x{static{n(this,"InvalidTargetError")}};It.errorCode="invalid_target";var Fo={[lt.errorCode]:lt,[Ue.errorCode]:Ue,[Te.errorCode]:Te,[Pe.errorCode]:Pe,[pt.errorCode]:pt,[mt.errorCode]:mt,[ft.errorCode]:ft,[ue.errorCode]:ue,[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 ed(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(ed,"isClientAuthMethod");var qr="code",Mr="S256";function td(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&ed(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(td,"selectClientAuthMethod");function rd(e,t,r,o){let{client_id:a,client_secret:i}=t;switch(e){case"client_secret_basic":nd(a,i,r);return;case"client_secret_post":od(a,i,o);return;case"none":ad(a,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(rd,"applyClientAuthentication");function nd(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(nd,"applyBasicAuth");function od(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(od,"applyPostAuth");function ad(e,t){t.set("client_id",e)}n(ad,"applyPublicAuth");async function Zo(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=No.parse(JSON.parse(r)),{error:a,error_description:i,error_uri:c}=o,s=Fo[a]||ue;return new s(i||"",c)}catch(o){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new ue(a)}}n(Zo,"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 Vo(u,{fetchFn:i}),!s)try{s=await Wo(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 ld(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 id(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 En=await gd(u,{metadata:p,clientMetadata:e.clientMetadata,scope:T,fetchFn:i});await e.saveClientInformation(En),R=En}}let q=!e.redirectUrl;if(r!==void 0||q){let M=await hd(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 fd(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 x)||M instanceof ue))throw M}let ne=e.state?await e.state():void 0,{authorizationUrl:rt,codeVerifier:oe}=await pd(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 id(e,t,r){let o=Jo(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!Go({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(id,"selectResourceURL");function Ko(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(Ko,"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 Wo(e,t,r=fetch){let o=await dd(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 Wt.parse(await o.json())}n(Wo,"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 sd(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(sd,"buildWellKnownPath");async function $o(e,t,r=fetch){return await Br(e,{"MCP-Protocol-Version":t},r)}n($o,"tryMetadataDiscovery");function cd(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(cd,"shouldAttemptFallback");async function dd(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=sd(t,a.pathname);c=new URL(u,o?.metadataServerUrl??a),c.search=a.search}let s=await $o(c,i,r);if(!o?.metadataUrl&&cd(s,a.pathname)){let u=new URL(`/.well-known/${t}`,a);s=await $o(u,i,r)}return s}n(dd,"discoverMetadataWithFallback");function ud(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(ud,"buildDiscoveryUrls");async function Vo(e,{fetchFn:t=fetch,protocolVersion:r=_r}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},a=ud(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()):Vt.parse(await s.json())}}}n(Vo,"discoverAuthorizationServerMetadata");async function ld(e,t){let r,o;try{r=await Wo(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 Vo(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:a,resourceMetadata:r}}n(ld,"discoverOAuthServerInfo");async function pd(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(pd,"startAuthorization");function md(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(md,"prepareAuthorizationCodeRequest");async function Yo(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=td(o,h);rd(y,o,u,r)}let p=await(c??fetch)(s,{method:"POST",headers:u,body:r});if(!p.ok)throw await Zo(p);return Ne.parse(await p.json())}n(Yo,"executeTokenRequest");async function fd(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 Yo(e,{metadata:t,tokenRequestParams:s,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:c});return{refresh_token:o,...u}}n(fd,"refreshAuthorization");async function hd(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=md(a,p,e.redirectUrl)}let u=await e.clientInformation();return Yo(t,{metadata:r,tokenRequestParams:s,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:i})}n(hd,"fetchToken");async function gd(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 Zo(c);return ut.parse(await c.json())}n(gd,"registerClient");var Lr="zuplo.com",yd=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),_d=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function Xo(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(Xo,"s2FaviconHref");function wd(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(wd,"strictFaviconHref");var Xt=Xo(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")?Xo(Lr):wd(e)}n(Nr,"resolveIconHref");function Rd(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(Rd,"hostnameFromHost");function bd(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(bd,"isLocalOrAddressHost");function Id(e){let t=Rd(e).toLowerCase().replace(/\.$/,"");if(bd(t)||_d.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=yd.has(o)?3:2;return r.slice(-a).join(".")}n(Id,"inferFaviconDomain");function Jr(e){return{src:Nr(Id(e)),mimeType:"image/png",sizes:["128x128"]}}n(Jr,"resolveMcpFaviconIcon");function Qt(e){try{return Jr(new URL(e).host)}catch{return}}n(Qt,"resolveMcpFaviconIconFromUrl");function be(e){let t=X().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 er(e){let t=X().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(er,"getUpstreamAuthConfig");function Je(e,t){let r=er({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 Qo(e,t){let r=er({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(Qo,"requireUpstreamIdJagConfig");function ea(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(ea,"mergeAbortSignals");async function Sd(e){try{await e.cancel()}catch{}}n(Sd,"cancelReader");async function tr(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 Sd(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(tr,"readBoundedByteStream");var Cd=2,vd=1024*1024,Ad=1e4,xd=new Set([301,302,303,307,308]),kd=["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 Ud(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(Ud,"assertContentLengthWithinLimit");async function Td(e,t,r){return Ud(e,t,r),tr(e.body,{maxBytes:t,createLimitError:n(()=>new f({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}}),"createLimitError")})}n(Td,"readBoundedResponseBody");function Pd(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(Pd,"responseFromBufferedBody");function Ed(e,t){if(!xd.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(Ed,"resolveRedirectUrl");function ta(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(ta,"validateOutboundUrl");function Od(e,t){throw e instanceof f&&Mt(e.extensionMembers?.[g])?e:new f({message:"Outbound fetch failed.",extensionMembers:{[g]:t}},{cause:e})}n(Od,"normalizeFetchError");function St(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(St,"logOutboundFailure");async function qd(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";St(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:s,host:U(i),error:u,extra:{abortReason:c()}}),Od(u,a)}}n(qd,"fetchWithNormalizedError");function Md(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(Md,"assertRedirectAllowed");function Dd(e,t){let r=new Headers(e);for(let o of kd)r.delete(o);for(let o of t)r.delete(o);return r}n(Dd,"stripCrossOriginHeaders");function zd(e,t,r,o,a){let i={...e,method:t,redirect:"manual",signal:r};return o&&(i.headers=Dd(e.headers,a)),i}n(zd,"buildRedirectInit");function jd(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(jd,"buildInitialRequestInit");function Hd(e){let t=Ge(e.currentInput,e.currentInit);Md({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=ta(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:zd(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(Hd,"followRedirect");async function Fr(e,t,r){let o=r.problemCode??"invalid_request",a=r.maxRedirects??Cd,i=r.maxResponseBytes??vd,c=r.timeoutMs??Ad,s=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,h=new AbortController,y=ea(h,t.signal),T=!1,R=setTimeout(()=>{T=!0,h.abort()},c),q=e,O=jd(e,t,h.signal),ne;try{ne=ta(Gr(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(oe){throw St(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 qd(p,s,q,O,o,ne,()=>T?`timeout_after_${c}ms`:void 0),M=Ed(oe,ne);if(M!==void 0)try{let z=Hd({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 St(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 Pd(oe,await Td(oe,i,o))}catch(z){throw St(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 Ct(e,t,r){let o=await Fr(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(a){throw St(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(Ct,"runSafeOutboundJsonExchange");function ra(e,t={},r={}){return Fr(e,t,{...r,validateUrl:st})}n(ra,"fetchConfiguredOutbound");function na(e,t={},r={}){return Ct(e,t,{...r,validateUrl:st})}n(na,"fetchConfiguredOutboundJson");function rr(e,t={},r={}){return Ct(e,t,{...r,validateUrl:Co})}n(rr,"fetchIdentityProviderJson");function oa(e,t={},r={}){return Ct(e,t,{...r,validateUrl:Ft})}n(oa,"fetchCimdClientMetadataJson");function aa(e,t={},r={}){return Ct(e,t,{...r,validateUrl:ct})}n(aa,"fetchCimdClientJwksJson");F();import{errors as pa,jwtVerify as ma,SignJWT as fa}from"jose";var J="zuplo-mcp-gateway",Z=J,K="HS256";import{base64url as Bd}from"jose";var Ld=new TextEncoder,Nd="MCP gateway could not initialize secure key material.",Jd=32,ia=new Map,sa=new Map,Gd;function Fd(){return Gd??On.instance.authPrivateKey}n(Fd,"readAuthPrivateKey");function ca(e){return new Y(Nd,e===void 0?void 0:{cause:e})}n(ca,"createGeneratedKeyMaterialError");function da(e,t){let r=Bd.decode(t);if(r.byteLength!==Jd)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(da,"decodeJwkKeyField");function $d(e){let t=Fd();if(!t)throw ca();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=da("d",r.d);da("x",r.x);let a=Ld.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 ca(r)}}n($d,"decodeGeneratedKeyMaterial");function Zd(e){let t=ia.get(e);return t||(t=$d(e),ia.set(e,t)),t}n(Zd,"getMasterKeyMaterial");async function te(e){let t=sa.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Zd(e.keyMaterialPurpose));return sa.set(e.purpose,r),r}n(te,"readCachedDerivedKey");var Kd="SHA-256";var Wd="zuplo-mcp-gateway:",Vd=new TextEncoder,ua=new WeakMap;async function Ie(e,t){let r=ua.get(e);r||(r=new Map,ua.set(e,r));let o=r.get(t);if(o)return o;let a=await Yd(e,t);return r.set(t,a),a}n(Ie,"deriveGatewaySigningKey");async function Yd(e,t){let r=la(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=Vd.encode(`${Wd}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:Kd,salt:new Uint8Array,info:la(a)},o,32*8);return new Uint8Array(i)}n(Yd,"hkdfExpand");function la(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}n(la,"copyToArrayBuffer");var ha=15*60,Xd=15*60,Qd=oo.extend({id:Uo}),eu=Qd.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ga=wr.extend({id:To,purpose:d.literal("browser_connect")}),tu=wr.extend({purpose:d.literal("browser_connect")}),ru=ga.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ya=ha*1e3;async function _a(){return te({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ie(e,"oauth-state"),"derive")})}n(_a,"getOAuthStateKey");async function wa(){return te({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ie(e,"browser-connect"),"derive")})}n(wa,"getBrowserConnectKey");async function Ra(e){let t=Math.floor(Date.now()/1e3)+ha;return new fa(e).setProtectedHeader({alg:K,typ:"JWT"}).setIssuer(J).setAudience(Z).setIssuedAt().setExpirationTime(t).sign(await _a())}n(Ra,"signOAuthState");async function nr(e){try{let{payload:t}=await ma(e,await _a(),{algorithms:[K],issuer:J,audience:Z});return eu.parse(t)}catch(t){throw t instanceof pa.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(nr,"verifyOAuthState");async function ba(e){let t=Math.floor(Date.now()/1e3)+Xd,r=tu.parse(e),o=ga.parse({...r,id:Oo()});return new fa(o).setProtectedHeader({alg:K,typ:"JWT"}).setIssuer(J).setAudience(Z).setIssuedAt().setExpirationTime(t).sign(await wa())}n(ba,"signBrowserConnectTicket");async function Ia(e){try{let{payload:t}=await ma(e,await wa(),{algorithms:[K],issuer:J,audience:Z});return ru.parse(t)}catch(t){throw t instanceof pa.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(Ia,"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 nu(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(nu,"buildConnectRequiredMessage");async function ou(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 ba({...at(e),purpose:"browser_connect"})),r.toString()}n(ou,"buildGatewayBrowserTicketUrl");function au(e){return j().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(au,"buildGatewayConnectPath");async function $r(e){return ou({...e,path:au(e.upstreamServerId),redirect:!0})}n($r,"buildGatewayConnectUrl");async function or(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:nu(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(or,"buildRedirectConnectRequiredResponse");function Ca(e){return iu({...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 iu(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(iu,"buildAdminSetupRequiredResponse");F();var va=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function su(e,t){return e&&e.length>0?e.join(t):void 0}n(su,"joinOAuthScopes");function cu(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of va)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(cu,"sanitizeAuthorizationServerMetadata");function Zr(e){let t=cu(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(Zr,"sanitizeOAuthDiscoveryState");function Aa(e){let t=new URL(e);for(let r of va){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(Aa,"normalizeDuplicateSingletonAuthorizationRequestParams");function ar(e){let t=new URL(e);return $(t)&&Gn(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(ar,"normalizeLoopbackOAuthRedirectUri");function xa(e){return su(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(xa,"readProtectedResourceMetadataScope");function du(e){return`Zuplo MCP Gateway - ${e}`}n(du,"buildGatewayOAuthClientName");function uu(e,t){return e&&e.length>0?e.join(t):void 0}n(uu,"joinOAuthScopeList");function lu(e){if(e.clientRegistration.mode!=="auto")return uu(e.scopes,e.scopeDelimiter)}n(lu,"readPublicClientMetadataScope");function Kr(e){return new URL(j().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Kr,"buildOAuthClientMetadataDocumentUrl");function Wr(e){let t=be(e.upstreamServerId);return{client_name:du(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(Wr,"buildGatewayOAuthClientMetadata");function ka(e,t,r){let o=Je(t,r),a=lu(o);return{client_id:Kr({origin:e,upstreamServerId:t}),...Wr({origin:e,upstreamServerId:t,redirectUri:ar(new URL(o.redirectPath,e)).toString(),scope:a})}}n(ka,"buildOAuthClientMetadataDocument");F();import{base64url as Se}from"jose";var pu="SHA-256",$e="AES-GCM",mu=12,Yr="zuplo-secret",Xr=1,Ua="generated:auth_private_key:token-encryption",fu=d.object({version:d.literal(Xr),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 Vr(){return te({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(pu,Fe(e));return crypto.subtle.importKey("raw",t,{name:$e},!1,["encrypt","decrypt"])},"derive")})}n(Vr,"getEncryptionKey");function Ta(e){return Fe(new TextEncoder().encode(`${Yr}:v${e.version}:${e.keyId}`))}n(Ta,"getAssociatedData");function hu(e){return`${Yr}:v${e.version}:${Se.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(hu,"encodeEnvelope");function gu(e){let t=`${Yr}:v${Xr}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(Se.decode(r));return fu.parse(JSON.parse(o))}n(gu,"decodeEnvelope");async function le(e){let t=await Vr(),r=crypto.getRandomValues(new Uint8Array(mu)),o={version:Xr,keyId:Ua},a=await crypto.subtle.encrypt({name:$e,iv:r,additionalData:Ta(o)},t,new TextEncoder().encode(e));return hu({...o,algorithm:$e,iv:Se.encode(r),ciphertext:Se.encode(new Uint8Array(a))})}n(le,"encryptSecret");async function Ce(e){let t=gu(e);if(t){let c=await Vr(),s=await crypto.subtle.decrypt({name:$e,iv:Fe(Se.decode(t.iv)),additionalData:Ta(t)},c,Fe(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 Vr(),i=await crypto.subtle.decrypt({name:$e,iv:Fe(Se.decode(r))},a,Fe(Se.decode(o)));return new TextDecoder().decode(i)}n(Ce,"decryptSecret");var yu=d.union([ut,Yt]),Pa=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:Wt.optional(),authorizationServerMetadata:d.union([dt,Vt]).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 Jt.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 Ea(e){if(e!==void 0)return le(JSON.stringify(e))}n(Ea,"encryptJson");async function Oa(e,t){if(!e)return;let r=await Ce(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(Oa,"decryptJson");function Su(e){if(e===void 0)return;e=Zr(e);let t={authorizationServerUrl:e.authorizationServerUrl};return e.resourceMetadataUrl!==void 0&&(t.resourceMetadataUrl=e.resourceMetadataUrl),e.resourceMetadata!==void 0&&(t.resourceMetadata=e.resourceMetadata),e.authorizationServerMetadata!==void 0&&(t.authorizationServerMetadata=e.authorizationServerMetadata),t}n(Su,"toOAuthDiscoveryState");function Cu(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(Cu,"clientInformationAllowsRedirectUri");function vu(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(vu,"clientInformationMatchesCurrentClientMetadataUrl");function Au(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(Au,"isUrlBasedClientInformation");function xu(e,t){return t===void 0?e:{...e,scope:t}}n(xu,"applyOAuthClientMetadataScope");function qa(e,t){return xa({state:e,delimiter:t})}n(qa,"readResourceMetadataScope");function ku(e,t){return e&&e.length>0?e.join(t):void 0}n(ku,"joinOAuthScopeList");function Uu(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(Uu,"buildManualOAuthClientInformation");function Tu(e,t){let r=Kr({origin:new URL(t).origin,upstreamServerId:e});return Hr(r)?r:void 0}n(Tu,"buildClientMetadataUrl");function Ma(e){for(let t of e)if(t!==void 0)return t}n(Ma,"firstDefined");function Pu(e){let t=Je(e.target.upstreamServerId,e.target.authProfileId),r=ku(t.scopes,t.scopeDelimiter),o=Wr({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:Uu({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let a=Tu(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 Ma([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(Eu,"readEncryptedClientInformation");function Ou(e){return Ma([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}n(Ou,"readEncryptedDiscoveryState");var Oe=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredScope;scopeDelimiter;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;connection;pendingState;encryptedClientInformation;encryptedDiscoveryState;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),this.encryptedDiscoveryState=Ou(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return xu(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return Ra({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,we()?.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"),!Au({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Ea(t),await this.syncPendingState(!1)))}async discoveryState(){return this.loadPersistedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=Zr(Pa.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,we()?.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=qa(r,this.scopeDelimiter),this.encryptedDiscoveryState=await Ea(r),await this.syncPendingState(!1)}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 le(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:Ne.parse({...r,refresh_token:await Ce(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let i={id:this.connection?.id??$t(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await le(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),we()?.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: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.encryptedDiscoveryState=void 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:Eo(),...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()+ya)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await 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,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await Oa(this.encryptedClientInformation,yu)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&(!Cu(t,this.redirectUriValue)||!vu({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=Yt.parse({client_id:this.clientMetadataUrl})),this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async loadPersistedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;try{this.cachedDiscoveryState=Su(await Oa(this.encryptedDiscoveryState,Pa))}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1)}return this.discoveryStateLoaded=!0,this.inferredScope=qa(this.cachedDiscoveryState,this.scopeDelimiter),this.cachedDiscoveryState}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 Ce(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await Ce(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=Ne.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&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var qu=3e4,Mu=256*1024,Du=2;function zu(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}n(zu,"hasUsableAccessToken");var ju="does not support dynamic client registration",Hu=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],Bu=["HTTP 403 Forbidden","Access Denied","permission to access"];function Lu(e){return e instanceof Error&&e.message.includes(ju)}n(Lu,"isDynamicClientRegistrationUnsupported");function Nu(e){return e instanceof Error&&Hu.some(t=>e.message.includes(t))}n(Nu,"isProtectedResourceMetadataUnavailable");function Ju(e){return e instanceof Error&&Bu.some(t=>e.message.includes(t))}n(Ju,"isUpstreamProviderAccessDenied");function Gu(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(Gu,"mapUpstreamOAuthSetupError");function Fu(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(Fu,"readOAuthFetchRequest");function $u(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n($u,"responseLooksJson");function Zu(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(Zu,"responseLooksHtml");function Ku(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",[ge]:e.response.status,[ze]:r,[ye]:e.request.url.toString(),[je]:e.body}})}n(Ku,"throwUpstreamHtmlError");function Wu(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(Wu,"readUpstreamOAuthErrorBody");function Vu(e){let{error:t,errorDescription:r}=Wu(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(Vu,"logUpstreamOAuthHttpError");function Da(e){return async(t,r)=>{let o=Fu(t),a=we(),i=Date.now(),c=await ra(t,r,{maxRedirects:Du,maxResponseBytes:Mu,problemCode:"upstream_token_exchange_failed",timeoutMs:qu}),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||Vu({log:a,upstreamServerId:e,request:o,response:c,body:s}),!c.ok&&Zu(c,s)&&Ku({upstreamServerId:e,request:o,response:c,body:s}),!$u(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(Da,"createUpstreamOAuthFetch");function za(e){we()?.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(za,"logUpstreamOAuthFlowStarted");function ja(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),we()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(ja,"logUpstreamOAuthFlowFailed");async function Ha(e,t){e.applyChallengeScope(t.requestedScope),za({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Da(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),await jr(e,r)}catch(r){ja({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=Gu({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(Ha,"runUpstreamOAuth");async function Yu(e,t){e.applyChallengeScope(t.requestedScope),za({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Da(t.upstreamServerId)};t.requestedScope!==void 0&&(r.scope=t.requestedScope);try{return await jr(e,r)}catch(o){throw ja({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:o}),o}}n(Yu,"exchangeUpstreamAuthorizationCode");async function Ba(e,t){let r=await Ha(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(Ba,"requireUpstreamAuthorizationRedirect");async function La(e){if(!e.forceRefresh&&zu(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await Ha(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}});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 rl({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(La,"authorizeUpstreamOAuthSession");async function Xu(e){let t=await nr(e.stateToken),r=await b().consumeUpstreamOAuthState({id:t.id,now:I(new Date)}),o=Qu(r);return el({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),tl(o),o}n(Xu,"consumeStoredCallbackState");function Qu(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(Qu,"readConsumedCallbackState");function el(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(el,"assertStoredCallbackStateMatches");function tl(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new f({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}})}n(tl,"assertStoredCallbackStateFresh");async function rl(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),or(t)}n(rl,"buildOAuthConnectRequiredResponse");async function Na(e){let t=await Xu({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Bt(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 Yu(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(Na,"finishUpstreamOAuthCallback");F();import{importPKCS8 as nl,SignJWT as ol}from"jose";var Ga=1e4,Fa=64*1024,$a=2,al=300,W=d.string().min(1),il=d.object({access_token:W,issued_token_type:W,token_type:W,expires_in:d.number().int().positive().optional(),scope:W.optional()}).passthrough(),sl=d.object({id_token:W,token_type:W.optional(),expires_in:d.number().int().positive().optional(),refresh_token:W.optional(),scope:W.optional()}).passthrough(),cl=d.object({access_token:W,token_type:W,expires_in:d.number().int().positive().optional(),scope:W.optional(),resource:W.optional(),refresh_token:W.optional()}).passthrough();function Ja(e){return encodeURIComponent(e).replace(/%20/g,"+")}n(Ja,"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=Ja(e.clientAuth.clientId),r=Ja(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",Nt),e.form.set("client_assertion",await ul({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}n(ll,"appendClientAuthentication");async function Qr(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(Qr,"buildFormRequest");function Za(e){return(t,r)=>rr(t,r,{context:e,maxRedirects:$a,maxResponseBytes:Fa,problemCode:"upstream_token_exchange_failed",timeoutMs:Ga})}n(Za,"defaultIdpFetchJson");function pl(e){return(t,r)=>na(t,r,{context:e,maxRedirects:$a,maxResponseBytes:Fa,problemCode:"upstream_token_exchange_failed",timeoutMs:Ga})}n(pl,"defaultResourceAsFetchJson");function vt(e){let t={[g]:e.code,[ye]:e.tokenUrl};return e.response!==void 0&&(t[ge]=e.response.status),new f({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}n(vt,"runtimeError");function en(e){if(!e.response.ok)throw vt({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(en,"assertTokenEndpointSucceeded");function ml(e){let t=sl.safeParse(e.json);if(!t.success)throw vt({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 vt({code:"upstream_token_response_invalid",message:"IdP token exchange returned an invalid ID-JAG response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});if(t.data.issued_token_type!==br||t.data.token_type.toLowerCase()!=="n_a")throw vt({code:"upstream_token_response_invalid",message:"IdP token exchange response did not contain an ID-JAG assertion.",tokenUrl:e.tokenUrl,response:e.response});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 vt({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 Ka(e){let t=new URLSearchParams({grant_type:Lt,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??Za(e.context),{response:o,json:a}=await r(e.idp.tokenUrl,await Qr({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return en({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),fl({json:a,response:o,tokenUrl:e.idp.tokenUrl})}n(Ka,"requestIdJag");async function Wa(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??Za(e.context),{response:o,json:a}=await r(e.idp.tokenUrl,await Qr({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return en({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),ml({json:a,response:o,tokenUrl:e.idp.tokenUrl})}n(Wa,"refreshIdpSubjectToken");async function Va(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 Qr({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return en({response:o,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),hl({json:a,response:o,tokenUrl:e.resourceAs.tokenUrl})}n(Va,"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 Ce(e.encryptedSubjectToken);if(e.subjectTokenType!==Le)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await Wa({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 le(r.refreshToken),idpSubjectTokenType:Le,idpSubjectTokenExpiresAt:void 0}}),subjectToken:r.idToken,subjectTokenType:it}}n(wl,"resolveIdJagSubjectToken");async function Ya(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 Ce(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=Qo(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 Ka({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 Va({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 le(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(Ya,"authorizeUpstreamIdJagRequest");function Rl(e){return ar(new URL(e.callbackPath,P(e.requestUrl,e.requestHeaders))).toString()}n(Rl,"buildGatewayOAuthRedirectUri");async function Xa(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(Xa,"prepareUpstreamOAuthRequest");async function Qa(e){let t=await Xa(e),r=new Oe({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Ba(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(Qa,"startUpstreamConnect");async function ei(e){let t=await Xa(e),r=new Oe({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return La({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(ei,"authorizeUpstreamRequest");async function Ze(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return ei({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 Ya({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(Ze,"resolveUpstreamCredentialForRoute");async function ti(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 Qa({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(ti,"startUpstreamConnectForRequest");async function ri(e){let r=(await nr(e.callbackRequest.state)).authProfileId;if(er({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 Na({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:be(e.callbackRequest.upstreamServerId)})}n(ri,"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 ni(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:ao(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(ni,"buildRouteAuthBaseFromPolicyOptions");function ir(e,t){let o=X().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 tn(e,t){switch(e){case"user":return He(t);case"shared":return no()}}n(tn,"buildOwnerForSubject");function Ke(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:tn("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:tn("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:tn("user",t),initiatedBySubjectId:t}}}n(Ke,"resolveRouteAuthForSubject");var Il=nt.InvalidRequest,Sl=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function Cl(e,t){return{credentialType:e.type,forceRefresh:t}}n(Cl,"buildCredentialResolvedAttributes");function vl(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(vl,"connectRequiredReasonCode");function oi(e){v(e.context,{eventType:S.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:Cl(e.credential,e.forceRefresh===!0)})}n(oi,"emitCredentialResolvedAnalyticsEvent");function ai(e){let t={forceRefresh:e.forceRefresh===!0,nextAction:e.payload.nextAction,state:e.payload.state};if(v(e.context,{eventType:S.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:S.MCP_AUTH_UPSTREAM_RECONSENT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:"reconsent_required",reasonClass:"auth",attributes:t});return}v(e.context,{eventType:S.MCP_AUTH_UPSTREAM_CONNECT_REQUIRED,outcome:"connect_required",routeBinding:e.routeBinding,reasonCode:vl(e.payload.state),reasonClass:"auth",attributes:t})}n(ai,"emitCredentialMissingAnalyticsEvents");function Al(e){let t=e.route.raw();return zt.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 ai({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(oi({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 rn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(rn,"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=Qt(Vn(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(El,"readFallbackServerIcons");function Ol(e){if(!rn(e.body))return e.body;let t=e.body.result;if(!rn(t))return e.body;let r=t.serverInfo;return!rn(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 Mn(e,{headers:r})}n(ql,"applyUpstreamHeaders");function Ml(e){let t=new Headers(e.headers);for(let r of Sl)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 ii(e,t){let r=t.authUrl===void 0?void 0:Do({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(Zt({id:Mo(e),error:{code:r?.code??Il,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(ii,"connectRequiredJsonRpcResponse");async function zl(e){let{scope:t}=Ko(e.upstreamResponse),r=await Ze({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="connect_required")return ai({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(oi({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 ii(e.requestBody,o.payload);if(o.kind==="response")return o.response;let a=Yn({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return Et.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 nn(e,t,r){let o=Al(t),a=await Dl(e),i=ni({connection:r,operationId:o}),c=ke(e.user,e.url,e.headers);t.log.setLogProperties?.({requestId:t.requestId}),po(t,c);let s=Ke(i,c.subjectId),u=await xl(e,s,r,t);if(!(u instanceof Response)&&u.kind==="connect_required")return ii(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(nn,"mcpTokenExchangePolicy");var on=class extends Ot{static{n(this,"McpTokenExchangeInboundPolicy")}constructor(t,r){let o=io(t,r);super(o,r)}async handler(t,r){return G("policy.inbound.mcp-token-exchange"),nn(t,r,this.options)}};F();var si=Symbol("Html");function Bl(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n(Bl,"escapeHtml");function Ll(e){return e===null||typeof e!="object"?!1:e[si]===!0}n(Ll,"isHtml");function ci(e){return e==null||e===!1?"":Array.isArray(e)?e.map(ci).join(""):Ll(e)?e.value:Bl(String(e))}n(ci,"renderValue");function pe(e){return{[si]:!0,value:e}}n(pe,"trustedHtml");var Q=pe("");function C(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=ci(t[o]),r+=e[o+1]??"";return pe(r)}n(C,"html");function We(e){return e.value}n(We,"renderHtml");function di(e){return C`<p class="card__description">${e.detail}</p>${e.guidance} ${e.technicalDetails} ${e.action}`}n(di,"renderBrowserErrorPage");var Ve=pe('*,: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 C`<!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(Ve,"renderShell");var Nl="text/html; charset=utf-8";function Ye(e){try{return new URL(e).host}catch{return""}}n(Ye,"safeHostFromUrl");function te(e){let t=Gl(e.kind??"authorization_failed"),r=Jl(e);return new Response(Ke(Ve({title:e.title??t.title,iconHref:"",styles:We,headerIcon:X,heading:e.title??t.title,subhead:"",body:di({detail:e.detail,guidance:C`<p class="card__description">${t.guidance}</p>`,technicalDetails:Wl({diagnostic:r,upstreamHtml:e.upstreamHtml}),action:Zl(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":Nl,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(te,"browserErrorPageResponse");function Jl(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??Fl(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??$l(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}n(Jl,"buildBrowserErrorDiagnostic");function Gl(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(Gl,"readBrowserErrorPagePresentation");function Fl(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(Fl,"readBrowserErrorStage");function $l(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($l,"readBrowserErrorSuggestedFix");function Zl(e){return e===void 0?X:C`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(Zl,"renderAction");function Kl(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 C`<pre class="banner__message" style="white-space: pre-wrap; overflow-wrap: anywhere; margin-top: 8px;"><code>${t}</code></pre>`}n(Kl,"renderTechnicalPre");function sr(e){return e.value===void 0||e.value===""?X:C`<p class="banner__message"><strong>${e.label}:</strong> <code>${e.value}</code></p>`}n(sr,"renderOptionalTechnicalRow");function Wl(e){return C`<section class="banner banner--warning" aria-label="Developer details">
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(Ye,"renderShell");var Nl="text/html; charset=utf-8";function Xe(e){try{return new URL(e).host}catch{return""}}n(Xe,"safeHostFromUrl");function re(e){let t=Gl(e.kind??"authorization_failed"),r=Jl(e);return new Response(We(Ye({title:e.title??t.title,iconHref:"",styles:Ve,headerIcon:Q,heading:e.title??t.title,subhead:"",body:di({detail:e.detail,guidance:C`<p class="card__description">${t.guidance}</p>`,technicalDetails:Wl({diagnostic:r,upstreamHtml:e.upstreamHtml}),action:Zl(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":Nl,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(re,"browserErrorPageResponse");function Jl(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??Fl(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??$l(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}n(Jl,"buildBrowserErrorDiagnostic");function Gl(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(Gl,"readBrowserErrorPagePresentation");function Fl(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(Fl,"readBrowserErrorStage");function $l(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($l,"readBrowserErrorSuggestedFix");function Zl(e){return e===void 0?Q:C`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(Zl,"renderAction");function Kl(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 C`<pre class="banner__message" style="white-space: pre-wrap; overflow-wrap: anywhere; margin-top: 8px;"><code>${t}</code></pre>`}n(Kl,"renderTechnicalPre");function sr(e){return e.value===void 0||e.value===""?Q:C`<p class="banner__message"><strong>${e.label}:</strong> <code>${e.value}</code></p>`}n(sr,"renderOptionalTechnicalRow");function Wl(e){return C`<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>
@@ -40,11 +40,11 @@ import{$b as ot,$c as Uo,Ab as fc,Ac as ho,Bb as hc,Bc as se,Cb as gc,Cc as Ir,D
40
40
  ${Kl(e.diagnostic)}
41
41
  ${Vl(e.upstreamHtml)}
42
42
  </div>
43
- </section>`}n(Wl,"renderTechnicalDetails");function Vl(e){return e===void 0?X:C`<iframe
43
+ </section>`}n(Wl,"renderTechnicalDetails");function Vl(e){return e===void 0?Q:C`<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 ui="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===ui&&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 li(e,t){let r=t.label??"Request body";ep(e,t.expectedContentTypes),tp(e,t.maxBytes,r);let o=await tr(e.body,{maxBytes:t.maxBytes,createLimitError:n(()=>cr(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(o)}n(li,"readBoundedTextBody");async function pi(e,t){let r=await li(e,{...t,expectedContentTypes:[ui]});try{return JSON.parse(r)}catch(o){throw cr("Request body must be valid JSON.",o)}}n(pi,"readBoundedJsonBody");async function mi(e,t){let r=await li(e,{...t,expectedContentTypes:[Yl]});return new URLSearchParams(r)}n(mi,"readBoundedFormUrlEncodedBody");G();G();import{errors as fi,jwtVerify as hi,SignJWT as gi}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:Sr,exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ap=d.object({purpose:d.literal("gateway_authorization_setup"),transactionId:Ir,stateId:Sr,exp:d.number().int().positive(),iat:d.number().int().positive().optional()});async function yi(){return ee({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>be(e,"browser-login"),"derive")})}n(yi,"getBrowserLoginKey");async function _i(){return ee({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>be(e,"authorization-csrf"),"derive")})}n(_i,"getCsrfKey");function wi(e){return{now:e.now??new Date,ttlSeconds:Ri()}}n(wi,"readPendingTransactionDependencies");function Ri(){return B().browserLogin.stateTtlSeconds}n(Ri,"readBrowserLoginStateTtlSeconds");function ip(e){let t=j();return F(e)&&t.isActionPath(e.pathname,"/oauth/dev-login")}n(ip,"isLoopbackDevLoginUrl");function sp(e){let t=B().browserLogin,r=j(),o=new URL(ye("url")),a=new URL(r.actionPath("/oauth/callback"),He(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",ye("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 bi(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}n(bi,"toPendingPrincipal");function Ii(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(ie(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:bi(e.principal)}}n(Ii,"createTransactionRecord");async function Si(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(Si,"startPendingTransaction");async function dp(e){return new gi({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:Z,typ:"JWT"}).setIssuer(J).setAudience($).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await yi())}n(dp,"signBrowserLoginState");async function Ci(e){return new gi({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:vr()}).setProtectedHeader({alg:Z,typ:"JWT"}).setIssuer(J).setAudience($).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await _i())}n(Ci,"signCsrfToken");async function an(e){try{let{payload:t}=await hi(e,await yi(),{algorithms:[Z],issuer:J,audience:$}),r=op.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof fi.JWTExpired?w("oauth_state_expired","Browser login state has expired.",t):w("oauth_state_invalid","Browser login state could not be verified.",t)}}n(an,"verifyBrowserLoginStateToken");async function dr(e){try{let{payload:t}=await hi(e,await _i(),{algorithms:[Z],issuer:J,audience:$});return{transactionId:ap.parse(t).transactionId}}catch(t){throw t instanceof fi.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 sn(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}n(sn,"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 cn(e){return e==="principal_mismatch"?"oauth_callback_mismatch":sn(e==="consumed_already"?"consumed_already":e)}n(cn,"setupDecisionErrorCode");async function vi(e){let t=e.now??new Date,r=await dr(e.csrfToken),o=await b().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await A(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:I(t)});if(o.kind!=="marked")throw w(cn(o.kind),"Authorization setup state is invalid, expired, or already used.");return Ai({kind:"available",record:o.transaction})}n(vi,"markSetupApproved");function Ai(e){if(e.kind!=="available")throw w(sn(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(Ai,"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 xi(e){let t=e.now??new Date,r=Ri(),o=Cr(),a=vr(),i=await dp({transactionId:o,stateId:a,ttlSeconds:r}),c=Ii({id:o,transaction:e.transaction,currentStateHash:await A(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 Si({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(xi,"startAwaitingLogin");async function ki(e){let{now:t,ttlSeconds:r}=wi(e),o=Cr(),a=await Ci({transactionId:o,ttlSeconds:r}),i=Ii({id:o,transaction:e.transaction,currentStateHash:await A(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 Si({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(ki,"startAwaitingSetup");async function Ui(e){let{now:t,ttlSeconds:r}=wi(e),o=await an(e.browserLoginStateToken),a=await Ci({transactionId:o.transactionId,ttlSeconds:r}),i=lp(await b().advancePendingAuthorization({transactionId:o.transactionId,expectedPhase:"awaiting_login",currentStateHash:await A(e.browserLoginStateToken),nextStateHash:await A(a),nextPhase:"awaiting_setup",principal:bi(e.principal),now:I(t)}));if(i.kind!=="advanced")throw w(sn(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(Ui,"completeLogin");async function Ti(e){let t=await dn(e);return pp({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}n(Ti,"getSetup");async function dn(e){let t=e.now??new Date,r=await dr(e.csrfToken);return Ai(up(await b().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await A(e.csrfToken),now:I(t)})))}n(dn,"getSetupTransaction");async function mp(e){let t=await dr(e.csrfToken),r=ce(),o=I(ie(e.now,np)),a=await b().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await A(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await A(r),authorizationCodeExpiresAt:o,grantId:yo(),now:I(e.now)});if(a.kind!=="approved")throw w(a.kind==="cancelled"?"oauth_state_invalid":cn(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 A(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:I(e.now)});if(r.kind!=="cancelled")throw w(r.kind==="approved"?"oauth_state_invalid":cn(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 Pi(e){let t=e.now??new Date;return mp({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Pi,"approve");async function Ei(e){let t=e.now??new Date;return fp({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Ei,"cancel");G();import{createRemoteJWKSet as gp,errors as Xe,jwtVerify as Oi,SignJWT as yp}from"jose";var pn="zuplo_mcp_session",_p=d.object({purpose:d.literal("gateway_browser_session"),sub:nt,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:nt,nonce:d.string().min(1)}).catchall(d.unknown()),un;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 qi(){return ee({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>be(e,"browser-session"),"derive")})}n(qi,"getBrowserSessionKey");function ln(e,t){let r=new URL(P(e,t)),o=[`${pn}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return r.protocol==="https:"&&o.push("Secure"),o.join("; ")}n(ln,"buildBrowserSessionEvictionCookie");function Sp(e){let t=new URL(P(e.requestUrl,e.requestHeaders)),r=[`${pn}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(Sp,"serializeSessionCookie");function Mi(){return new URL(ye("url")).origin}n(Mi,"readBrowserLoginOrigin");function Cp(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(Cp,"readIdpErrorFields");function vp(e){return e instanceof Xe.JWTExpired?"expired":e instanceof Xe.JWTClaimValidationFailed?"claim":e instanceof Xe.JWSSignatureVerificationFailed?"signature":e instanceof Xe.JWKSNoMatchingKey?"jwks_no_match":e instanceof Xe.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(!un){let e=B();un=gp(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return un}n(kp,"readFederatedJwks");function Di(e){if(!e.user)throw w("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return xe(e.user,e.url)}n(Di,"resolveCurrentRequestPrincipal");async function ur(e,t={}){let r=Ip(e.headers.get("cookie")).get(pn);if(!r)return{};try{let{payload:o}=await Oi(r,await qi(),{algorithms:[Z],issuer:J,audience:$}),a=_p.parse(o);if(a.browserLoginOrigin!==Mi())return{evictCookie:ln(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 Xe.JWTExpired?{evictCookie:ln(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:ln(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:Mi()};e.principal.roles&&(r.roles=e.principal.roles);let o=await new yp(r).setProtectedHeader({alg:Z,typ:"JWT"}).setIssuer(J).setAudience($).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await qi());return Sp({value:o,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t})}n(lr,"createBrowserSessionCookie");async function Up(e){let t=B(),r=ye("tokenUrl"),o=ye("clientId"),a=ye("clientSecret"),i=new URL(j().actionPath("/oauth/callback"),He(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 rr(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=Cp(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 Oi(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:xe({sub:y.sub,data:y},e.requestUrl),subjectToken:{token:p.id_token,tokenType:at,expiresAt:typeof h.exp=="number"?I(new Date(h.exp*1e3)):void 0}}}catch(s){let u=ae(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 zi(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(zi,"resolveBrowserLoginCallbackIdentity");G();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 Hi=[{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=>F(e),"accepts"),matches:n((e,t)=>F(e)&&F(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 Bi(e){let t=Hi.find(r=>r.accepts(e.url));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}n(Bi,"evaluateBuiltInRedirectUriCompatibility");function ji(e){try{return new URL(e)}catch{return}}n(ji,"parseUrl");function Li(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=ji(e.registeredRedirectUri),r=ji(e.requestedRedirectUri);return t===void 0||r===void 0?!1:Hi.some(o=>o.matches?.(t,r))}n(Li,"redirectUriMatchesBuiltInCompatibility");var qp=1e4,Mp=5*1024,Dp=0,zp=90*24*60*60,Ni=["authorization_code","refresh_token",Lt,we],jp=["authorization_code","refresh_token"],Ji=[mo],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(Ni)).min(1).max(Ni.length).optional(),authorization_grant_profiles_supported:d.array(d.enum(Ji)).min(1).max(Ji.length).optional(),response_types:d.array(d.enum(Hp)).min(1).max(1).optional(),scope:d.literal(E).optional(),token_endpoint_auth_method:go.optional(),jwks_uri:d.string().min(1).optional()});function Lp(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&F(t))&&t.pathname!=="/"}catch{return!1}}n(Lp,"isCimdClientIdCandidate");function Gi(e,t){throw new m("invalid_client",vo({clientId:e})??"OAuth client is not registered.",void 0,t===void 0?void 0:{cause:t})}n(Gi,"invalidCimdClientError");function Qe(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(Bi({url:r}).kind==="rejected")throw new m(t,"redirect_uris must use HTTPS, loopback HTTP, or a native-app private-use URI scheme.")}n(Qe,"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 oa(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=Gt(r);for(let a of o.redirect_uris)Qe(a,"invalid_request");if(o.jwks_uri!==void 0&&st(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=Ft(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=se.parse(e);if(Lp(r)){B().gateway.downstreamCimdEnabled||Gi(r);try{return await Gp(r)}catch(a){Gi(r,a)}}let o=await b().readClient({clientId:r});if(o.kind==="found"){let a=o.client,i=xo(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=Gt({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 Fi(e,t){if(!e.metadata.redirect_uris.some(r=>Li({registeredRedirectUri:r,requestedRedirectUri:t})))throw w("invalid_request","redirect_uri is not registered for the client.")}n(Fi,"assertRedirectRegistered");function Fp(e){return e===void 0?[...jp]:Array.from(new Set(e))}n(Fp,"normalizeGrantTypes");function $p(e){try{st(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?se.parse(Ao({clientId:crypto.randomUUID(),jwksUri:e.jwksUri})):se.parse(`dcr:${crypto.randomUUID()}`)}n(Zp,"createDcrClientId");function et(e){if(e===void 0||e===E)return E;throw new m("invalid_request",`Only the ${E} scope is supported.`)}n(et,"assertSupportedOAuthScope");function Oe(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:"&&!F(o))throw new m("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let a=P(e,r),i=lo(),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(Oe,"resolveResource");async function $i(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)Qe(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=Gt({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=ie(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=ce();y.hashedClientSecret=await A(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($i,"registerDownstreamClient");function Kp(e){return e?.metadata?.idpSubjectTokenType!==Be&&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 Zi(e){let t=je(e.principal.subjectId);return(await b().batchGetUpstreamConnections([{owner:t,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId}]))[0]}n(Zi,"readIdJagSubjectConnection");async function mn(e){let t=Y().byOperationId.get(e.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag")return!1;let r=await Zi({connection:t.connection,principal:e.principal});return!Kp(r)}n(mn,"requiresIdJagSubjectTokenBinding");async function Ki(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 Zi({connection:t.connection,principal:e.principal});return b().upsertUpstreamConnection({id:r?.id??$t(),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 ue(e.subjectToken.token),idpSubjectTokenType:e.subjectToken.tokenType,idpSubjectTokenExpiresAt:e.subjectToken.expiresAt}})}n(Ki,"bindIdJagSubjectTokenForAuthorizationTransaction");function mr(e){return C`<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 Wi(e){return C`<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(Wi,"renderActions");var Vi=le('<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 Yi(e){return C`<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(Yi,"renderBannerWarning");var _R=le('<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>'),wR=le('<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 RR=le('<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:,",Xi=C`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);"`,Qi=C`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 Wi({state:e.state,setupAction:e.gateway.actionPath("/oauth/setup"),submitOnceAttrs:Xi,authorizeAttrs:X})}n(Xp,"renderActions");function fn(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(fn,"firstUserConnectHref");function Qp(e){let t=e.connectHref===void 0?X:C`<a class="button button--primary" href="${e.connectHref}" ${Qi}>Connect</a>`;return C`<form class="actions" method="post" action="${e.gateway.actionPath("/oauth/setup")}" ${Xi}><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?C`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${Qi}>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 es(e){return e?.find(t=>tm(t.src))?.src}n(es,"readIconHref");function rm(e){return es(e.serverIcons)??(e.transportHost===void 0?void 0:Jr(e.transportHost).src)}n(rm,"readUpstreamIconHref");function nm(e){let t=es(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:Yi({icon:Vi,message:e.setupMessage});return C`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>${t}`}n(om,"renderBody");function hn(e){let t=Yp(e.upstreams),r=fn(e.upstreams,e.gatewayOrigin,"not_connected",e.gateway),o=fn(e.upstreams,e.gatewayOrigin,"reconsent_required",e.gateway),a=fn(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"?C`<footer class="card__footer">${Qp({state:e.state,connectHref:i,gateway:e.gateway})}</footer>`:C`<footer class="card__footer">${em(a)}${Xp({state:e.state,gateway:e.gateway})}</footer>`;return Ke(Ve({title:`Authorize access \xB7 ${e.routeDisplayName}`,iconHref:s??Wp,styles:We,headerIcon:s===void 0?X:mr({iconHref:s,fallbackIconHref:Xt}),heading:"Authorize access",subhead:X,body:om({routeDisplayName:e.routeDisplayName,clientDisplayName:e.clientDisplayName,setupMessage:c}),footer:u}))}n(hn,"renderConsentPage");var am=1e4,ts="mcp-session-id",im;function is(){return{tools:[],prompts:[],resources:[]}}n(is,"emptyCapabilities");function rs(){return new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":Ar})}n(rs,"buildReadinessHeaders");async function ns(e){if(e.type==="bearer_token"){let o=rs();return o.set("authorization",`Bearer ${e.token}`),o}let t=await e.provider.tokens();if(!t)return;let r=rs();return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}n(ns,"buildAsyncCredentialHeaders");function os(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(Ht.parse({jsonrpc:jt,id:1,method:"initialize",params:{protocolVersion:Ar,capabilities:{},clientInfo:{name:"zuplo-mcp-gateway-readiness",version:"0.0.0"}}}))})}n(os,"buildInitializePreflight");async function gn(e){it(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(gn,"runPreflight");function yn(e){e.body?.cancel().catch(()=>{})}n(yn,"releasePreflightBody");async function sm(e){let t=e.response.headers.get(ts);if(!t)return;let r=new Headers(e.headers);r.set(ts,t),r.delete("content-type");try{let o=await gn(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));yn(o)}catch{}}n(sm,"terminatePreflightSession");async function ss(e){let{response:t}=e;return yn(t),t.status>=200&&t.status<300?(await sm(e),{kind:"ready",upstreamStatus:t.status,capabilities:is()}):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(ss,"classifyResponse");function as(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(as,"connectRequiredResult");async function cm(e){try{return ss({response:await gn(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:is()};let r=ir(t.upstreamServerId,e.route.operationId),o=Ze(r,e.subjectId),a=e.returnTo===void 0?o:{...o,returnTo:e.returnTo},i=new Request(e.requestUrl,{headers:e.requestHeaders}),c=await $e({request:i,routeAuth:a,preloadedConnection:e.preloadedConnection});if(c.kind==="connect_required")return as(c.payload);let s=await ns(c.credential);if(s===void 0)return{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens."};let u=os({upstreamUrl:t.mcpUrl,headers:s}),p;try{p=await gn(u)}catch(T){return{kind:"upstream_unavailable",message:T instanceof Error?T.message:"Upstream MCP server readiness preflight failed."}}if(p.status!==401)return ss({response:p,upstreamUrl:t.mcpUrl,headers:s});yn(p);let h=await $e({request:i,routeAuth:a,forceRefresh:!0,preloadedConnection:e.preloadedConnection});if(h.kind==="connect_required")return as(h.payload);let y=await ns(h.credential);return y===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:cm({request:os({upstreamUrl:t.mcpUrl,headers:y}),upstreamUrl:t.mcpUrl,headers:y})}n(dm,"checkUpstreamRouteReadinessImpl");function cs(e){return(im??dm)(e)}n(cs,"checkUpstreamRouteReadiness");function um(e){try{return new URL(e).host}catch{return}}n(um,"safeUrlHost");function ds(e){return e!==void 0&&e.length>0}n(ds,"hasItems");function lm(e){let t=e.serverInfo?.icons;if(ds(t))return t;let r=Qt(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?Po(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:ds(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 us(e){let t=Y().byOperationId.get(e);if(!t)throw w("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}n(us,"requireRoute");async function _n(e){let t=us(e.transaction.operationId),r=je(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 cs({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(_n,"requirementsForSetup");async function wn(e){let t=us(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(wn,"consentContext");function Rn(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}n(Rn,"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:fo,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}),Ce=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 ls(e){return typeof e=="string"&&e.length>0?e:void 0}n(ls,"readQueryString");function wm(e,t){let r=ls(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new m("invalid_target",hm)}let o=bo(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=Di(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 ps(e){return`${j().actionPath("/oauth/setup")}?state=${encodeURIComponent(e)}`}n(ps,"buildSetupReturnTo");async function ms(e){let t=await _n({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:ps(e.csrfToken)}),r=await wn({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders}),o={kind:"setup_page",html:hn({state:e.csrfToken,operationId:e.transaction.operationId,gateway:j(),upstreams:t,...r})};return e.setCookie!==void 0&&(o.setCookie=e.setCookie),o}n(ms,"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 bn(e,t={}){let r=gm.parse({...e.query,resource:wm(e,t.operationId),state:ls(e.query.state)}),o=et(r.scope);Qe(r.redirect_uri,"invalid_request");let a=new Date,i=se.parse(r.client_id),c=await pr(r.client_id,a);Fi(c,r.redirect_uri);try{let s=Oe(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:S.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 mn({operationId:s.operationId,principal:h});if(!h||T){let q=await xi({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 ki({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:S.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:s.operationId,attributes:{clientId:i,scope:o,responseType:r.response_type,subjectId:h.subjectId}}),ms({transaction:R.transaction,csrfToken:R.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookie:y})}catch(s){throw Sm({redirectUri:r.redirect_uri,clientState:r.state,cause:s})}}n(bn,"authorizeDownstreamClient");function Sm(e){if(e.cause instanceof Ce)return e.cause;let t=Cm(e.cause);return t?new Ce({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}n(Sm,"toDownstreamAuthorizeRedirectError");function Cm(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(Cm,"mapToOAuthRedirectError");async function fs(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 an(o),i={request:e,stateId:a.stateId};t.context!==void 0&&(i.context=t.context);let c=await zi(i),s=await Ui({browserLoginStateToken:o,principal:c.principal});if(await Ki({transaction:s.transaction,principal:c.principal,subjectToken:c.subjectToken}),await mn({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 ms({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(fs,"completeBrowserLoginCallback");async function hs(e){let t=B(),r=new URL(e.url);if(!F(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:nt.parse(fm),roles:mm};return{kind:"redirect",location:i,setCookie:await lr({principal:s,requestUrl:e.url,requestHeaders:e.headers})}}n(hs,"completeLocalDevBrowserLogin");function vm(e){let t=e.method==="POST"?e.body:e.query;return _m.parse(t)}n(vm,"readSetupContinueRequest");async function gs(e){let{state:t,decision:r}=vm({method:e.request.method,query:e.request.query,body:e.body}),o=new Date,a=await dn({csrfToken:t,now:o}),i=await bm(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await Ei({csrfToken:t,currentBrowserPrincipal:i,now:o})};let c=await Ti({csrfToken:t,currentBrowserPrincipal:i,now:o}),s=await _n({transaction:c,requestUrl:e.request.url,requestHeaders:e.request.headers,returnTo:ps(t)});if(r==="approve"&&Rn(s)&&await vi({csrfToken:t,currentBrowserPrincipal:i,now:o}),Rn(s)){let u=await wn({transaction:c,requestUrl:e.request.url,requestHeaders:e.request.headers});return{kind:"setup_page",html:hn({state:t,operationId:c.operationId,gateway:j(),upstreams:s,...u})}}return{kind:"redirect",location:await Pi({csrfToken:t,currentBrowserPrincipal:i,now:o})}}n(gs,"continueDownstreamAuthorizeSetup");G();import{createLocalJWKSet as jm,decodeJwt as Hm,errors as At,jwtVerify as Bm}from"jose";G();import{createRemoteJWKSet as Am,decodeJwt as xm,decodeProtectedHeader as km,errors as vt,jwtVerify as Um}from"jose";var bs=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 ys(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(ys,"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 _s(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(_s,"assertClientBinding");function ws(e){e.cnf!==void 0&&W("ID-JAG cnf-bound assertions require DPoP support.")}n(ws,"assertProofOfPossessionNotDeferred");function Rs(e){let t=Math.floor(e.now.getTime()/1e3)+bs;e.claims.iat>t&&W("ID-JAG iat must not be in the future.")}n(Rs,"assertIssuedAtNotInFuture");async function Is(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=ys(xm(e.assertion))}catch(s){if(s instanceof m)throw s;W("ID-JAG assertion is malformed.")}let o=He(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."),_s({claims:r,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),ws(r),Rs({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:bs,typ:Rr});c=ys(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 _s({claims:c,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),ws(c),Rs({claims:c,now:e.now}),{claims:c,trustedIssuer:i,subjectId:Io({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(Is,"verifyIdJagAssertion");var Lm=new Set(["authorization_code","refresh_token",we]),Nm=1e4,Jm=32*1024,Gm=2,Fm=60*60,In=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",[In.extend({grant_type:d.literal("authorization_code"),code:d.string().min(1),redirect_uri:d.string().min(1),code_verifier:Jt,resource:d.url().optional(),scope:d.literal(E).optional()}),In.extend({grant_type:d.literal("refresh_token"),refresh_token:d.string().min(1),resource:d.url().optional(),scope:d.literal(E).optional()}),In.extend({grant_type:d.literal(we),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 Cs(){return B().gateway.accessTokenTtlSeconds}n(Cs,"readAccessTokenTtlSeconds");function Vm(){return B().gateway.refreshTokenTtlSeconds}n(Vm,"readRefreshTokenTtlSeconds");function Ss(e,t){let r=Cs(),o=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),a=Math.min(r,o);return{expiresAt:I(ie(e,a)),expiresIn:a}}n(Ss,"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 vs(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(vs,"readBasicClientSecret");function As(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(As,"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 aa(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!==Nt||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=se.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=se.parse(e.clientId);if(ko(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 A(e.clientSecret)}}n(cf,"buildRuntimeHttpClientAuth");async function xs(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(xs,"resolveRuntimeHttpClientAuth");async function ks(e){Zm(e.body);let t=$m.parse(e.body),r=vs(e.authorizationHeader),o=As({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date,i=await xs({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(ks,"exchangeDownstreamToken");async function df(e){if(e.parsed.grant_type==="authorization_code"){Qe(e.parsed.redirect_uri,"invalid_request"),et(e.parsed.scope),e.parsed.resource!==void 0&&Oe(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let s=ce(),u=ce(),p=I(ie(e.now,Vm())),h=Ss(e.now,p),y=await b().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await A(e.parsed.code),redirectUri:e.parsed.redirect_uri,resource:e.parsed.resource,codeChallenge:await qo(e.parsed.code_verifier),currentRefreshTokenHash:await A(s),accessTokenHash:await A(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:S.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===we){et(e.parsed.scope),ef(e.requestHeaders);let s=await Is({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=Oe(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=ce(),R=I(new Date(s.claims.exp*1e3)),q=Ss(e.now,R),O=await b().issueAccessTokenForIdJag({clientAuth:e.clientAuth,accessTokenHash:await A(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:S.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}}}et(e.parsed.scope),e.parsed.resource!==void 0&&Oe(e.requestUrl??e.parsed.resource,e.parsed.resource,e.requestHeaders);let t=await A(e.parsed.refresh_token),r=e.parsed.refresh_token,o=ce(),a=I(ie(e.now,Cs())),i=await b().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:t,nextRefreshTokenHash:t,accessTokenHash:await A(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.");Oe(e.requestUrl??i.grant.resource,i.grant.resource,e.requestHeaders);let c=i.accessToken.expiresAt;return e.context&&v(e.context,{eventType:S.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 Us(e){let t=Km.parse(e.body),r=vs(e.authorizationHeader),o=As({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date;if((await b().revokeOAuthToken({clientAuth:await xs({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 A(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:S.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}n(Us,"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 pi(e,{maxBytes:uf,label:"Request body"})}n(ff,"readJsonBody");async function Cn(e){return mf(await mi(e,{maxBytes:lf,label:"Request body"}))}n(Cn,"readFormBody");async function Ps(e,t,r){let o=ae(r),a=r instanceof d.ZodError?ve(r):void 0,i={code:o??(r instanceof d.ZodError?"invalid_request":"internal_server_error")};return a!==void 0&&(i.detail=a),Dt(e,t,i)}n(Ps,"handleProblem");function Es(e){return e?.requestId}n(Es,"readBrowserRequestId");function Os(e){if(!(e instanceof f))return;let t=e.extensionMembers?.[ze];return typeof t=="string"?t:void 0}n(Os,"readUpstreamHtmlError");function Ts(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}n(Ts,"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 qe(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,he),t.contentType=Ts(e.error,De),t.upstreamUrl=Ts(e.error,ge)),t}n(qe,"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 Sn(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}n(Sn,"readZodOAuthErrorCode");function wf(e){let t={error:Sn(e)},r=ve(e);return r!==void 0&&(t.errorDescription=r),xt(t)}n(wf,"oauthZodErrorResponse");function Rf(e){let t=ae(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 vn(e,t={}){return e instanceof Ce?Ds(e):e instanceof m?_f(e,t):e instanceof d.ZodError?wf(e):Rf(e)??bf()}n(vn,"oauthProblemResponse");function An(e,t,r){let o=Ye(e.url),a=Es(t);if(r instanceof Ce)return Ds(r);if(r instanceof m){let s=Q("internal_server_error");return te({host:o,kind:Sf(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:qe({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 te({host:o,kind:"invalid_request",detail:ve(r)??"The authorization request was invalid.",developerDetail:ve(r)??"The authorization request was invalid.",code:Sn(r),diagnostic:qe({request:e,requestId:a,code:Sn(r),underlyingError:ve(r)??"The authorization request was invalid.",error:r}),requestId:a});let i=ae(r);if(i!==void 0){let s=Q(i);return te({host:o,kind:Ms(i),detail:s.publicDetail,developerDetail:s.status>=500||!(r instanceof Error)?s.publicDetail:r.message,code:i,diagnostic:qe({request:e,requestId:a,code:i,underlyingError:s.status>=500||!(r instanceof Error)?s.publicDetail:r.message,error:r}),requestId:a,upstreamHtml:Os(r),status:s.status})}let c=Q("internal_server_error");return te({host:o,kind:"internal_error",detail:c.publicDetail,developerDetail:c.publicDetail,code:"server_error",diagnostic:qe({request:e,requestId:a,code:"server_error",underlyingError:c.publicDetail,error:r}),requestId:a,status:c.status})}n(An,"browserOAuthProblemResponse");function qs(e,t,r){let o=Ye(e.url),a=Es(t),i=ae(r);if(i!==void 0){let s=Q(i);return te({host:o,kind:Ms(i),detail:s.publicDetail,developerDetail:s.status>=500||!(r instanceof Error)?s.publicDetail:r.message,code:i,diagnostic:qe({request:e,requestId:a,code:i,underlyingError:s.status>=500||!(r instanceof Error)?s.publicDetail:r.message,error:r}),requestId:a,upstreamHtml:Os(r),status:s.status})}if(r instanceof d.ZodError)return te({host:o,kind:"invalid_request",detail:ve(r)??"The authorization request was invalid.",developerDetail:ve(r)??"The authorization request was invalid.",code:"invalid_request",diagnostic:qe({request:e,requestId:a,code:"invalid_request",underlyingError:ve(r)??"The authorization request was invalid.",error:r}),requestId:a});let c=Q("internal_server_error");return te({host:o,kind:"internal_error",detail:c.publicDetail,developerDetail:c.publicDetail,code:"internal_server_error",diagnostic:qe({request:e,requestId:a,code:"internal_server_error",underlyingError:c.publicDetail,error:r}),requestId:a,status:c.status})}n(qs,"browserGatewayProblemResponse");function Sf(e){return e==="server_error"?"internal_error":"invalid_request"}n(Sf,"readOAuthBrowserErrorKind");function Ms(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(Ms,"readGatewayBrowserErrorKind");function pe(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 Ce)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=ae(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(pe,"logUnexpectedOAuthHandlerError");function Ds(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(Ds,"downstreamAuthorizeRedirectErrorResponse");function ve(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}n(ve,"formatZodErrorDetail");function Cf(e,t){let r={event:"browser_login_callback_failed",code:ae(t)??"invalid_request"};L(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}n(Cf,"logBrowserLoginCallbackFailure");function zs(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(zs,"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 zs(e)}n(fr,"authorizeResultResponse");async function js(e,t){try{return Response.json(_o(e.url,e.headers))}catch(r){return pe(t,"oauth_authorization_server_metadata_failed",r),Ps(e,t,r)}}n(js,"authorizationServerMetadataHandler");async function Hs(e,t){try{let r=xr(e.params.routePath);return Response.json(wo({operationId:r.operationId,requestUrl:e.url,requestHeaders:e.headers}))}catch(r){return pe(t,"oauth_authorization_server_metadata_failed",r),Ps(e,t,r)}}n(Hs,"scopedAuthorizationServerMetadataHandler");async function Bs(e,t){try{let r=await $i(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:S.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 pe(t,"oauth_register_failed",r),vn(r)}}n(Bs,"registerHandler");async function Ls(e,t){try{return fr(await bn(e,{context:t}))}catch(r){return pe(t,"oauth_authorize_failed",r),An(e,t,r)}}n(Ls,"authorizeHandler");async function Ns(e,t){try{let r=xr(e.params.routePath);return fr(await bn(e,{operationId:r.operationId,context:t}))}catch(r){return pe(t,"oauth_authorize_scoped_failed",r),An(e,t,r)}}n(Ns,"scopedAuthorizeHandler");async function Js(e,t){try{let r=await fs(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 Cf(t,r),qs(e,t,r)}}n(Js,"callbackHandler");async function Gs(e,t){try{return zs(await hs(e))}catch(r){return pe(t,"oauth_dev_login_failed",r),An(e,t,r)}}n(Gs,"devLoginHandler");async function Fs(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await gs({request:e,body:e.method==="POST"?await Cn(e):void 0,context:t});return fr(r)}catch(r){return pe(t,"oauth_setup_failed",r),qs(e,t,r)}}n(Fs,"setupHandler");async function $s(e,t){try{return Response.json(await ks({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 pe(t,"oauth_token_failed",r),vn(r)}}n($s,"tokenHandler");async function Zs(e,t){try{return await Us({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 pe(t,"oauth_revoke_failed",r),vn(r)}}n(Zs,"revokeHandler");function Ks(e){return C`<p data-gateway-error-code="${e.code}">${e.body}</p>`}n(Ks,"renderBrowserResult");var vf="text/html; charset=utf-8",Af="none";function xf(e){let t=Nr(e.host);return Ve({title:e.title,iconHref:t,styles:We,headerIcon:mr({iconHref:t,fallbackIconHref:Xt}),heading:e.title,subhead:"",body:Ks({body:e.body,code:e.code??Af}),footer:""})}n(xf,"browserResultHtml");function kf(e,t=200){return new Response(Ke(e),{status:t,headers:{"content-type":vf,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(kf,"browserResultResponse");function Ws(e){return kf(xf(e))}n(Ws,"browserConnectionSuccessResponse");function hr(e,t,r={}){let o=Wn(t);return te({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"},Vs=Symbol("upstream-request");function kt(e,t){Object.defineProperty(e,Vs,{configurable:!0,value:t})}n(kt,"setUpstreamRequestContext");function Pf(e){let t=e[Vs];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 Me(e){if(typeof e=="string"&&e.length!==0)return e}n(Me,"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=Me(e);return t?zt.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=Me(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=xe(e.user,e.url),u={kind:"connect",...Ze(r,s.subjectId),redirect:o},p=ro(Me(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 Ia(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=Bt(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=Xn.parse(qf(e,"connection"));switch(r){case"connect":kt(e,await Hf(e,o));return;case"callback":{let a=Me(e.query.error);if(a){let s={kind:"callback_provider_error",upstreamServerId:o,error:a},u=Me(e.query.error_description);u!==void 0&&(s.errorDescription=u),kt(e,s);return}let i=Me(e.query.code),c=Me(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 Ae.badRequest(e,t,{code:a,detail:i});case"authentication_required":return Ae.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 xn(e){try{return new URL(e.url).pathname}catch{return}}n(xn,"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 Ys(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=Gf(r))}n(Ys,"addErrorAttributes");function kn(e){if(!(e instanceof f))return;let t=e.extensionMembers?.[g];return Mt(t)?t:void 0}n(kn,"readRuntimeGatewayCode");function Xs(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}n(Xs,"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:S.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:xn(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:xn(e),upstreamServerId:r.upstreamServerId}});case"callback_authorization_code":return r}}n($f,"requireAuthorizationCallbackRequest");function Zf(e,t){v(e,{eventType:S.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}n(Zf,"emitCallbackReceivedAnalyticsEvent");function Kf(e,t){v(e,{eventType:S.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 Ws({host:Ye(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 Ys(t,"error",e),e instanceof Error&&Ys(t,"cause",Jf(e)),t}n(Vf,"buildTokenExchangeFailureAttributes");function Yf(e){v(e.context,{eventType:S.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:kn(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=kn(t),o=Kn(r)?r:"upstream_token_exchange_failed",a={code:o,requestId:e.context.requestId,routePath:xn(e.request),upstreamServerId:e.callbackRequest.upstreamServerId,underlyingError:t instanceof Error?t.message:void 0,...t instanceof f?{httpStatus:Ff(t,he),contentType:Xs(t,De),upstreamUrl:Xs(t,ge)}:{}};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?.[ze];return typeof t=="string"?t:void 0}n(Qf,"readUpstreamHtmlError");async function Un(e,t){let r=Ut(e,Nf),o=Ye(e.url),a=$f(e,t,r,o);if(a instanceof Response)return a;Zf(t,a);try{let i=await ri({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:kn(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(Un,"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 Qs(e,t){let r=Ut(e,"connect"),o=await ti({request:e,connectRequest:r});if(v(t,{eventType:S.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 or({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(Qs,"connectHandler");async function ec(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"),Ae.notFound(e,t,{code:"not_found",detail:eh(o)})}}n(ec,"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 Tn(e){return async(t,r)=>t.method==="OPTIONS"?nh():oh(await e(t,r))}n(Tn,"wrapWellKnownHandler");var nc=[{routeName:"oauth_as_metadata",mount:"root",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:Tn(js),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",mount:"root",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:Tn(Hs),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",mount:"root",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:Tn(Ro),corsPolicy:"anything-goes"},{routeName:"oauth_register",mount:"action",path:"/oauth/register",methods:["POST"],handler:Bs},{routeName:"oauth_authorize",mount:"action",path:"/oauth/authorize",methods:["GET"],handler:Ls},{routeName:"oauth_authorize_scoped",mount:"action",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:Ns},{routeName:"oauth_callback",mount:"action",path:"/oauth/callback",methods:["GET"],handler:Js},{routeName:"oauth_dev_login",mount:"action",path:"/oauth/dev-login",methods:["GET"],handler:Gs},{routeName:"oauth_setup",mount:"action",path:"/oauth/setup",methods:["GET","POST"],handler:Fs},{routeName:"oauth_token",mount:"action",path:"/oauth/token",methods:["POST"],handler:$s},{routeName:"oauth_revoke",mount:"action",path:"/oauth/revoke",methods:["POST"],handler:Zs},{routeName:"upstream_client_metadata",mount:"action",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:gr("client_metadata",ec)},{routeName:"upstream_connect",mount:"action",path:"/auth/connections/:connection/connect",methods:["GET"],handler:gr("connect",Qs)},{routeName:"upstream_callback",mount:"action",path:"/auth/connections/:connection/callback",methods:["GET"],handler:gr("callback",Un)}],ah=nc.filter(e=>!e.routeName.startsWith("upstream_")),ih=nc.filter(e=>e.routeName.startsWith("upstream_"));function sh(e){let t=so({routes:e.routes,policies:e.policies,gateway:e.gateway});return co(t),t}n(sh,"initializeMcpGatewayConnectionRegistry");function ch(e){return[...e.byOperationId.values()].some(t=>t.downstreamOAuth!==void 0)}n(ch,"hasDownstreamOAuthRoutes");function dh(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(dh,"readSingletonDownstreamOAuthConfig");function uh(e,t,r){let o=String(t.params.routePath??""),a=e.byRoutePath.get(ho(o));if(a===void 0)return;let i=a?.downstreamOAuth?.config;return i===void 0?Dt(t,r,{code:"not_found",detail:"The requested MCP route does not expose downstream OAuth."}):i}n(uh,"readScopedDownstreamOAuthConfig");function lh(e){return e.path==="/.well-known/oauth-authorization-server/:routePath*"||e.path==="/.well-known/oauth-protected-resource/:routePath*"||e.path==="/oauth/authorize/:routePath*"}n(lh,"routeUsesScopedOAuthConfig");function tc(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&&$n(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(tc,"wrapInternalHandler");function rc(e,t,r,o){e.addPluginRoute({path:th(t,r),methods:t.methods,handler:o,processors:[Dn],corsPolicy:t.corsPolicy??"none"})}n(rc,"addInternalRoute");function oc(e,t){let r=sh(t),o=ch(r),a=r.connectionsById.size>0,i,c=n(()=>(i===void 0&&(i=dh(r)),i),"readSingletonOAuthConfig");if(o)for(let s of ah){let u=lh(s)?(p,h)=>uh(r,p,h):c;rc(e,s,r.gateway,tc(s.routeName,s.handler,u))}if(a)for(let s of ih)rc(e,s,r.gateway,tc(s.routeName,s.handler))}n(oc,"registerMcpGatewayInternalRoutes");var Pn=class extends qn{static{n(this,"McpGatewayPlugin")}#e;constructor(t={}){super(),this.#e=Zn(t)}registerRoutes(t){let r=t.parsedRouteData;r&&oc(t.router,{routes:r.routes,policies:r.policies,gateway:this.#e})}};var ph=new TextDecoder;function mh(e){if(e)try{return JSON.parse(ph.decode(e))}catch{return}}n(mh,"readBodyJson");function me(e){return e&&typeof e=="object"?e:void 0}n(me,"readRecord");function Tt(e,t){let r=me(e)?.[t];return typeof r=="string"?r:void 0}n(Tt,"readStringProperty");function ic(e,t){let r=me(e)?.[t];return typeof r=="number"?r:void 0}n(ic,"readNumberProperty");function ac(e,t){return ic(e,"code")??(t.status>=400?t.status:void 0)}n(ac,"readErrorCode");function sc(e){return Array.isArray(e)?e.map(sc).find(t=>t?.method):me(e)}n(sc,"readJsonRpcMessage");function cc(e){let t=sc(mh(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(cc,"buildBaseCapabilityInput");function dc(e){return e==="tools/list"||e==="prompts/list"||e==="resources/list"||e==="resources/templates/list"}n(dc,"isCapabilityListMethod");function fh(e,t,r){let i=me(r)?.[e==="resources/templates/list"?"resourceTemplates":t==="tool"?"tools":t==="prompt"?"prompts":"resources"];return Array.isArray(i)?i.length:void 0}n(fh,"readItemCount");async function hh(e){try{return await e.clone().json()}catch{return}}n(hh,"readResponseJson");function uc(e){let t=cc(e);return!t||dc(t.mcpMethod)?null:{eventType:S.MCP_CAPABILITY_INVOKED,outcome:"success",...t}}n(uc,"buildCapabilityInvokedAnalyticsInput");async function lc(e,t){let r=cc(e);if(!r)return null;let o=me(await hh(t)),a=me(o?.error),i=me(a?.data),c=o?.result,s=r.mcpMethod==="tools/call"&&me(c)?.isError===!0;if(me(i?.connectRequired))return{eventType:S.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",...r,httpStatusCode:t.status,reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required",errorCode:ic(a,"code"),mcpErrorType:Tt(a,"message")};if(dc(r.mcpMethod)){let u=t.status>=400?void 0:fh(r.mcpMethod,r.capabilityType,c);return{eventType:S.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:ac(a,t)}:{},...u===void 0?{}:{attributes:{itemCount:u}}}}return t.status>=400||a?{eventType:S.MCP_CAPABILITY_FAILED,outcome:"failure",...r,httpStatusCode:t.status,reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"capability_error",errorCode:ac(a,t),mcpErrorType:Tt(a,"message")}:{eventType:S.MCP_CAPABILITY_COMPLETED,outcome:s?"application_error":"success",...r,httpStatusCode:t.status,toolResultIsError:s,applicationError:s}}n(lc,"buildCapabilityFinalAnalyticsInput");var gh={Allow:"POST"};async function yh(e){try{return await e.clone().arrayBuffer()}catch{return}}n(yh,"readRequestBody");function pc(e){try{let t=uo(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(pc,"readRouteAnalyticsFields");function mc(e){return So(e.user,e.url,e.headers)?.subjectId}n(mc,"readRequestSubjectId");function _h(e){let t=uc(e.requestBody);t&&v(e.context,{...t,...pc(e.context),httpMethod:e.request.method,subjectId:mc(e.request),transport:"http"})}n(_h,"emitCapabilityInvokedAnalytics");async function wh(e){let t=await lc(e.requestBody,e.response);t&&v(e.context,{...t,...pc(e.context),httpMethod:e.request.method,subjectId:mc(e.request),transport:"http",latencyMs:Date.now()-e.startedAt})}n(wh,"emitCapabilityFinalAnalytics");async function Rh(e,t){if(e.method==="GET")return Ae.methodNotAllowed(e,t,{detail:"MCP Gateway routes support stateless Streamable HTTP requests over POST. Server-sent event GET streams are not supported."},gh);let r=Date.now(),o=await yh(e);_h({context:t,request:e,requestBody:o});let a=await Jn(e,t);return await wh({context:t,request:e,requestBody:o,response:a,startedAt:r}),a}n(Rh,"McpProxyHandler");export{Cc as McpAuth0OAuthInboundPolicy,kr as McpCapabilityFilterInboundPolicy,fc as McpClerkOAuthInboundPolicy,hc as McpCognitoOAuthInboundPolicy,gc as McpEntraOAuthInboundPolicy,Pn as McpGatewayPlugin,yc as McpGoogleOAuthInboundPolicy,_c as McpKeycloakOAuthInboundPolicy,wc as McpLogtoOAuthInboundPolicy,vc as McpOAuthInboundPolicy,Rc as McpOktaOAuthInboundPolicy,bc as McpOneLoginOAuthInboundPolicy,Ic as McpPingOAuthInboundPolicy,Rh as McpProxyHandler,on as McpTokenExchangeInboundPolicy,Sc as McpWorkosOAuthInboundPolicy};
48
+ ></iframe>`}n(Vl,"renderUpstreamHtml");var ui="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===ui&&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 li(e,t){let r=t.label??"Request body";ep(e,t.expectedContentTypes),tp(e,t.maxBytes,r);let o=await tr(e.body,{maxBytes:t.maxBytes,createLimitError:n(()=>cr(`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(o)}n(li,"readBoundedTextBody");async function pi(e,t){let r=await li(e,{...t,expectedContentTypes:[ui]});try{return JSON.parse(r)}catch(o){throw cr("Request body must be valid JSON.",o)}}n(pi,"readBoundedJsonBody");async function mi(e,t){let r=await li(e,{...t,expectedContentTypes:[Yl]});return new URLSearchParams(r)}n(mi,"readBoundedFormUrlEncodedBody");F();F();import{errors as fi,jwtVerify as hi,SignJWT as gi}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:Sr,exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),ap=d.object({purpose:d.literal("gateway_authorization_setup"),transactionId:Ir,stateId:Sr,exp:d.number().int().positive(),iat:d.number().int().positive().optional()});async function yi(){return te({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ie(e,"browser-login"),"derive")})}n(yi,"getBrowserLoginKey");async function _i(){return te({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ie(e,"authorization-csrf"),"derive")})}n(_i,"getCsrfKey");function wi(e){return{now:e.now??new Date,ttlSeconds:Ri()}}n(wi,"readPendingTransactionDependencies");function Ri(){return B().browserLogin.stateTtlSeconds}n(Ri,"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(_e("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",_e("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 bi(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}n(bi,"toPendingPrincipal");function Ii(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:bi(e.principal)}}n(Ii,"createTransactionRecord");async function Si(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(Si,"startPendingTransaction");async function dp(e){return new gi({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 yi())}n(dp,"signBrowserLoginState");async function Ci(e){return new gi({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 _i())}n(Ci,"signCsrfToken");async function an(e){try{let{payload:t}=await hi(e,await yi(),{algorithms:[K],issuer:J,audience:Z}),r=op.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof fi.JWTExpired?w("oauth_state_expired","Browser login state has expired.",t):w("oauth_state_invalid","Browser login state could not be verified.",t)}}n(an,"verifyBrowserLoginStateToken");async function dr(e){try{let{payload:t}=await hi(e,await _i(),{algorithms:[K],issuer:J,audience:Z});return{transactionId:ap.parse(t).transactionId}}catch(t){throw t instanceof fi.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 sn(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}n(sn,"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 cn(e){return e==="principal_mismatch"?"oauth_callback_mismatch":sn(e==="consumed_already"?"consumed_already":e)}n(cn,"setupDecisionErrorCode");async function vi(e){let t=e.now??new Date,r=await dr(e.csrfToken),o=await b().markAuthorizationSetupApproved({transactionId:r.transactionId,currentStateHash:await A(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:I(t)});if(o.kind!=="marked")throw w(cn(o.kind),"Authorization setup state is invalid, expired, or already used.");return Ai({kind:"available",record:o.transaction})}n(vi,"markSetupApproved");function Ai(e){if(e.kind!=="available")throw w(sn(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(Ai,"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 xi(e){let t=e.now??new Date,r=Ri(),o=Cr(),a=vr(),i=await dp({transactionId:o,stateId:a,ttlSeconds:r}),c=Ii({id:o,transaction:e.transaction,currentStateHash:await A(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 Si({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(xi,"startAwaitingLogin");async function ki(e){let{now:t,ttlSeconds:r}=wi(e),o=Cr(),a=await Ci({transactionId:o,ttlSeconds:r}),i=Ii({id:o,transaction:e.transaction,currentStateHash:await A(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 Si({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(ki,"startAwaitingSetup");async function Ui(e){let{now:t,ttlSeconds:r}=wi(e),o=await an(e.browserLoginStateToken),a=await Ci({transactionId:o.transactionId,ttlSeconds:r}),i=lp(await b().advancePendingAuthorization({transactionId:o.transactionId,expectedPhase:"awaiting_login",currentStateHash:await A(e.browserLoginStateToken),nextStateHash:await A(a),nextPhase:"awaiting_setup",principal:bi(e.principal),now:I(t)}));if(i.kind!=="advanced")throw w(sn(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(Ui,"completeLogin");async function Ti(e){let t=await dn(e);return pp({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}n(Ti,"getSetup");async function dn(e){let t=e.now??new Date,r=await dr(e.csrfToken);return Ai(up(await b().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await A(e.csrfToken),now:I(t)})))}n(dn,"getSetupTransaction");async function mp(e){let t=await dr(e.csrfToken),r=de(),o=I(se(e.now,np)),a=await b().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await A(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await A(r),authorizationCodeExpiresAt:o,grantId:yo(),now:I(e.now)});if(a.kind!=="approved")throw w(a.kind==="cancelled"?"oauth_state_invalid":cn(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 A(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:I(e.now)});if(r.kind!=="cancelled")throw w(r.kind==="approved"?"oauth_state_invalid":cn(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 Pi(e){let t=e.now??new Date;return mp({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Pi,"approve");async function Ei(e){let t=e.now??new Date;return fp({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}n(Ei,"cancel");F();import{createRemoteJWKSet as gp,errors as Qe,jwtVerify as Oi,SignJWT as yp}from"jose";var pn="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()),un;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 qi(){return te({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Ie(e,"browser-session"),"derive")})}n(qi,"getBrowserSessionKey");function ln(e,t){let r=new URL(P(e,t)),o=[`${pn}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return r.protocol==="https:"&&o.push("Secure"),o.join("; ")}n(ln,"buildBrowserSessionEvictionCookie");function Sp(e){let t=new URL(P(e.requestUrl,e.requestHeaders)),r=[`${pn}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}n(Sp,"serializeSessionCookie");function Mi(){return new URL(_e("url")).origin}n(Mi,"readBrowserLoginOrigin");function Cp(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(Cp,"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(!un){let e=B();un=gp(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return un}n(kp,"readFederatedJwks");function Di(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(Di,"resolveCurrentRequestPrincipal");async function ur(e,t={}){let r=Ip(e.headers.get("cookie")).get(pn);if(!r)return{};try{let{payload:o}=await Oi(r,await qi(),{algorithms:[K],issuer:J,audience:Z}),a=_p.parse(o);if(a.browserLoginOrigin!==Mi())return{evictCookie:ln(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:ln(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:ln(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:Mi()};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 qi());return Sp({value:o,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,ttlSeconds:t})}n(lr,"createBrowserSessionCookie");async function Up(e){let t=B(),r=_e("tokenUrl"),o=_e("clientId"),a=_e("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 rr(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=Cp(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 Oi(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 zi(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(zi,"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 Hi=[{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 Bi(e){let t=Hi.find(r=>r.accepts(e.url));return t===void 0?{kind:"rejected"}:{kind:"allowed",ruleId:t.id,mode:t.mode}}n(Bi,"evaluateBuiltInRedirectUriCompatibility");function ji(e){try{return new URL(e)}catch{return}}n(ji,"parseUrl");function Li(e){if(e.registeredRedirectUri===e.requestedRedirectUri)return!0;let t=ji(e.registeredRedirectUri),r=ji(e.requestedRedirectUri);return t===void 0||r===void 0?!1:Hi.some(o=>o.matches?.(t,r))}n(Li,"redirectUriMatchesBuiltInCompatibility");var qp=1e4,Mp=5*1024,Dp=0,zp=90*24*60*60,Ni=["authorization_code","refresh_token",Lt,Re],jp=["authorization_code","refresh_token"],Ji=[mo],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(Ni)).min(1).max(Ni.length).optional(),authorization_grant_profiles_supported:d.array(d.enum(Ji)).min(1).max(Ji.length).optional(),response_types:d.array(d.enum(Hp)).min(1).max(1).optional(),scope:d.literal(E).optional(),token_endpoint_auth_method:go.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 Gi(e,t){throw new m("invalid_client",vo({clientId:e})??"OAuth client is not registered.",void 0,t===void 0?void 0:{cause:t})}n(Gi,"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(Bi({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 oa(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=Gt(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=Ft(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=ce.parse(e);if(Lp(r)){B().gateway.downstreamCimdEnabled||Gi(r);try{return await Gp(r)}catch(a){Gi(r,a)}}let o=await b().readClient({clientId:r});if(o.kind==="found"){let a=o.client,i=xo(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=Gt({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 Fi(e,t){if(!e.metadata.redirect_uris.some(r=>Li({registeredRedirectUri:r,requestedRedirectUri:t})))throw w("invalid_request","redirect_uri is not registered for the client.")}n(Fi,"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?ce.parse(Ao({clientId:crypto.randomUUID(),jwksUri:e.jwksUri})):ce.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=lo(),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 $i(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=Gt({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=de();y.hashedClientSecret=await A(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($i,"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 Zi(e){let t=He(e.principal.subjectId);return(await b().batchGetUpstreamConnections([{owner:t,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId}]))[0]}n(Zi,"readIdJagSubjectConnection");async function mn(e){let t=X().byOperationId.get(e.operationId);if(t?.connection===void 0||t.connection.authMode!=="id-jag")return!1;let r=await Zi({connection:t.connection,principal:e.principal});return!Kp(r)}n(mn,"requiresIdJagSubjectTokenBinding");async function Ki(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 Zi({connection:t.connection,principal:e.principal});return b().upsertUpstreamConnection({id:r?.id??$t(),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 le(e.subjectToken.token),idpSubjectTokenType:e.subjectToken.tokenType,idpSubjectTokenExpiresAt:e.subjectToken.expiresAt}})}n(Ki,"bindIdJagSubjectTokenForAuthorizationTransaction");function mr(e){return C`<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 Wi(e){return C`<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(Wi,"renderActions");var Vi=pe('<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 Yi(e){return C`<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(Yi,"renderBannerWarning");var wR=pe('<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>'),RR=pe('<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 bR=pe('<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:,",Xi=C`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);"`,Qi=C`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 Wi({state:e.state,setupAction:e.gateway.actionPath("/oauth/setup"),submitOnceAttrs:Xi,authorizeAttrs:Q})}n(Xp,"renderActions");function fn(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(fn,"firstUserConnectHref");function Qp(e){let t=e.connectHref===void 0?Q:C`<a class="button button--primary" href="${e.connectHref}" ${Qi}>Connect</a>`;return C`<form class="actions" method="post" action="${e.gateway.actionPath("/oauth/setup")}" ${Xi}><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?C`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${Qi}>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(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 es(e){return e?.find(t=>tm(t.src))?.src}n(es,"readIconHref");function rm(e){return es(e.serverIcons)??(e.transportHost===void 0?void 0:Jr(e.transportHost).src)}n(rm,"readUpstreamIconHref");function nm(e){let t=es(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?Q:Yi({icon:Vi,message:e.setupMessage});return C`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.routeDisplayName}</strong>' on your behalf?</p>${t}`}n(om,"renderBody");function hn(e){let t=Yp(e.upstreams),r=fn(e.upstreams,e.gatewayOrigin,"not_connected",e.gateway),o=fn(e.upstreams,e.gatewayOrigin,"reconsent_required",e.gateway),a=fn(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"?C`<footer class="card__footer">${Qp({state:e.state,connectHref:i,gateway:e.gateway})}</footer>`:C`<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?Q:mr({iconHref:s,fallbackIconHref:Xt}),heading:"Authorize access",subhead:Q,body:om({routeDisplayName:e.routeDisplayName,clientDisplayName:e.clientDisplayName,setupMessage:c}),footer:u}))}n(hn,"renderConsentPage");var am=1e4,ts="mcp-session-id",im;function is(){return{tools:[],prompts:[],resources:[]}}n(is,"emptyCapabilities");function rs(){return new Headers({accept:"application/json, text/event-stream","content-type":"application/json","mcp-protocol-version":Ar})}n(rs,"buildReadinessHeaders");async function ns(e){if(e.type==="bearer_token"){let o=rs();return o.set("authorization",`Bearer ${e.token}`),o}let t=await e.provider.tokens();if(!t)return;let r=rs();return r.set("authorization",`${t.token_type??"Bearer"} ${t.access_token}`),r}n(ns,"buildAsyncCredentialHeaders");function os(e){return new Request(e.upstreamUrl,{method:"POST",headers:e.headers,body:JSON.stringify(Ht.parse({jsonrpc:jt,id:1,method:"initialize",params:{protocolVersion:Ar,capabilities:{},clientInfo:{name:"zuplo-mcp-gateway-readiness",version:"0.0.0"}}}))})}n(os,"buildInitializePreflight");async function gn(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 Et.fetch(o)}finally{clearTimeout(r)}}n(gn,"runPreflight");function yn(e){e.body?.cancel().catch(()=>{})}n(yn,"releasePreflightBody");async function sm(e){let t=e.response.headers.get(ts);if(!t)return;let r=new Headers(e.headers);r.set(ts,t),r.delete("content-type");try{let o=await gn(new Request(e.upstreamUrl,{method:"DELETE",headers:r}));yn(o)}catch{}}n(sm,"terminatePreflightSession");async function ss(e){let{response:t}=e;return yn(t),t.status>=200&&t.status<300?(await sm(e),{kind:"ready",upstreamStatus:t.status,capabilities:is()}):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(ss,"classifyResponse");function as(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(as,"connectRequiredResult");async function cm(e){try{return ss({response:await gn(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:is()};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 as(c.payload);let s=await ns(c.credential);if(s===void 0)return{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens."};let u=os({upstreamUrl:t.mcpUrl,headers:s}),p;try{p=await gn(u)}catch(T){return{kind:"upstream_unavailable",message:T instanceof Error?T.message:"Upstream MCP server readiness preflight failed."}}if(p.status!==401)return ss({response:p,upstreamUrl:t.mcpUrl,headers:s});yn(p);let h=await Ze({request:i,routeAuth:a,forceRefresh:!0,preloadedConnection:e.preloadedConnection});if(h.kind==="connect_required")return as(h.payload);let y=await ns(h.credential);return y===void 0?{kind:"upstream_auth_rejected",status:401,message:"Upstream credential did not produce tokens after refresh."}:cm({request:os({upstreamUrl:t.mcpUrl,headers:y}),upstreamUrl:t.mcpUrl,headers:y})}n(dm,"checkUpstreamRouteReadinessImpl");function cs(e){return(im??dm)(e)}n(cs,"checkUpstreamRouteReadiness");function um(e){try{return new URL(e).host}catch{return}}n(um,"safeUrlHost");function ds(e){return e!==void 0&&e.length>0}n(ds,"hasItems");function lm(e){let t=e.serverInfo?.icons;if(ds(t))return t;let r=Qt(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?Po(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:ds(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 us(e){let t=X().byOperationId.get(e);if(!t)throw w("unknown_mcp_route",`Unknown MCP route: ${e}`);return t}n(us,"requireRoute");async function _n(e){let t=us(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 cs({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(_n,"requirementsForSetup");async function wn(e){let t=us(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(wn,"consentContext");function Rn(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}n(Rn,"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:fo,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 ls(e){return typeof e=="string"&&e.length>0?e:void 0}n(ls,"readQueryString");function wm(e,t){let r=ls(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new m("invalid_target",hm)}let o=bo(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=Di(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 ps(e){return`${j().actionPath("/oauth/setup")}?state=${encodeURIComponent(e)}`}n(ps,"buildSetupReturnTo");async function ms(e){let t=await _n({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders,returnTo:ps(e.csrfToken)}),r=await wn({transaction:e.transaction,requestUrl:e.requestUrl,requestHeaders:e.requestHeaders}),o={kind:"setup_page",html:hn({state:e.csrfToken,operationId:e.transaction.operationId,gateway:j(),upstreams:t,...r})};return e.setCookie!==void 0&&(o.setCookie=e.setCookie),o}n(ms,"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 bn(e,t={}){let r=gm.parse({...e.query,resource:wm(e,t.operationId),state:ls(e.query.state)}),o=tt(r.scope);et(r.redirect_uri,"invalid_request");let a=new Date,i=ce.parse(r.client_id),c=await pr(r.client_id,a);Fi(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:S.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 mn({operationId:s.operationId,principal:h});if(!h||T){let q=await xi({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 ki({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:S.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:s.operationId,attributes:{clientId:i,scope:o,responseType:r.response_type,subjectId:h.subjectId}}),ms({transaction:R.transaction,csrfToken:R.csrfToken,requestUrl:e.url,requestHeaders:e.headers,setCookie:y})}catch(s){throw Sm({redirectUri:r.redirect_uri,clientState:r.state,cause:s})}}n(bn,"authorizeDownstreamClient");function Sm(e){if(e.cause instanceof ve)return e.cause;let t=Cm(e.cause);return t?new ve({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}n(Sm,"toDownstreamAuthorizeRedirectError");function Cm(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(Cm,"mapToOAuthRedirectError");async function fs(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 an(o),i={request:e,stateId:a.stateId};t.context!==void 0&&(i.context=t.context);let c=await zi(i),s=await Ui({browserLoginStateToken:o,principal:c.principal});if(await Ki({transaction:s.transaction,principal:c.principal,subjectToken:c.subjectToken}),await mn({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 ms({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(fs,"completeBrowserLoginCallback");async function hs(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(hs,"completeLocalDevBrowserLogin");function vm(e){let t=e.method==="POST"?e.body:e.query;return _m.parse(t)}n(vm,"readSetupContinueRequest");async function gs(e){let{state:t,decision:r}=vm({method:e.request.method,query:e.request.query,body:e.body}),o=new Date,a=await dn({csrfToken:t,now:o}),i=await bm(e.request,e.context);if(r==="cancel")return{kind:"redirect",location:await Ei({csrfToken:t,currentBrowserPrincipal:i,now:o})};let c=await Ti({csrfToken:t,currentBrowserPrincipal:i,now:o}),s=await _n({transaction:c,requestUrl:e.request.url,requestHeaders:e.request.headers,returnTo:ps(t)});if(r==="approve"&&Rn(s)&&await vi({csrfToken:t,currentBrowserPrincipal:i,now:o}),Rn(s)){let u=await wn({transaction:c,requestUrl:e.request.url,requestHeaders:e.request.headers});return{kind:"setup_page",html:hn({state:t,operationId:c.operationId,gateway:j(),upstreams:s,...u})}}return{kind:"redirect",location:await Pi({csrfToken:t,currentBrowserPrincipal:i,now:o})}}n(gs,"continueDownstreamAuthorizeSetup");F();import{createLocalJWKSet as jm,decodeJwt as Hm,errors as xt,jwtVerify as Bm}from"jose";F();import{createRemoteJWKSet as Am,decodeJwt as xm,decodeProtectedHeader as km,errors as At,jwtVerify as Um}from"jose";var bs=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 V(e){throw new m("invalid_grant",e)}n(V,"throwInvalidGrant");function qm(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(qm,"readJwtFailureKind");function Mm(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(Mm,"readSingleAudience");function ys(e){try{let t=Om.parse(e);return Mm(t),t}catch(t){if(t instanceof m)throw t;V("ID-JAG claims are invalid.")}}n(ys,"parseIdJagClaims");function Dm(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(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 _s(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(_s,"assertClientBinding");function ws(e){e.cnf!==void 0&&V("ID-JAG cnf-bound assertions require DPoP support.")}n(ws,"assertProofOfPossessionNotDeferred");function Rs(e){let t=Math.floor(e.now.getTime()/1e3)+bs;e.claims.iat>t&&V("ID-JAG iat must not be in the future.")}n(Rs,"assertIssuedAtNotInFuture");async function Is(e){let t;try{t=km(e.assertion)}catch{V("ID-JAG assertion is malformed.")}t.typ!==Rr&&V('ID-JAG header typ must be "oauth-id-jag+jwt".');let r;try{r=ys(xm(e.assertion))}catch(s){if(s instanceof m)throw s;V("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)&&V("ID-JAG issuer must be different from the gateway."),_s({claims:r,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),ws(r),Rs({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:bs,typ:Rr});c=ys(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"),V("ID-JAG assertion verification failed.")}return _s({claims:c,trustedIssuer:i,authenticatedClientId:e.authenticatedClientId,clientAuth:e.clientAuth}),ws(c),Rs({claims:c,now:e.now}),{claims:c,trustedIssuer:i,subjectId:Io({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(Is,"verifyIdJagAssertion");var Lm=new Set(["authorization_code","refresh_token",Re]),Nm=1e4,Jm=32*1024,Gm=2,Fm=60*60,In=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",[In.extend({grant_type:d.literal("authorization_code"),code:d.string().min(1),redirect_uri:d.string().min(1),code_verifier:Jt,resource:d.url().optional(),scope:d.literal(E).optional()}),In.extend({grant_type:d.literal("refresh_token"),refresh_token:d.string().min(1),resource:d.url().optional(),scope:d.literal(E).optional()}),In.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 Cs(){return B().gateway.accessTokenTtlSeconds}n(Cs,"readAccessTokenTtlSeconds");function Vm(){return B().gateway.refreshTokenTtlSeconds}n(Vm,"readRefreshTokenTtlSeconds");function Ss(e,t){let r=Cs(),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(Ss,"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 vs(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(vs,"readBasicClientSecret");function As(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(As,"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 xt.JWTExpired?"expired":e instanceof xt.JWTClaimValidationFailed?"claim":e instanceof xt.JWSSignatureVerificationFailed?"signature":e instanceof xt.JWKSNoMatchingKey?"jwks_no_match":e instanceof xt.JWTInvalid?"invalid":e instanceof d.ZodError?"schema":"other"}n(of,"readJwtFailureKind");async function af(e){let{response:t,json:r}=await aa(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!==Nt||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=ce.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=ce.parse(e.clientId);if(ko(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 A(e.clientSecret)}}n(cf,"buildRuntimeHttpClientAuth");async function xs(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(xs,"resolveRuntimeHttpClientAuth");async function ks(e){Zm(e.body);let t=$m.parse(e.body),r=vs(e.authorizationHeader),o=As({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date,i=await xs({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(ks,"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=de(),u=de(),p=I(se(e.now,Vm())),h=Ss(e.now,p),y=await b().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await A(e.parsed.code),redirectUri:e.parsed.redirect_uri,resource:e.parsed.resource,codeChallenge:await qo(e.parsed.code_verifier),currentRefreshTokenHash:await A(s),accessTokenHash:await A(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:S.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 Is({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=de(),R=I(new Date(s.claims.exp*1e3)),q=Ss(e.now,R),O=await b().issueAccessTokenForIdJag({clientAuth:e.clientAuth,accessTokenHash:await A(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:S.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 A(e.parsed.refresh_token),r=e.parsed.refresh_token,o=de(),a=I(se(e.now,Cs())),i=await b().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:t,nextRefreshTokenHash:t,accessTokenHash:await A(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:S.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 Us(e){let t=Km.parse(e.body),r=vs(e.authorizationHeader),o=As({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date;if((await b().revokeOAuthToken({clientAuth:await xs({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 A(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:S.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:o,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}n(Us,"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 pi(e,{maxBytes:uf,label:"Request body"})}n(ff,"readJsonBody");async function Cn(e){return mf(await mi(e,{maxBytes:lf,label:"Request body"}))}n(Cn,"readFormBody");async function Ps(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),Dt(e,t,i)}n(Ps,"handleProblem");function Es(e){return e?.requestId}n(Es,"readBrowserRequestId");function Os(e){if(!(e instanceof f))return;let t=e.extensionMembers?.[je];return typeof t=="string"?t:void 0}n(Os,"readUpstreamHtmlError");function Ts(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}n(Ts,"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,ge),t.contentType=Ts(e.error,ze),t.upstreamUrl=Ts(e.error,ye)),t}n(Me,"buildBrowserErrorDiagnostic");function kt(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(kt,"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=ee("internal_server_error");return kt({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:yf(e,t)})}n(_f,"oauthProtocolErrorResponse");function Sn(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}n(Sn,"readZodOAuthErrorCode");function wf(e){let t={error:Sn(e)},r=Ae(e);return r!==void 0&&(t.errorDescription=r),kt(t)}n(wf,"oauthZodErrorResponse");function Rf(e){let t=ie(e);if(t===void 0)return;let r=ee(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,kt(o)}n(Rf,"oauthGatewayProblemResponse");function bf(){let t={error:"server_error",status:500,errorDescription:ee("internal_server_error").publicDetail};return kt(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 vn(e,t={}){return e instanceof ve?Ds(e):e instanceof m?_f(e,t):e instanceof d.ZodError?wf(e):Rf(e)??bf()}n(vn,"oauthProblemResponse");function An(e,t,r){let o=Xe(e.url),a=Es(t);if(r instanceof ve)return Ds(r);if(r instanceof m){let s=ee("internal_server_error");return re({host:o,kind:Sf(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:Sn(r),diagnostic:Me({request:e,requestId:a,code:Sn(r),underlyingError:Ae(r)??"The authorization request was invalid.",error:r}),requestId:a});let i=ie(r);if(i!==void 0){let s=ee(i);return re({host:o,kind:Ms(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:Os(r),status:s.status})}let c=ee("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(An,"browserOAuthProblemResponse");function qs(e,t,r){let o=Xe(e.url),a=Es(t),i=ie(r);if(i!==void 0){let s=ee(i);return re({host:o,kind:Ms(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:Os(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=ee("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(qs,"browserGatewayProblemResponse");function Sf(e){return e==="server_error"?"internal_error":"invalid_request"}n(Sf,"readOAuthBrowserErrorKind");function Ms(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(Ms,"readGatewayBrowserErrorKind");function me(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=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(me,"logUnexpectedOAuthHandlerError");function Ds(e){let t;try{t=new URL(e.redirectUri)}catch{return kt({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(Ds,"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 Cf(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(Cf,"logBrowserLoginCallbackFailure");function zs(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(zs,"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 zs(e)}n(fr,"authorizeResultResponse");async function js(e,t){try{return Response.json(_o(e.url,e.headers))}catch(r){return me(t,"oauth_authorization_server_metadata_failed",r),Ps(e,t,r)}}n(js,"authorizationServerMetadataHandler");async function Hs(e,t){try{let r=xr(e.params.routePath);return Response.json(wo({operationId:r.operationId,requestUrl:e.url,requestHeaders:e.headers}))}catch(r){return me(t,"oauth_authorization_server_metadata_failed",r),Ps(e,t,r)}}n(Hs,"scopedAuthorizationServerMetadataHandler");async function Bs(e,t){try{let r=await $i(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:S.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 me(t,"oauth_register_failed",r),vn(r)}}n(Bs,"registerHandler");async function Ls(e,t){try{return fr(await bn(e,{context:t}))}catch(r){return me(t,"oauth_authorize_failed",r),An(e,t,r)}}n(Ls,"authorizeHandler");async function Ns(e,t){try{let r=xr(e.params.routePath);return fr(await bn(e,{operationId:r.operationId,context:t}))}catch(r){return me(t,"oauth_authorize_scoped_failed",r),An(e,t,r)}}n(Ns,"scopedAuthorizeHandler");async function Js(e,t){try{let r=await fs(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 Cf(t,r),qs(e,t,r)}}n(Js,"callbackHandler");async function Gs(e,t){try{return zs(await hs(e))}catch(r){return me(t,"oauth_dev_login_failed",r),An(e,t,r)}}n(Gs,"devLoginHandler");async function Fs(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await gs({request:e,body:e.method==="POST"?await Cn(e):void 0,context:t});return fr(r)}catch(r){return me(t,"oauth_setup_failed",r),qs(e,t,r)}}n(Fs,"setupHandler");async function $s(e,t){try{return Response.json(await ks({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 me(t,"oauth_token_failed",r),vn(r)}}n($s,"tokenHandler");async function Zs(e,t){try{return await Us({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 me(t,"oauth_revoke_failed",r),vn(r)}}n(Zs,"revokeHandler");function Ks(e){return C`<p data-gateway-error-code="${e.code}">${e.body}</p>`}n(Ks,"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:Xt}),heading:e.title,subhead:"",body:Ks({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 Ws(e){return kf(xf(e))}n(Ws,"browserConnectionSuccessResponse");function hr(e,t,r={}){let o=Wn(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"},Vs=Symbol("upstream-request");function Ut(e,t){Object.defineProperty(e,Vs,{configurable:!0,value:t})}n(Ut,"setUpstreamRequestContext");function Pf(e){let t=e[Vs];if(!t)throw new Y("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 Tt(e,t){let r=Pf(e),o=Of(t);if(!Ef(r.kind,o)){let a=Tf[o[0]];throw new Y(`${a} request context has not been set`)}return r}n(Tt,"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 Y(`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?zt.parse(t):void 0}n(Df,"readOptionalOperationId");function zf(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(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=ro(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 Ia(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=Bt(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=Xn.parse(qf(e,"connection"));switch(r){case"connect":Ut(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),Ut(e,s);return}let i=De(e.query.code),c=De(e.query.state);if(i&&c){Ut(e,{kind:"callback_authorization_code",upstreamServerId:o,code:i,state:c});return}Ut(e,{kind:"callback_invalid",upstreamServerId:o});return}case"client_metadata":Ut(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 xn(e){try{return new URL(e.url).pathname}catch{return}}n(xn,"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 Ys(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=Gf(r))}n(Ys,"addErrorAttributes");function kn(e){if(!(e instanceof f))return;let t=e.extensionMembers?.[g];return Mt(t)?t:void 0}n(kn,"readRuntimeGatewayCode");function Xs(e,t){let r=e.extensionMembers?.[t];return typeof r=="string"?r:void 0}n(Xs,"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:S.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:xn(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:xn(e),upstreamServerId:r.upstreamServerId}});case"callback_authorization_code":return r}}n($f,"requireAuthorizationCallbackRequest");function Zf(e,t){v(e,{eventType:S.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}n(Zf,"emitCallbackReceivedAnalyticsEvent");function Kf(e,t){v(e,{eventType:S.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 Ws({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 Ys(t,"error",e),e instanceof Error&&Ys(t,"cause",Jf(e)),t}n(Vf,"buildTokenExchangeFailureAttributes");function Yf(e){v(e.context,{eventType:S.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:kn(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=kn(t),o=Kn(r)?r:"upstream_token_exchange_failed",a={code:o,requestId:e.context.requestId,routePath:xn(e.request),upstreamServerId:e.callbackRequest.upstreamServerId,underlyingError:t instanceof Error?t.message:void 0,...t instanceof f?{httpStatus:Ff(t,ge),contentType:Xs(t,ze),upstreamUrl:Xs(t,ye)}:{}};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 Un(e,t){let r=Tt(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 ri({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:kn(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(Un,"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 Qs(e,t){let r=Tt(e,"connect"),o=await ti({request:e,connectRequest:r});if(v(t,{eventType:S.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 or({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(Qs,"connectHandler");async function ec(e,t){let r=Tt(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(ec,"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 Tn(e){return async(t,r)=>t.method==="OPTIONS"?nh():oh(await e(t,r))}n(Tn,"wrapWellKnownHandler");var nc=[{routeName:"oauth_as_metadata",mount:"root",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:Tn(js),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",mount:"root",path:"/.well-known/oauth-authorization-server/:routePath*",methods:["GET","OPTIONS"],handler:Tn(Hs),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",mount:"root",path:"/.well-known/oauth-protected-resource/:routePath*",methods:["GET","OPTIONS"],handler:Tn(Ro),corsPolicy:"anything-goes"},{routeName:"oauth_register",mount:"action",path:"/oauth/register",methods:["POST"],handler:Bs},{routeName:"oauth_authorize",mount:"action",path:"/oauth/authorize",methods:["GET"],handler:Ls},{routeName:"oauth_authorize_scoped",mount:"action",path:"/oauth/authorize/:routePath*",methods:["GET"],handler:Ns},{routeName:"oauth_callback",mount:"action",path:"/oauth/callback",methods:["GET"],handler:Js},{routeName:"oauth_dev_login",mount:"action",path:"/oauth/dev-login",methods:["GET"],handler:Gs},{routeName:"oauth_setup",mount:"action",path:"/oauth/setup",methods:["GET","POST"],handler:Fs},{routeName:"oauth_token",mount:"action",path:"/oauth/token",methods:["POST"],handler:$s},{routeName:"oauth_revoke",mount:"action",path:"/oauth/revoke",methods:["POST"],handler:Zs},{routeName:"upstream_client_metadata",mount:"action",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:gr("client_metadata",ec)},{routeName:"upstream_connect",mount:"action",path:"/auth/connections/:connection/connect",methods:["GET"],handler:gr("connect",Qs)},{routeName:"upstream_callback",mount:"action",path:"/auth/connections/:connection/callback",methods:["GET"],handler:gr("callback",Un)}],ah=nc.filter(e=>!e.routeName.startsWith("upstream_")),ih=nc.filter(e=>e.routeName.startsWith("upstream_"));function sh(e){let t=so({routes:e.routes,policies:e.policies,gateway:e.gateway});return co(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(ho(o));if(a===void 0)return;let i=a?.downstreamOAuth?.config;return i===void 0?Dt(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 tc(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&&$n(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(tc,"wrapInternalHandler");function rc(e,t,r,o){e.addPluginRoute({path:th(t,r),methods:t.methods,handler:o,processors:[Dn],corsPolicy:t.corsPolicy??"none"})}n(rc,"addInternalRoute");function oc(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;rc(e,s,r.gateway,tc(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)rc(e,s,r.gateway,tc(s.routeName,s.handler))}}n(oc,"registerMcpGatewayInternalRoutes");var Pn=class extends qn{static{n(this,"McpGatewayPlugin")}#e;constructor(t={}){super(),G("plugin.mcp-gateway"),this.#e=Zn(t)}registerRoutes(t){let r=t.parsedRouteData;r&&oc(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 fe(e){return e&&typeof e=="object"?e:void 0}n(fe,"readRecord");function Pt(e,t){let r=fe(e)?.[t];return typeof r=="string"?r:void 0}n(Pt,"readStringProperty");function ic(e,t){let r=fe(e)?.[t];return typeof r=="number"?r:void 0}n(ic,"readNumberProperty");function ac(e,t){return ic(e,"code")??(t.status>=400?t.status:void 0)}n(ac,"readErrorCode");function sc(e){return Array.isArray(e)?e.map(sc).find(t=>t?.method):fe(e)}n(sc,"readJsonRpcMessage");function cc(e){let t=sc(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:Pt(o,"name")};case"prompts/list":return{mcpMethod:r,capabilityType:"prompt"};case"prompts/get":return{mcpMethod:r,capabilityType:"prompt",capabilityName:Pt(o,"name")};case"resources/list":case"resources/templates/list":return{mcpMethod:r,capabilityType:"resource"};case"resources/read":{let a=Pt(o,"uri");return{mcpMethod:r,capabilityType:"resource",capabilityName:a,resourceUri:a}}default:return null}}n(cc,"buildBaseCapabilityInput");function dc(e){return e==="tools/list"||e==="prompts/list"||e==="resources/list"||e==="resources/templates/list"}n(dc,"isCapabilityListMethod");function hh(e,t,r){let i=fe(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 uc(e){let t=cc(e);return!t||dc(t.mcpMethod)?null:{eventType:S.MCP_CAPABILITY_INVOKED,outcome:"success",...t}}n(uc,"buildCapabilityInvokedAnalyticsInput");async function lc(e,t){let r=cc(e);if(!r)return null;let o=fe(await gh(t)),a=fe(o?.error),i=fe(a?.data),c=o?.result,s=r.mcpMethod==="tools/call"&&fe(c)?.isError===!0;if(fe(i?.connectRequired))return{eventType:S.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",...r,httpStatusCode:t.status,reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required",errorCode:ic(a,"code"),mcpErrorType:Pt(a,"message")};if(dc(r.mcpMethod)){let u=t.status>=400?void 0:hh(r.mcpMethod,r.capabilityType,c);return{eventType:S.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:ac(a,t)}:{},...u===void 0?{}:{attributes:{itemCount:u}}}}return t.status>=400||a?{eventType:S.MCP_CAPABILITY_FAILED,outcome:"failure",...r,httpStatusCode:t.status,reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"capability_error",errorCode:ac(a,t),mcpErrorType:Pt(a,"message")}:{eventType:S.MCP_CAPABILITY_COMPLETED,outcome:s?"application_error":"success",...r,httpStatusCode:t.status,toolResultIsError:s,applicationError:s}}n(lc,"buildCapabilityFinalAnalyticsInput");var yh={Allow:"POST"};async function _h(e){try{return await e.clone().arrayBuffer()}catch{return}}n(_h,"readRequestBody");function pc(e){try{let t=uo(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(pc,"readRouteAnalyticsFields");function mc(e){return So(e.user,e.url,e.headers)?.subjectId}n(mc,"readRequestSubjectId");function wh(e){let t=uc(e.requestBody);t&&v(e.context,{...t,...pc(e.context),httpMethod:e.request.method,subjectId:mc(e.request),transport:"http"})}n(wh,"emitCapabilityInvokedAnalytics");async function Rh(e){let t=await lc(e.requestBody,e.response);t&&v(e.context,{...t,...pc(e.context),httpMethod:e.request.method,subjectId:mc(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 Jn(e,t);return await Rh({context:t,request:e,requestBody:o,response:a,startedAt:r}),a}n(bh,"McpProxyHandler");export{Cc as McpAuth0OAuthInboundPolicy,kr as McpCapabilityFilterInboundPolicy,fc as McpClerkOAuthInboundPolicy,hc as McpCognitoOAuthInboundPolicy,gc as McpEntraOAuthInboundPolicy,Pn as McpGatewayPlugin,yc as McpGoogleOAuthInboundPolicy,_c as McpKeycloakOAuthInboundPolicy,wc as McpLogtoOAuthInboundPolicy,vc as McpOAuthInboundPolicy,Rc as McpOktaOAuthInboundPolicy,bc as McpOneLoginOAuthInboundPolicy,Ic as McpPingOAuthInboundPolicy,bh as McpProxyHandler,on as McpTokenExchangeInboundPolicy,Sc as McpWorkosOAuthInboundPolicy};
50
50
  //# sourceMappingURL=index.js.map