@zuplo/cli 6.71.21 → 6.71.22

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 (44) hide show
  1. package/node_modules/@posthog/core/dist/error-tracking/exception-steps.d.ts.map +1 -1
  2. package/node_modules/@posthog/core/dist/error-tracking/exception-steps.js +6 -24
  3. package/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs +7 -25
  4. package/node_modules/@posthog/core/dist/posthog-core-stateless.d.ts +1 -0
  5. package/node_modules/@posthog/core/dist/posthog-core-stateless.d.ts.map +1 -1
  6. package/node_modules/@posthog/core/dist/posthog-core-stateless.js +25 -7
  7. package/node_modules/@posthog/core/dist/posthog-core-stateless.mjs +26 -8
  8. package/node_modules/@posthog/core/dist/utils/string-utils.d.ts +1 -0
  9. package/node_modules/@posthog/core/dist/utils/string-utils.d.ts.map +1 -1
  10. package/node_modules/@posthog/core/dist/utils/string-utils.js +21 -0
  11. package/node_modules/@posthog/core/dist/utils/string-utils.mjs +19 -1
  12. package/node_modules/@posthog/core/package.json +1 -1
  13. package/node_modules/@posthog/core/src/error-tracking/exception-steps.ts +5 -42
  14. package/node_modules/@posthog/core/src/posthog-core-stateless.ts +38 -9
  15. package/node_modules/@posthog/core/src/utils/string-utils.spec.ts +38 -1
  16. package/node_modules/@posthog/core/src/utils/string-utils.ts +42 -0
  17. package/node_modules/@zuplo/core/customer.cli.minified.js +2 -2
  18. package/node_modules/@zuplo/core/index.minified.js +2 -2
  19. package/node_modules/@zuplo/core/package.json +1 -1
  20. package/node_modules/@zuplo/graphql/package.json +1 -1
  21. package/node_modules/@zuplo/openapi-tools/package.json +1 -1
  22. package/node_modules/@zuplo/otel/package.json +1 -1
  23. package/node_modules/@zuplo/runtime/out/esm/{chunk-I5HLAHUY.js → chunk-36XLJ4X6.js} +143 -111
  24. package/node_modules/@zuplo/runtime/out/esm/chunk-36XLJ4X6.js.map +1 -0
  25. package/node_modules/@zuplo/runtime/out/esm/{chunk-DQ4ANJLR.js → chunk-4MNJC7E2.js} +2 -2
  26. package/node_modules/@zuplo/runtime/out/esm/chunk-4MNJC7E2.js.map +1 -0
  27. package/node_modules/@zuplo/runtime/out/esm/{chunk-2Y72LML3.js → chunk-54PA7VDV.js} +2 -2
  28. package/node_modules/@zuplo/runtime/out/esm/{chunk-2Y72LML3.js.map → chunk-54PA7VDV.js.map} +1 -1
  29. package/node_modules/@zuplo/runtime/out/esm/{chunk-L3MZGNQA.js → chunk-DSZS6PZJ.js} +10 -10
  30. package/node_modules/@zuplo/runtime/out/esm/chunk-DSZS6PZJ.js.map +1 -0
  31. package/node_modules/@zuplo/runtime/out/esm/index.js +1 -1
  32. package/node_modules/@zuplo/runtime/out/esm/index.js.map +1 -1
  33. package/node_modules/@zuplo/runtime/out/esm/internal/index.js +1 -1
  34. package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +1 -1
  35. package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js.map +1 -1
  36. package/node_modules/@zuplo/runtime/out/esm/mocks/index.js +1 -1
  37. package/node_modules/@zuplo/runtime/out/types/index.d.ts +942 -0
  38. package/node_modules/@zuplo/runtime/package.json +1 -1
  39. package/package.json +6 -6
  40. package/node_modules/@zuplo/runtime/out/esm/chunk-DQ4ANJLR.js.map +0 -1
  41. package/node_modules/@zuplo/runtime/out/esm/chunk-I5HLAHUY.js.map +0 -1
  42. package/node_modules/@zuplo/runtime/out/esm/chunk-L3MZGNQA.js.map +0 -1
  43. /package/node_modules/@zuplo/runtime/out/esm/{chunk-I5HLAHUY.js.LEGAL.txt → chunk-36XLJ4X6.js.LEGAL.txt} +0 -0
  44. /package/node_modules/@zuplo/runtime/out/esm/{chunk-L3MZGNQA.js.LEGAL.txt → chunk-DSZS6PZJ.js.LEGAL.txt} +0 -0
@@ -22,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{$b as so,$c as Wt,Ab as to,Ac as Ar,Bb as ne,Bc as $t,Cb as ro,Cc as kr,Db as ce,Dc as Zt,Eb as R,Ec as ut,Fb as Lt,Fc as Fe,G as Jn,Gb as L,Gc as bo,H as l,Hb as Re,Hc as ue,I as Gn,Ib as _c,Ic as xr,J as Sr,Jb as wc,Jc as Tr,K as se,Kb as Rc,Kc as Io,L as Fn,Lb as bc,Lc as Kt,M as _,Mb as Ic,Mc as Ur,N as ye,Nb as Sc,Nc as Pr,O as Ht,Ob as Cc,Oc as So,P as $n,Pb as vc,Pc as M,Q as Zn,Qb as Ac,Qc as Co,R as Kn,Rb as kc,Rc as vo,S as d,Sb as no,Sc as Er,T as K,Tb as oo,Tc as Ao,Ub as io,Uc as ko,Vb as Nt,Vc as Or,Wb as Cr,Wc as xo,Xb as Jt,Xc as Te,Yb as Gt,Yc as To,Z as Wn,Zb as st,Zc as lt,_b as ao,_c as Uo,a as Z,ac as co,ad as pt,bc as ct,bd as Po,cc as uo,cd as Eo,dc as Je,dd as Oo,ec as lo,ed as qo,fc as vr,fd as Mo,gc as po,gd as Do,hc as dt,hd as jo,i as xe,ic as Ft,id as Vt,j as Bn,jc as mo,jd as zo,kc as fo,kd as Ho,l as Ln,lb as Vn,lc as ho,ld as b,mb as W,mc as go,md as v,nb as Yn,nc as te,nd as G,ob as Xn,oc as H,od as le,p as Nn,pb as q,pc as yo,pd as x,qb as Qn,qc as _o,qd as Yt,r as zt,rb as He,rc as I,rd as xc,sb as eo,sc as de,sd as Tc,tb as Be,tc as Ge,ub as g,uc as N,vb as Le,vc as O,wb as Ne,wc as wo,xb as _e,xc as J,yb as we,yc as Ro,zb as Bt,zc as be}from"../chunk-I5HLAHUY.js";import"../chunk-DQ4ANJLR.js";import{a as S}from"../chunk-2Y72LML3.js";import{$ as ee,a as n,aa as h,ba as B,ca as Hn,da as jt}from"../chunk-L3MZGNQA.js";K();function Uc(e){let t=Gt.safeParse(e);return t.success?t.data.id:void 0}n(Uc,"parseJsonRpcRequestId");function Bo(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Uc(t)}catch{return}}n(Bo,"readJsonRpcRequestIdFromBody");function Xt(e){return ao.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(Xt,"jsonRpcErrorResponse");function Lo(e){return new co([so.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Lo,"urlElicitationRequiredError");var Qt=d.record(d.string(),d.unknown()),Pc=d.record(d.string(),d.unknown()),Ec=d.object({name:d.string().min(1),description:d.string().min(1).optional(),annotations:Pc.optional(),_meta:Qt.optional()}).strict(),Oc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),_meta:Qt.optional()}).strict(),qc=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:Qt.optional()}).strict(),Mc=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:Qt.optional()}).strict(),Dc=d.array(d.union([d.string(),Ec])),jc=d.array(d.union([d.string(),Oc])),zc=d.array(d.union([d.string(),qc])),Hc=d.array(d.union([d.string(),Mc])),Bc=d.object({tools:Dc.optional(),prompts:jc.optional(),resources:zc.optional(),resourceTemplates:Hc.optional()}).strict(),Mr=[{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 Lc(e,t){return Yn(Bc,e,`MCP capability filter policy "${t}"`)}n(Lc,"parseMcpCapabilityFilterOptions");function F(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(F,"isRecord");function Nc(e,t){if(!F(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(Nc,"readParamString");function Dr(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(Dr,"readRequestId");function Fo(e){return e===void 0?void 0:JSON.stringify(e)}n(Fo,"requestIdKey");function Jc(e){let t={};for(let r of Mr){let o=e[r.option];if(o===void 0)continue;let i=new Map;for(let a of o){let c=Zc(a,r.itemProperty);c!==void 0&&i.set(c.key,c)}t[r.option]=i}return t}n(Jc,"buildProjectionMaps");function jr(e){return Mr.find(t=>t.listMethod===e)}n(jr,"findListRule");function Gc(e){return e.requests.some(t=>{if(!F(t))return!1;let r=jr(t.method);return r!==void 0&&e.projectionMaps[r.option]!==void 0})}n(Gc,"shouldFilterListResponses");function Fc(e){for(let t of Mr){let r=e.projectionMaps[t.option];if(r!==void 0)for(let o of t.directMethods){if(e.request.method!==o.method)continue;let i=Nc(e.request.params,o.paramProperty);if(i!==void 0&&!r.has(i))return{id:Dr(e.request)}}}}n(Fc,"findDisallowedDirectAccess");function $c(e){return Response.json(Xt({id:e,error:{code:st.MethodNotFound,message:"Method not found"}}))}n($c,"methodNotFoundResponse");function Zc(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!F(e))return;let r=e[t];if(typeof r=="string")return{key:r,overlay:e}}n(Zc,"buildProjection");function No(e){let t=e.base[e.property],r=e.overlay[e.property];return F(r)?F(t)?{...t,...r}:r:t}n(No,"mergeRecordProperty");function Kc(e,t){let r={...e,...t.overlay},o=No({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let i=No({base:e,overlay:t.overlay,property:"_meta"});return i!==void 0&&(r._meta=i),r}n(Kc,"applyProjection");function Jo(e,t,r){if(!F(e))return e;let o=e.result;if(!F(o))return e;let i=o[t.resultProperty];return!Array.isArray(i)||!i.every(a=>F(a)&&typeof a[t.itemProperty]=="string")?e:{...e,result:{...o,[t.resultProperty]:i.flatMap(a=>{if(!F(a))return[];let c=a[t.itemProperty];if(typeof c!="string")return[];let s=r.get(c);return s===void 0?[]:[Kc(a,s)]})}}}n(Jo,"filterAndProjectItems");function Wc(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!F(r))continue;let o=jr(r.method),i=Dr(r),a=Fo(i);o!==void 0&&a!==void 0&&t.set(a,o)}return t}n(Wc,"buildListRulesByResponseId");function Vc(e){if(Array.isArray(e.responseBody)){let o=Wc(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(i=>{if(!F(i)||"error"in i)return i;let a=Fo(Dr(i)),c=a===void 0?void 0:o.get(a),s=c===void 0?void 0:e.projectionMaps[c.option];return c===void 0||s===void 0?i:Jo(i,c,s)})}if(!F(e.requestBody)||!F(e.responseBody)||"error"in e.responseBody)return e.responseBody;let t=jr(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(Vc,"filterJsonRpcResponse");async function Go(e){return e.clone().json()}n(Go,"readJson");function Yc(e){return e.headers.get("content-type")?.includes("json")??!1}n(Yc,"isJsonResponse");var qr=class extends zt{static{n(this,"McpCapabilityFilterInboundPolicy")}#e;constructor(t,r){let o=Lc(t,r);super(o,r),this.#e=Jc(o)}async handler(t,r){Z("policy.inbound.mcp-capability-filter");let o;try{o=await Go(t)}catch{return t}let i=Array.isArray(o)?o:[o];for(let a of i){if(!F(a))continue;let c=Fc({request:a,projectionMaps:this.#e});if(c!==void 0)return $c(c.id)}return Gc({requests:i,projectionMaps:this.#e})&&r.addResponseSendingHook(async a=>{if(!Yc(a))return a;let c;try{c=await Go(a)}catch{return a}let s=Vc({requestBody:o,responseBody:c,projectionMaps:this.#e});if(s===c)return a;let u=new Headers(a.headers);return u.delete("content-length"),new Response(JSON.stringify(s),{status:a.status,statusText:a.statusText,headers:u})}),t}};var zr;zr=globalThis.crypto;async function Xc(e){return(await zr).getRandomValues(new Uint8Array(e))}n(Xc,"getRandomValues");async function Qc(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await Xc(e-o.length);for(let a of i)a<r&&(o+=t[a%t.length])}return o}n(Qc,"random");async function ed(e){return await Qc(e)}n(ed,"generateVerifier");async function td(e){let t=await(await zr).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(td,"generateChallenge");async function Hr(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await ed(e),r=await td(t);return{code_verifier:t,code_challenge:r}}n(Hr,"pkceChallenge");K();var j=Gn().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Zn.custom,message:"URL must be parseable",fatal:!0}),Jn}).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"}),er=Ht({resource:l().url(),authorization_servers:_(j).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:se().optional(),authorization_details_types_supported:_(l()).optional(),dpop_signing_alg_values_supported:_(l()).optional(),dpop_bound_access_tokens_required:se().optional()}),mt=Ht({issuer:l(),authorization_endpoint:j,token_endpoint:j,registration_endpoint:j.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:j.optional(),revocation_endpoint:j.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:se().optional()}),rd=Ht({issuer:l(),authorization_endpoint:j,token_endpoint:j,userinfo_endpoint:j.optional(),jwks_uri:j,registration_endpoint:j.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:se().optional(),request_parameter_supported:se().optional(),request_uri_parameter_supported:se().optional(),require_request_uri_registration:se().optional(),op_policy_uri:j.optional(),op_tos_uri:j.optional(),client_id_metadata_document_supported:se().optional()}),tr=ye({...rd.shape,...mt.pick({code_challenge_methods_supported:!0}).shape}),$e=ye({access_token:l(),id_token:l().optional(),token_type:l(),expires_in:Kn.number().optional(),scope:l().optional(),refresh_token:l().optional()}).strip(),Zo=ye({error:l(),error_description:l().optional(),error_uri:l().optional()}),$o=j.optional().or($n("").transform(()=>{})),nd=ye({redirect_uris:_(j),token_endpoint_auth_method:l().optional(),grant_types:_(l()).optional(),response_types:_(l()).optional(),client_name:l().optional(),client_uri:j.optional(),logo_uri:$o,scope:l().optional(),contacts:_(l()).optional(),tos_uri:$o,policy_uri:l().optional(),jwks_uri:j.optional(),jwks:Fn().optional(),software_id:l().optional(),software_version:l().optional(),software_statement:l().optional()}).strip(),rr=ye({client_id:l(),client_secret:l().optional(),client_id_issued_at:Sr().optional(),client_secret_expires_at:Sr().optional()}).strip(),ft=nd.merge(rr),Zh=ye({error:l(),error_description:l().optional()}).strip(),Kh=ye({token:l(),token_type_hint:l().optional()}).strip();function Ko(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(Ko,"resourceUrlFromServerUrl");function Wo({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 i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",a=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return i.startsWith(a)}n(Wo,"checkResourceAllowed");var A=class extends Error{static{n(this,"OAuthError")}constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},ht=class extends A{static{n(this,"InvalidRequestError")}};ht.errorCode="invalid_request";var Ue=class extends A{static{n(this,"InvalidClientError")}};Ue.errorCode="invalid_client";var Pe=class extends A{static{n(this,"InvalidGrantError")}};Pe.errorCode="invalid_grant";var Ee=class extends A{static{n(this,"UnauthorizedClientError")}};Ee.errorCode="unauthorized_client";var gt=class extends A{static{n(this,"UnsupportedGrantTypeError")}};gt.errorCode="unsupported_grant_type";var yt=class extends A{static{n(this,"InvalidScopeError")}};yt.errorCode="invalid_scope";var _t=class extends A{static{n(this,"AccessDeniedError")}};_t.errorCode="access_denied";var pe=class extends A{static{n(this,"ServerError")}};pe.errorCode="server_error";var wt=class extends A{static{n(this,"TemporarilyUnavailableError")}};wt.errorCode="temporarily_unavailable";var Rt=class extends A{static{n(this,"UnsupportedResponseTypeError")}};Rt.errorCode="unsupported_response_type";var bt=class extends A{static{n(this,"UnsupportedTokenTypeError")}};bt.errorCode="unsupported_token_type";var It=class extends A{static{n(this,"InvalidTokenError")}};It.errorCode="invalid_token";var St=class extends A{static{n(this,"MethodNotAllowedError")}};St.errorCode="method_not_allowed";var Ct=class extends A{static{n(this,"TooManyRequestsError")}};Ct.errorCode="too_many_requests";var Oe=class extends A{static{n(this,"InvalidClientMetadataError")}};Oe.errorCode="invalid_client_metadata";var vt=class extends A{static{n(this,"InsufficientScopeError")}};vt.errorCode="insufficient_scope";var At=class extends A{static{n(this,"InvalidTargetError")}};At.errorCode="invalid_target";var Vo={[ht.errorCode]:ht,[Ue.errorCode]:Ue,[Pe.errorCode]:Pe,[Ee.errorCode]:Ee,[gt.errorCode]:gt,[yt.errorCode]:yt,[_t.errorCode]:_t,[pe.errorCode]:pe,[wt.errorCode]:wt,[Rt.errorCode]:Rt,[bt.errorCode]:bt,[It.errorCode]:It,[St.errorCode]:St,[Ct.errorCode]:Ct,[Oe.errorCode]:Oe,[vt.errorCode]:vt,[At.errorCode]:At};function od(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(od,"isClientAuthMethod");var Br="code",Lr="S256";function id(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&od(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(id,"selectClientAuthMethod");function ad(e,t,r,o){let{client_id:i,client_secret:a}=t;switch(e){case"client_secret_basic":sd(i,a,r);return;case"client_secret_post":cd(i,a,o);return;case"none":dd(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(ad,"applyClientAuthentication");function sd(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(sd,"applyBasicAuth");function cd(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(cd,"applyPostAuth");function dd(e,t){t.set("client_id",e)}n(dd,"applyPublicAuth");async function Xo(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Zo.parse(JSON.parse(r)),{error:i,error_description:a,error_uri:c}=o,s=Vo[i]||pe;return new s(a||"",c)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new pe(i)}}n(Xo,"parseErrorResponse");async function Gr(e,t){try{return await Nr(e,t)}catch(r){if(r instanceof Ue||r instanceof Ee)return await e.invalidateCredentials?.("all"),await Nr(e,t);if(r instanceof Pe)return await e.invalidateCredentials?.("tokens"),await Nr(e,t);throw r}}n(Gr,"auth");async function Nr(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:i,fetchFn:a}){let c=await e.discoveryState?.(),s,u,p,f=i;if(!f&&c?.resourceMetadataUrl&&(f=new URL(c.resourceMetadataUrl)),c?.authorizationServerUrl){if(u=c.authorizationServerUrl,s=c.resourceMetadata,p=c.authorizationServerMetadata??await ti(u,{fetchFn:a}),!s)try{s=await ei(t,{resourceMetadataUrl:f},a)}catch{}(p!==c.authorizationServerMetadata||s!==c.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:f?.toString(),resourceMetadata:s,authorizationServerMetadata:p})}else{let E=await hd(t,{resourceMetadataUrl:f,fetchFn:a});u=E.authorizationServerUrl,p=E.authorizationServerMetadata,s=E.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:f?.toString(),resourceMetadata:s,authorizationServerMetadata:p})}let w=await ud(t,e,s),U=o||s?.scopes_supported?.join(" ")||e.clientMetadata.scope,y=await Promise.resolve(e.clientInformation());if(!y){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let E=p?.client_id_metadata_document_supported===!0,D=e.clientMetadataUrl;if(D&&!Fr(D))throw new Oe(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${D}`);if(E&&D)y={client_id:D},await e.saveClientInformation?.(y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let zn=await Rd(u,{metadata:p,clientMetadata:e.clientMetadata,scope:U,fetchFn:a});await e.saveClientInformation(zn),y=zn}}let P=!e.redirectUrl;if(r!==void 0||P){let E=await wd(e,u,{metadata:p,resource:w,authorizationCode:r,fetchFn:a});return await e.saveTokens(E),"AUTHORIZED"}let k=await e.tokens();if(k?.refresh_token)try{let E=await _d(u,{metadata:p,clientInformation:y,refreshToken:k.refresh_token,resource:w,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(E),"AUTHORIZED"}catch(E){if(!(!(E instanceof A)||E instanceof pe))throw E}let z=e.state?await e.state():void 0,{authorizationUrl:ze,codeVerifier:Q}=await gd(u,{metadata:p,clientInformation:y,state:z,redirectUrl:e.redirectUrl,scope:U,resource:w});return await e.saveCodeVerifier(Q),await e.redirectToAuthorization(ze),"REDIRECT"}n(Nr,"authInternal");function Fr(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(Fr,"isHttpsUrl");async function ud(e,t,r){let o=Ko(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!Wo({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(ud,"selectResourceURL");function Qo(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let i=Jr(e,"resource_metadata")||void 0,a;if(i)try{a=new URL(i)}catch{}let c=Jr(e,"scope")||void 0,s=Jr(e,"error")||void 0;return{resourceMetadataUrl:a,scope:c,error:s}}n(Qo,"extractWWWAuthenticateParams");function Jr(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=r.match(o);return i?i[1]||i[2]:null}n(Jr,"extractFieldFromWwwAuth");async function ei(e,t,r=fetch){let o=await md(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 er.parse(await o.json())}n(ei,"discoverOAuthProtectedResourceMetadata");async function $r(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?$r(e,void 0,r):void 0;throw o}}n($r,"fetchWithCorsRetry");function ld(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(ld,"buildWellKnownPath");async function Yo(e,t,r=fetch){return await $r(e,{"MCP-Protocol-Version":t},r)}n(Yo,"tryMetadataDiscovery");function pd(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(pd,"shouldAttemptFallback");async function md(e,t,r,o){let i=new URL(e),a=o?.protocolVersion??Cr,c;if(o?.metadataUrl)c=new URL(o.metadataUrl);else{let u=ld(t,i.pathname);c=new URL(u,o?.metadataServerUrl??i),c.search=i.search}let s=await Yo(c,a,r);if(!o?.metadataUrl&&pd(s,i.pathname)){let u=new URL(`/.well-known/${t}`,i);s=await Yo(u,a,r)}return s}n(md,"discoverMetadataWithFallback");function fd(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 i=t.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:"oidc"}),o.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(fd,"buildDiscoveryUrls");async function ti(e,{fetchFn:t=fetch,protocolVersion:r=Cr}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=fd(e);for(let{url:a,type:c}of i){let s=await $r(a,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 ${a}`)}return c==="oauth"?mt.parse(await s.json()):tr.parse(await s.json())}}}n(ti,"discoverAuthorizationServerMetadata");async function hd(e,t){let r,o;try{r=await ei(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 i=await ti(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(hd,"discoverOAuthServerInfo");async function gd(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:i,state:a,resource:c}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Br))throw new Error(`Incompatible auth server: does not support response type ${Br}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Lr))throw new Error(`Incompatible auth server: does not support code challenge method ${Lr}`)}else s=new URL("/authorize",e);let u=await Hr(),p=u.code_verifier,f=u.code_challenge;return s.searchParams.set("response_type",Br),s.searchParams.set("client_id",r.client_id),s.searchParams.set("code_challenge",f),s.searchParams.set("code_challenge_method",Lr),s.searchParams.set("redirect_uri",String(o)),a&&s.searchParams.set("state",a),i&&s.searchParams.set("scope",i),i?.includes("offline_access")&&s.searchParams.append("prompt","consent"),c&&s.searchParams.set("resource",c.href),{authorizationUrl:s,codeVerifier:p}}n(gd,"startAuthorization");function yd(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(yd,"prepareAuthorizationCodeRequest");async function ri(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:i,resource:a,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(a&&r.set("resource",a.href),i)await i(u,r,s,t);else if(o){let f=t?.token_endpoint_auth_methods_supported??[],w=id(o,f);ad(w,o,u,r)}let p=await(c??fetch)(s,{method:"POST",headers:u,body:r});if(!p.ok)throw await Xo(p);return $e.parse(await p.json())}n(ri,"executeTokenRequest");async function _d(e,{metadata:t,clientInformation:r,refreshToken:o,resource:i,addClientAuthentication:a,fetchFn:c}){let s=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),u=await ri(e,{metadata:t,tokenRequestParams:s,clientInformation:r,addClientAuthentication:a,resource:i,fetchFn:c});return{refresh_token:o,...u}}n(_d,"refreshAuthorization");async function wd(e,t,{metadata:r,resource:o,authorizationCode:i,fetchFn:a}={}){let c=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(c)),!s){if(!i)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=yd(i,p,e.redirectUrl)}let u=await e.clientInformation();return ri(t,{metadata:r,tokenRequestParams:s,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(wd,"fetchToken");async function Rd(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");a=new URL(t.registration_endpoint)}else a=new URL("/register",e);let c=await(i??fetch)(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!c.ok)throw await Xo(c);return ft.parse(await c.json())}n(Rd,"registerClient");var Zr="zuplo.com",bd=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),Id=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function ni(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(ni,"s2FaviconHref");function Sd(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(Sd,"strictFaviconHref");var nr=ni(Zr);function Kr(e){let t=e.toLowerCase();return t===Zr||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?ni(Zr):Sd(e)}n(Kr,"resolveIconHref");function Cd(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(Cd,"hostnameFromHost");function vd(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(vd,"isLocalOrAddressHost");function Ad(e){let t=Cd(e).toLowerCase().replace(/\.$/,"");if(vd(t)||Id.some(a=>t===a.slice(1)||t.endsWith(a)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let o=r.slice(-2).join("."),i=bd.has(o)?3:2;return r.slice(-i).join(".")}n(Ad,"inferFaviconDomain");function Wr(e){return{src:Kr(Ad(e)),mimeType:"image/png",sizes:["128x128"]}}n(Wr,"resolveMcpFaviconIcon");function or(e){try{return Wr(new URL(e).host)}catch{return}}n(or,"resolveMcpFaviconIconFromUrl");function Ie(e){let t=te().connectionsById.get(e);if(!t)throw new B(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,description:t.description,serverInfo:t.serverInfo,transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}n(Ie,"getUpstreamServerConfig");function ir(e){let t=te().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new B(`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(ir,"getUpstreamAuthConfig");function Ze(e,t){let r=ir({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new B(`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(Ze,"requireUpstreamOAuthConfig");function oi(e,t){let r=ir({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new B(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(oi,"requireUpstreamIdJagConfig");function ii(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(ii,"mergeAbortSignals");async function kd(e){try{await e.cancel()}catch{}}n(kd,"cancelReader");async function ar(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],i=0,a=await r.read();for(;!a.done;){let u=a.value;if(i+=u.byteLength,i>t.maxBytes)throw await kd(r),t.createLimitError();o.push(u),a=await r.read()}let c=new Uint8Array(i),s=0;for(let u of o)c.set(u,s),s+=u.byteLength;return c}n(ar,"readBoundedByteStream");var xd=2,Td=1024*1024,Ud=1e4,Pd=new Set([301,302,303,307,308]),Ed=["authorization","proxy-authorization","cookie","cookie2"];function Vr(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Vr,"readRequestUrl");function Ke(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(Ke,"readRequestMethod");function Od(e,t,r){let o=e.headers.get("content-length");if(!o)return;let i=Number.parseInt(o,10);if(Number.isFinite(i)&&i>t)throw new h({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}})}n(Od,"assertContentLengthWithinLimit");async function qd(e,t,r){return Od(e,t,r),ar(e.body,{maxBytes:t,createLimitError:n(()=>new h({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}}),"createLimitError")})}n(qd,"readBoundedResponseBody");function Md(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(Md,"responseFromBufferedBody");function Dd(e,t){if(!Pd.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(Dd,"resolveRedirectUrl");function ai(e,t){try{return t.validateUrl(e)}catch(r){throw new h({message:"Outbound URL was not allowed.",extensionMembers:{[g]:t.problemCode}},{cause:r})}}n(ai,"validateOutboundUrl");function jd(e,t){throw e instanceof h&&Bt(e.extensionMembers?.[g])?e:new h({message:"Outbound fetch failed.",extensionMembers:{[g]:t}},{cause:e})}n(jd,"normalizeFetchError");function kt(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,i]of Object.entries(t.extra))i!==void 0&&(r[o]=i);t.error!==void 0&&N(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(kt,"logOutboundFailure");async function zd(e,t,r,o,i,a,c){let s=Ke(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";kt(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:i,method:s,host:O(a),error:u,extra:{abortReason:c()}}),jd(u,i)}}n(zd,"fetchWithNormalizedError");function Hd(e){if(e.redirects>=e.maxRedirects)throw new h({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[g]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new h({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[g]:e.problemCode}})}n(Hd,"assertRedirectAllowed");function Bd(e,t){let r=new Headers(e);for(let o of Ed)r.delete(o);for(let o of t)r.delete(o);return r}n(Bd,"stripCrossOriginHeaders");function Ld(e,t,r,o,i){let a={...e,method:t,redirect:"manual",signal:r};return o&&(a.headers=Bd(e.headers,i)),a}n(Ld,"buildRedirectInit");function Nd(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(Nd,"buildInitialRequestInit");function Jd(e){let t=Ke(e.currentInput,e.currentInit);Hd({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=ai(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),i=r.origin!==o.origin,a=r.toString();return{currentInput:a,currentUrl:a,currentInit:Ld(e.currentInit,t,e.signal,i,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(Jd,"followRedirect");async function Yr(e,t,r){let o=r.problemCode??"invalid_request",i=r.maxRedirects??xd,a=r.maxResponseBytes??Td,c=r.timeoutMs??Ud,s=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,f=new AbortController,w=ii(f,t.signal),U=!1,y=setTimeout(()=>{U=!0,f.abort()},c),P=e,k=Nd(e,t,f.signal),z;try{z=ai(Vr(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(Q){throw kt(p,{event:"outbound_url_blocked",problemCode:o,method:Ke(e,t),host:O(Vr(e)),error:Q}),clearTimeout(y),w?.(),Q}let ze=0;try{for(;;){let Q=await zd(p,s,P,k,o,z,()=>U?`timeout_after_${c}ms`:void 0),E=Dd(Q,z);if(E!==void 0)try{let D=Jd({currentInput:P,currentInit:k,currentUrl:z,redirectUrl:E,redirects:ze,maxRedirects:i,problemCode:o,validateUrl:r.validateUrl,signal:f.signal,additionalCrossOriginStrippedHeaders:u});P=D.currentInput,k=D.currentInit,z=D.currentUrl,ze=D.redirects;continue}catch(D){throw kt(p,{event:"outbound_redirect_blocked",problemCode:o,method:Ke(P,k),host:O(z),error:D,extra:{redirects:ze,maxRedirects:i,redirectTargetHost:O(E)}}),D}try{return Md(Q,await qd(Q,a,o))}catch(D){throw kt(p,{event:"outbound_response_size_exceeded",problemCode:o,method:Ke(P,k),host:O(z),error:D,extra:{maxResponseBytes:a,status:Q.status}}),D}}}finally{clearTimeout(y),w?.()}}n(Yr,"runSafeOutboundExchange");async function xt(e,t,r){let o=await Yr(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(i){throw kt(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Ke(e,t),host:O(Vr(e)),error:i,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new h({message:"Outbound JSON response could not be parsed.",extensionMembers:{[g]:r.problemCode??"invalid_request"}},{cause:i})}}n(xt,"runSafeOutboundJsonExchange");function si(e,t={},r={}){return Yr(e,t,{...r,validateUrl:lt})}n(si,"fetchConfiguredOutbound");function ci(e,t={},r={}){return xt(e,t,{...r,validateUrl:lt})}n(ci,"fetchConfiguredOutboundJson");function sr(e,t={},r={}){return xt(e,t,{...r,validateUrl:Uo})}n(sr,"fetchIdentityProviderJson");function di(e,t={},r={}){return xt(e,t,{...r,validateUrl:Wt})}n(di,"fetchCimdClientMetadataJson");function ui(e,t={},r={}){return xt(e,t,{...r,validateUrl:pt})}n(ui,"fetchCimdClientJwksJson");K();import{errors as gi,jwtVerify as yi,SignJWT as _i}from"jose";var $="zuplo-mcp-gateway",V=$,Y="HS256";import{base64url as Gd}from"jose";var Fd=new TextEncoder,$d="MCP gateway could not initialize secure key material.",Zd=32,li=new Map,pi=new Map,Kd;function Wd(){return Kd??Hn.instance.authPrivateKey}n(Wd,"readAuthPrivateKey");function mi(e){return new ee($d,e===void 0?void 0:{cause:e})}n(mi,"createGeneratedKeyMaterialError");function fi(e,t){let r=Gd.decode(t);if(r.byteLength!==Zd)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(fi,"decodeJwkKeyField");function Vd(e){let t=Wd();if(!t)throw mi();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=fi("d",r.d);fi("x",r.x);let i=Fd.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),a=new Uint8Array(i.byteLength+o.byteLength);return a.set(i),a.set(o,i.byteLength),a}catch(r){throw mi(r)}}n(Vd,"decodeGeneratedKeyMaterial");function Yd(e){let t=li.get(e);return t||(t=Vd(e),li.set(e,t)),t}n(Yd,"getMasterKeyMaterial");async function ie(e){let t=pi.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Yd(e.keyMaterialPurpose));return pi.set(e.purpose,r),r}n(ie,"readCachedDerivedKey");var Xd="SHA-256",Qd=32,eu="zuplo-mcp-gateway:",tu=new TextEncoder,hi=new WeakMap;async function Se(e,t){let r=hi.get(e);r||(r=new Map,hi.set(e,r));let o=r.get(t);if(o)return o;let i=await ru(e,t);return r.set(t,i),i}n(Se,"deriveGatewaySigningKey");async function ru(e,t){let r=G(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=tu.encode(`${eu}${t}`),a=await crypto.subtle.deriveBits({name:"HKDF",hash:Xd,salt:new Uint8Array,info:G(i)},o,Qd*8);return new Uint8Array(a)}n(ru,"hkdfExpand");var wi=900,nu=900,ou=po.extend({id:Mo}),iu=ou.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),Ri=vr.extend({id:Do,purpose:d.literal("browser_connect")}),au=vr.extend({purpose:d.literal("browser_connect")}),su=Ri.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),bi=wi*1e3;async function Ii(){return ie({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Se(e,"oauth-state"),"derive")})}n(Ii,"getOAuthStateKey");async function Si(){return ie({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Se(e,"browser-connect"),"derive")})}n(Si,"getBrowserConnectKey");async function Ci(e){let t=Math.floor(Date.now()/1e3)+wi;return new _i(e).setProtectedHeader({alg:Y,typ:"JWT"}).setIssuer($).setAudience(V).setIssuedAt().setExpirationTime(t).sign(await Ii())}n(Ci,"signOAuthState");async function cr(e){try{let{payload:t}=await yi(e,await Ii(),{algorithms:[Y],issuer:$,audience:V});return iu.parse(t)}catch(t){throw t instanceof gi.JWTExpired?new h({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new h({message:"OAuth state could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(cr,"verifyOAuthState");async function vi(e){let t=Math.floor(Date.now()/1e3)+nu,r=au.parse(e),o=Ri.parse({...r,id:Ho()});return new _i(o).setProtectedHeader({alg:Y,typ:"JWT"}).setIssuer($).setAudience(V).setIssuedAt().setExpirationTime(t).sign(await Si())}n(vi,"signBrowserConnectTicket");async function Ai(e){try{let{payload:t}=await yi(e,await Si(),{algorithms:[Y],issuer:$,audience:V});return su.parse(t)}catch(t){throw t instanceof gi.JWTExpired?new h({message:"Browser connect ticket has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new h({message:"Browser connect ticket could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(Ai,"verifyBrowserConnectTicket");async function ki(e){if((await b().consumeBrowserConnectTicket({id:e.id,expiresAt:I(new Date(e.exp*1e3)),now:I(new Date)})).kind==="consumed")throw new h({message:"Browser connect ticket has already been used",extensionMembers:{[g]:"oauth_state_reused"}})}n(ki,"consumeBrowserConnectTicket");function cu(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(cu,"buildConnectRequiredMessage");async function du(e){let t=q(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 vi({...dt(e),purpose:"browser_connect"})),r.toString()}n(du,"buildGatewayBrowserTicketUrl");function uu(e){return H().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(uu,"buildGatewayConnectPath");async function Xr(e){return du({...e,path:uu(e.upstreamServerId),redirect:!0})}n(Xr,"buildGatewayConnectUrl");async function dr(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 Xr(t),message:cu(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(dr,"buildRedirectConnectRequiredResponse");function xi(e){return lu({...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(xi,"buildAdminConnectRequiredResponse");function lu(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(lu,"buildAdminSetupRequiredResponse");var Ti=12;async function Ui(e){let t=await crypto.subtle.digest("SHA-256",G(new TextEncoder().encode(e)));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}n(Ui,"sha256Hex");async function We(e){if(e)return(await Ui(e)).slice(0,Ti)}n(We,"fingerprintSecret");async function Ve(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await Ui(t)).slice(0,Ti)}n(Ve,"fingerprintConnectionIdentity");function Tt(e){return e?e.status!=="active"?"inactive":e.encryptedAccessToken?e.expiresAt&&new Date(e.expiresAt).getTime()<=Date.now()?"expired":"usable":"no_access_token":"no_connection"}n(Tt,"describeAccessTokenState");K();var Pi=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function pu(e,t){return e&&e.length>0?e.join(t):void 0}n(pu,"joinOAuthScopes");function mu(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of Pi)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(mu,"sanitizeAuthorizationServerMetadata");function Ei(e){let t=mu(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(Ei,"sanitizeOAuthDiscoveryState");function Oi(e){let t=new URL(e);for(let r of Pi){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(Oi,"dedupeSingletonAuthorizationRequestParams");function ur(e){let t=new URL(e);return W(t)&&Vn(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(ur,"normalizeLoopbackOAuthRedirectUri");function qi(e){return pu(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(qi,"readProtectedResourceMetadataScope");function fu(e){return`Zuplo MCP Gateway - ${e}`}n(fu,"buildGatewayOAuthClientName");function hu(e,t){return e&&e.length>0?e.join(t):void 0}n(hu,"joinOAuthScopeList");function gu(e){if(e.clientRegistration.mode!=="auto")return hu(e.scopes,e.scopeDelimiter)}n(gu,"readPublicClientMetadataScope");function Qr(e){return new URL(H().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Qr,"buildOAuthClientMetadataDocumentUrl");function en(e){let t=Ie(e.upstreamServerId);return{client_name:fu(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(en,"buildGatewayOAuthClientMetadata");function Mi(e,t,r){let o=Ze(t,r),i=gu(o);return{client_id:Qr({origin:e,upstreamServerId:t}),...en({origin:e,upstreamServerId:t,redirectUri:ur(new URL(o.redirectPath,e)).toString(),scope:i})}}n(Mi,"buildOAuthClientMetadataDocument");K();import{base64url as Ce}from"jose";var yu="SHA-256",Ye="AES-GCM",_u=12,rn="zuplo-secret",nn=1,Di="generated:auth_private_key:token-encryption",wu=d.object({version:d.literal(nn),keyId:d.literal(Di),algorithm:d.literal(Ye),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();async function tn(){return ie({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(yu,G(e));return crypto.subtle.importKey("raw",t,{name:Ye},!1,["encrypt","decrypt"])},"derive")})}n(tn,"getEncryptionKey");function ji(e){return G(new TextEncoder().encode(`${rn}:v${e.version}:${e.keyId}`))}n(ji,"getAssociatedData");function Ru(e){return`${rn}:v${e.version}:${Ce.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(Ru,"encodeEnvelope");function bu(e){let t=`${rn}:v${nn}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(Ce.decode(r));return wu.parse(JSON.parse(o))}n(bu,"decodeEnvelope");async function me(e){let t=await tn(),r=crypto.getRandomValues(new Uint8Array(_u)),o={version:nn,keyId:Di},i=await crypto.subtle.encrypt({name:Ye,iv:r,additionalData:ji(o)},t,new TextEncoder().encode(e));return Ru({...o,algorithm:Ye,iv:Ce.encode(r),ciphertext:Ce.encode(new Uint8Array(i))})}n(me,"encryptSecret");async function ve(e){let t=bu(e);if(t){let c=await tn(),s=await crypto.subtle.decrypt({name:Ye,iv:G(Ce.decode(t.iv)),additionalData:ji(t)},c,G(Ce.decode(t.ciphertext)));return new TextDecoder().decode(s)}let[r,o]=e.split(".");if(!r||!o)throw new ee("Encrypted payload is malformed");let i=await tn(),a=await crypto.subtle.decrypt({name:Ye,iv:G(Ce.decode(r))},i,G(Ce.decode(o)));return new TextDecoder().decode(a)}n(ve,"decryptSecret");var Iu=d.union([ft,rr]),Su=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:er.optional(),authorizationServerMetadata:d.union([mt,tr]).optional()}).passthrough(),Cu="Bearer",vu="__zuplo_refresh_only_upstream_access_token__";function Au(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Au,"splitScopes");function ku(e){return Be.parse(e)}n(ku,"parsePkceCodeVerifier");function xu(e){if(typeof e.expires_in=="number")return I(new Date(Date.now()+e.expires_in*1e3))}n(xu,"readTokenExpiry");async function Tu(e){if(e!==void 0)return me(JSON.stringify(e))}n(Tu,"encryptJson");async function Uu(e,t){if(!e)return;let r=await ve(e);try{return t.parse(JSON.parse(r))}catch(o){throw new h({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:o})}}n(Uu,"decryptJson");function Pu(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(Pu,"clientInformationAllowsRedirectUri");function Eu(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(Eu,"clientInformationMatchesCurrentClientMetadataUrl");function Ou(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(Ou,"isUrlBasedClientInformation");function qu(e,t){return t===void 0?e:{...e,scope:t}}n(qu,"applyOAuthClientMetadataScope");function Mu(e,t){return qi({state:e,delimiter:t})}n(Mu,"readResourceMetadataScope");function Du(e,t){return e&&e.length>0?e.join(t):void 0}n(Du,"joinOAuthScopeList");function ju(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new B(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return ft.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(ju,"buildManualOAuthClientInformation");function zu(e,t){let r=Qr({origin:new URL(t).origin,upstreamServerId:e});return Fr(r)?r:void 0}n(zu,"buildClientMetadataUrl");function Hu(e){for(let t of e)if(t!==void 0)return t}n(Hu,"firstDefined");function Bu(e){let t=Ze(e.target.upstreamServerId,e.target.authProfileId),r=Du(t.scopes,t.scopeDelimiter),o=en({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:ju({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let i=zu(e.target.upstreamServerId,e.redirectUri);return i===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,clientMetadataUrl:i}}n(Bu,"buildInitialOAuthClientSetup");function Lu(e,t){if(t===void 0)return Hu([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(Lu,"readEncryptedClientInformation");var qe=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredScope;scopeDelimiter;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;connection;pendingState;encryptedClientInformation;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;connectionFingerprintValue;usedRefreshTokenFingerprintValue;constructor(t){let r=Bu({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=Lu(t,this.configuredClientInformation)}get authorizationUrl(){return this.authorizationUrlValue}get usedRefreshTokenFingerprint(){return this.usedRefreshTokenFingerprintValue}async connectionFingerprint(){return this.connectionFingerprintValue===void 0&&(this.connectionFingerprintValue=await Ve({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return qu(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return Ci({id:t.id,...dt({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,J()?.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"),!Ou({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Tu(t),await this.syncPendingState(!1)))}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=Ei(Su.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,J()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:O(r.authorizationServerUrl),resourceMetadataHost:O(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=Mu(r,this.scopeDelimiter)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=$e.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=this.connection,a=!r.refresh_token&&!!i?.encryptedRefreshToken,c=r.refresh_token?await me(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:$e.parse({...r,refresh_token:await ve(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let s={id:this.connection?.id??Vt(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await me(r.access_token),encryptedRefreshToken:c,scopes:Au(r.scope??this.readEffectiveScope()),expiresAt:xu(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await b().upsertUpstreamConnection(s),J()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.connection.id,hasRefreshToken:!!c,priorStatus:i?.status,priorUpdatedAt:i?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await We(r.refresh_token),reusedSnapshotRefreshToken:a,scopeCount:s.scopes.length,expiresAt:s.expiresAt},"Upstream OAuth tokens persisted; upstream connection is active")}async redirectToAuthorization(t){let r=Oi(t);this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:ku(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new h({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",i=t==="all"||t==="discovery",a=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),i&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.challengeScope=void 0,this.inferredScope=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(a),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:zo(),...dt({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()+bi)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await b().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await Uu(this.encryptedClientInformation,Iu)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&(!Pu(t,this.redirectUriValue)||!Eu({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=rr.parse({client_id:this.clientMetadataUrl})),this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async readCachedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;this.discoveryStateLoaded=!0}readEffectiveScope(){return this.configuredScope??this.challengeScope??this.inferredScope}async loadStoredTokens(){if(this.tokensLoaded)return this.cachedTokens;if(this.tokensLoaded=!0,!this.connection||this.connection.status!=="active"){J()?.debug({event:"upstream_oauth_tokens_not_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.connection?.id,status:this.connection?.status??"not_connected"},"Upstream OAuth tokens not loaded; connection is not active");return}let t=this.connection.encryptedAccessToken?await ve(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await ve(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=J();this.usedRefreshTokenFingerprintValue=o?await We(r):void 0,o?.debug({event:"upstream_oauth_tokens_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.connection.id,hasAccessToken:!!t,hasRefreshToken:!!r,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,expiresAt:this.connection.expiresAt},"Upstream OAuth tokens loaded from stored connection");let i=$e.parse({access_token:t??vu,token_type:Cu,refresh_token:r,scope:this.connection.scopes.length>0?this.connection.scopes.join(" "):void 0});return this.cachedTokens=i,i}async persistCredentialInvalidation(t){if(!this.connection)return;let r=this.connection.status,o=this.connection.updatedAt,i={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&&(i.status="reconsent_required",i.encryptedAccessToken=void 0,i.encryptedRefreshToken=void 0,i.scopes=[],i.expiresAt=void 0),i.metadata=this.readStoredOAuthPersistence(this.connection.metadata?.connectedBySubjectId),this.connection=await b().upsertUpstreamConnection(i);let a=J();if(a){let c={event:"upstream_oauth_credentials_invalidated",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.connection.id,clearedTokens:t,priorStatus:r,newStatus:this.connection.status,priorUpdatedAt:o,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue};t?a.warn(c,"Upstream OAuth credentials invalidated; connection now requires reconsent"):a.debug(c,"Upstream OAuth credential metadata rewritten")}}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var Nu=3e4,Ju=256*1024,Gu=2,Fu="does not support dynamic client registration",$u=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],Zu=["HTTP 403 Forbidden","Access Denied","permission to access"],Ku=new Set(["access_denied","invalid_client","invalid_grant","invalid_request","invalid_scope","invalid_target","unauthorized_client","unsupported_grant_type"]);function Wu(e){return e instanceof Error&&e.message.includes(Fu)}n(Wu,"isDynamicClientRegistrationUnsupported");function Vu(e){return e instanceof Error&&$u.some(t=>e.message.includes(t))}n(Vu,"isProtectedResourceMetadataUnavailable");function Yu(e){return e instanceof Error&&Zu.some(t=>e.message.includes(t))}n(Yu,"isUpstreamProviderAccessDenied");function Xu(e){return e instanceof A&&Ku.has(e.errorCode)}n(Xu,"isStoredConnectionReconsentError");function Qu(e){if(e.error instanceof h&&e.error.extensionMembers?.[g]!==void 0)return e.error;if(Wu(e.error))return new h({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(Vu(e.error))return new h({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(Yu(e.error))return new h({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(Qu,"mapUpstreamOAuthSetupError");function el(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(el,"readOAuthFetchRequest");function tl(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(tl,"responseLooksJson");function rl(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(rl,"responseLooksHtml");function nl(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new h({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[g]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[_e]:e.response.status,[Le]:r,[we]:e.request.url.toString(),[Ne]:e.body}})}n(nl,"throwUpstreamHtmlError");function ol(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(ol,"readUpstreamOAuthErrorBody");function il(e){let{error:t,errorDescription:r}=ol(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.request.method??"GET",host:O(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(il,"logUpstreamOAuthHttpError");function Hi(e){return async(t,r)=>{let o=el(t),i=J(),a=Date.now(),c=await si(t,r,{maxRedirects:Gu,maxResponseBytes:Ju,problemCode:"upstream_token_exchange_failed",timeoutMs:Nu}),s=await c.clone().text();if(i?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:o.method??"GET",host:O(o.url),path:o.url.pathname,status:c.status,durationMs:Date.now()-a,responseChars:s.length},"Upstream OAuth HTTP request completed"),c.ok||il({log:i,upstreamServerId:e,request:o,response:c,body:s}),!c.ok&&rl(c,s)&&nl({upstreamServerId:e,request:o,response:c,body:s}),!tl(c,s))return c;try{JSON.parse(s)}catch(u){throw new h({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(Hi,"createUpstreamOAuthFetch");function Bi(e){J()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:O(e.serverUrl),resourceMetadataHost:O(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}n(Bi,"logUpstreamOAuthFlowStarted");function Li(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=O(e.serverUrl);r!==void 0&&(t.serverHost=r);let o=e.error instanceof h?e.error.extensionMembers?.[g]:void 0;typeof o=="string"&&(t.code=o),N(t,"error",e.error),J()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(Li,"logUpstreamOAuthFlowFailed");async function Ni(e,t){e.applyChallengeScope(t.requestedScope),Bi({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Hi(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),await Gr(e,r)}catch(r){Li({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=Qu({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(Ni,"runUpstreamOAuth");async function al(e,t){e.applyChallengeScope(t.requestedScope),Bi({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Hi(t.upstreamServerId)};t.requestedScope!==void 0&&(r.scope=t.requestedScope);try{return await Gr(e,r)}catch(o){throw Li({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:o}),o}}n(al,"exchangeUpstreamAuthorizationCode");async function Ji(e,t){let r=await Ni(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new h({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new h({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Ji,"requireUpstreamAuthorizationRedirect");async function Gi(e){let t=Tt(e.connection),r=!!e.forceRefresh,o=!r&&t==="usable",i=J(),a=i?await Ve({owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}):void 0;if(i?.debug({event:"upstream_oauth_refresh_decision",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,ownerMode:e.target.owner.mode,connectionFingerprint:a,connectionId:e.connection?.id,accessTokenState:t,forceRefresh:r,willRefresh:!o,expiresAt:e.connection?.expiresAt,connectionUpdatedAt:e.connection?.updatedAt},o?"Reusing stored upstream access token":"Refreshing upstream credential"),o)return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let c;try{c=await Ni(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(s){if(e.connection===void 0||!Xu(s))throw s;return i?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:s.errorCode,connectionFingerprint:a,connectionId:e.connection.id,rejectedRefreshTokenFingerprint:e.provider.usedRefreshTokenFingerprint,connectionUpdatedAt:e.connection.updatedAt,connectionExpiresAt:e.connection.expiresAt},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),{kind:"connect_required",payload:await zi({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}if(c==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(c!=="REDIRECT")throw new h({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${c}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new h({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 zi({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(Gi,"authorizeUpstreamOAuthSession");async function sl(e){let t=await cr(e.stateToken),r=await b().consumeUpstreamOAuthState({id:t.id,now:I(new Date)}),o=cl(r);return dl({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),ul(o),o}n(sl,"consumeStoredCallbackState");function cl(e){switch(e.kind){case"consumed":throw new h({message:"OAuth state has already been used",extensionMembers:{[g]:"oauth_state_reused"}});case"missing":throw new h({message:"OAuth state is missing or expired",extensionMembers:{[g]:"oauth_state_expired"}});case"available":return e.record}}n(cl,"readConsumedCallbackState");function dl(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 h({message:"OAuth callback did not match the initiating request",extensionMembers:{[g]:"oauth_callback_mismatch"}})}n(dl,"assertStoredCallbackStateMatches");function ul(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new h({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}})}n(ul,"assertStoredCallbackStateFresh");async function zi(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),xi(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),dr(t)}n(zi,"buildOAuthConnectRequiredResponse");async function Fi(e){let t=await sl({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Ft(t),[o]=await b().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),i={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&&(i.connection=o);let a=new qe(i),c=await al(a,{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 h({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${c}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new h({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Fi,"finishUpstreamOAuthCallback");K();import{importPKCS8 as ll,SignJWT as pl}from"jose";var Zi=1e4,Ki=64*1024,Wi=2,ml=300,oe=d.string().min(1),fl=d.object({access_token:oe,issued_token_type:d.literal(kr),token_type:d.string().optional(),expires_in:d.number().int().positive().optional(),scope:oe.optional()}).passthrough(),hl=d.object({id_token:oe,token_type:oe.optional(),expires_in:d.number().int().positive().optional(),refresh_token:oe.optional(),scope:oe.optional()}).passthrough(),gl=d.object({access_token:oe,token_type:oe,expires_in:d.number().int().positive().optional(),scope:oe.optional(),resource:oe.optional(),refresh_token:oe.optional()}).passthrough();function $i(e){return encodeURIComponent(e).replace(/%20/g,"+")}n($i,"formEncodeClientCredential");function yl(e){return e.replaceAll("\\n",`
25
+ import{$b as Ac,$c as Co,Ab as q,Ac as yo,Ad as x,Bb as Qn,Bc as _o,Bd as Yt,Cb as He,Cc as I,Cd as xc,Db as eo,Dc as de,Dd as Tc,Eb as Be,Ec as Ge,Fb as g,Fc as N,Gb as Le,Gc as O,Hb as Ne,Hc as wo,Ib as _e,Ic as J,Jb as we,Jc as Ro,Kb as Bt,Kc as be,Lb as to,Lc as Ar,Mb as ne,Mc as $t,N as Jn,Nb as ro,Nc as kr,O as l,Ob as ce,Oc as Zt,P as Gn,Pb as R,Pc as ut,Q as Sr,Qb as Lt,Qc as Fe,R as se,Rb as L,Rc as bo,S as Fn,Sb as Re,Sc as ue,T as _,Tb as _c,Tc as xr,U as ye,Ub as wc,Uc as Tr,V as Ht,Vb as Rc,Vc as Io,W as $n,Wb as bc,Wc as Kt,X as Zn,Xb as Ic,Xc as Ur,Y as Kn,Yb as Sc,Yc as Pr,Z as d,Zb as Cc,Zc as So,_ as K,_b as vc,_c as M,ac as kc,ad as vo,bc as no,bd as Er,cc as oo,cd as Ao,dc as io,dd as ko,ea as Wn,ec as Nt,ed as Or,fc as Cr,fd as xo,gc as Jt,gd as Te,h as Z,hc as Gt,hd as To,ic as st,id as lt,jc as ao,jd as Uo,kc as so,kd as Wt,lc as co,ld as pt,mc as ct,md as Po,nc as uo,nd as Eo,oc as Je,od as Oo,p as xe,pc as lo,pd as qo,q as Bn,qc as vr,qd as Mo,rc as po,rd as Do,s as Ln,sc as dt,sd as jo,tc as Ft,td as Vt,uc as mo,ud as zo,vc as fo,vd as Ho,w as Nn,wb as Vn,wc as ho,wd as b,xb as W,xc as go,xd as v,y as zt,yb as Yn,yc as te,yd as G,zb as Xn,zc as H,zd as le}from"../chunk-36XLJ4X6.js";import"../chunk-4MNJC7E2.js";import{a as S}from"../chunk-54PA7VDV.js";import{$ as ee,a as n,aa as h,ba as B,ca as Hn,da as jt}from"../chunk-DSZS6PZJ.js";K();function Uc(e){let t=Gt.safeParse(e);return t.success?t.data.id:void 0}n(Uc,"parseJsonRpcRequestId");function Bo(e){if(e!==void 0)try{let t=JSON.parse(new TextDecoder().decode(e));return Uc(t)}catch{return}}n(Bo,"readJsonRpcRequestIdFromBody");function Xt(e){return ao.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(Xt,"jsonRpcErrorResponse");function Lo(e){return new co([so.parse({mode:"url",message:e.message,elicitationId:e.elicitationId,url:e.url})],e.message)}n(Lo,"urlElicitationRequiredError");var Qt=d.record(d.string(),d.unknown()),Pc=d.record(d.string(),d.unknown()),Ec=d.object({name:d.string().min(1),description:d.string().min(1).optional(),annotations:Pc.optional(),_meta:Qt.optional()}).strict(),Oc=d.object({name:d.string().min(1),description:d.string().min(1).optional(),_meta:Qt.optional()}).strict(),qc=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:Qt.optional()}).strict(),Mc=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:Qt.optional()}).strict(),Dc=d.array(d.union([d.string(),Ec])),jc=d.array(d.union([d.string(),Oc])),zc=d.array(d.union([d.string(),qc])),Hc=d.array(d.union([d.string(),Mc])),Bc=d.object({tools:Dc.optional(),prompts:jc.optional(),resources:zc.optional(),resourceTemplates:Hc.optional()}).strict(),Mr=[{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 Lc(e,t){return Yn(Bc,e,`MCP capability filter policy "${t}"`)}n(Lc,"parseMcpCapabilityFilterOptions");function F(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(F,"isRecord");function Nc(e,t){if(!F(e))return;let r=e[t];return typeof r=="string"?r:void 0}n(Nc,"readParamString");function Dr(e){let t=e.id;return typeof t=="string"||typeof t=="number"||t===null?t:void 0}n(Dr,"readRequestId");function Fo(e){return e===void 0?void 0:JSON.stringify(e)}n(Fo,"requestIdKey");function Jc(e){let t={};for(let r of Mr){let o=e[r.option];if(o===void 0)continue;let i=new Map;for(let a of o){let c=Zc(a,r.itemProperty);c!==void 0&&i.set(c.key,c)}t[r.option]=i}return t}n(Jc,"buildProjectionMaps");function jr(e){return Mr.find(t=>t.listMethod===e)}n(jr,"findListRule");function Gc(e){return e.requests.some(t=>{if(!F(t))return!1;let r=jr(t.method);return r!==void 0&&e.projectionMaps[r.option]!==void 0})}n(Gc,"shouldFilterListResponses");function Fc(e){for(let t of Mr){let r=e.projectionMaps[t.option];if(r!==void 0)for(let o of t.directMethods){if(e.request.method!==o.method)continue;let i=Nc(e.request.params,o.paramProperty);if(i!==void 0&&!r.has(i))return{id:Dr(e.request)}}}}n(Fc,"findDisallowedDirectAccess");function $c(e){return Response.json(Xt({id:e,error:{code:st.MethodNotFound,message:"Method not found"}}))}n($c,"methodNotFoundResponse");function Zc(e,t){if(typeof e=="string")return{key:e,overlay:{}};if(!F(e))return;let r=e[t];if(typeof r=="string")return{key:r,overlay:e}}n(Zc,"buildProjection");function No(e){let t=e.base[e.property],r=e.overlay[e.property];return F(r)?F(t)?{...t,...r}:r:t}n(No,"mergeRecordProperty");function Kc(e,t){let r={...e,...t.overlay},o=No({base:e,overlay:t.overlay,property:"annotations"});o!==void 0&&(r.annotations=o);let i=No({base:e,overlay:t.overlay,property:"_meta"});return i!==void 0&&(r._meta=i),r}n(Kc,"applyProjection");function Jo(e,t,r){if(!F(e))return e;let o=e.result;if(!F(o))return e;let i=o[t.resultProperty];return!Array.isArray(i)||!i.every(a=>F(a)&&typeof a[t.itemProperty]=="string")?e:{...e,result:{...o,[t.resultProperty]:i.flatMap(a=>{if(!F(a))return[];let c=a[t.itemProperty];if(typeof c!="string")return[];let s=r.get(c);return s===void 0?[]:[Kc(a,s)]})}}}n(Jo,"filterAndProjectItems");function Wc(e){let t=new Map;if(!Array.isArray(e))return t;for(let r of e){if(!F(r))continue;let o=jr(r.method),i=Dr(r),a=Fo(i);o!==void 0&&a!==void 0&&t.set(a,o)}return t}n(Wc,"buildListRulesByResponseId");function Vc(e){if(Array.isArray(e.responseBody)){let o=Wc(e.requestBody);return o.size===0?e.responseBody:e.responseBody.map(i=>{if(!F(i)||"error"in i)return i;let a=Fo(Dr(i)),c=a===void 0?void 0:o.get(a),s=c===void 0?void 0:e.projectionMaps[c.option];return c===void 0||s===void 0?i:Jo(i,c,s)})}if(!F(e.requestBody)||!F(e.responseBody)||"error"in e.responseBody)return e.responseBody;let t=jr(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(Vc,"filterJsonRpcResponse");async function Go(e){return e.clone().json()}n(Go,"readJson");function Yc(e){return e.headers.get("content-type")?.includes("json")??!1}n(Yc,"isJsonResponse");var qr=class extends zt{static{n(this,"McpCapabilityFilterInboundPolicy")}#e;constructor(t,r){let o=Lc(t,r);super(o,r),this.#e=Jc(o)}async handler(t,r){Z("policy.inbound.mcp-capability-filter");let o;try{o=await Go(t)}catch{return t}let i=Array.isArray(o)?o:[o];for(let a of i){if(!F(a))continue;let c=Fc({request:a,projectionMaps:this.#e});if(c!==void 0)return $c(c.id)}return Gc({requests:i,projectionMaps:this.#e})&&r.addResponseSendingHook(async a=>{if(!Yc(a))return a;let c;try{c=await Go(a)}catch{return a}let s=Vc({requestBody:o,responseBody:c,projectionMaps:this.#e});if(s===c)return a;let u=new Headers(a.headers);return u.delete("content-length"),new Response(JSON.stringify(s),{status:a.status,statusText:a.statusText,headers:u})}),t}};var zr;zr=globalThis.crypto;async function Xc(e){return(await zr).getRandomValues(new Uint8Array(e))}n(Xc,"getRandomValues");async function Qc(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let i=await Xc(e-o.length);for(let a of i)a<r&&(o+=t[a%t.length])}return o}n(Qc,"random");async function ed(e){return await Qc(e)}n(ed,"generateVerifier");async function td(e){let t=await(await zr).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}n(td,"generateChallenge");async function Hr(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await ed(e),r=await td(t);return{code_verifier:t,code_challenge:r}}n(Hr,"pkceChallenge");K();var j=Gn().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Zn.custom,message:"URL must be parseable",fatal:!0}),Jn}).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"}),er=Ht({resource:l().url(),authorization_servers:_(j).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:se().optional(),authorization_details_types_supported:_(l()).optional(),dpop_signing_alg_values_supported:_(l()).optional(),dpop_bound_access_tokens_required:se().optional()}),mt=Ht({issuer:l(),authorization_endpoint:j,token_endpoint:j,registration_endpoint:j.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:j.optional(),revocation_endpoint:j.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:se().optional()}),rd=Ht({issuer:l(),authorization_endpoint:j,token_endpoint:j,userinfo_endpoint:j.optional(),jwks_uri:j,registration_endpoint:j.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:se().optional(),request_parameter_supported:se().optional(),request_uri_parameter_supported:se().optional(),require_request_uri_registration:se().optional(),op_policy_uri:j.optional(),op_tos_uri:j.optional(),client_id_metadata_document_supported:se().optional()}),tr=ye({...rd.shape,...mt.pick({code_challenge_methods_supported:!0}).shape}),$e=ye({access_token:l(),id_token:l().optional(),token_type:l(),expires_in:Kn.number().optional(),scope:l().optional(),refresh_token:l().optional()}).strip(),Zo=ye({error:l(),error_description:l().optional(),error_uri:l().optional()}),$o=j.optional().or($n("").transform(()=>{})),nd=ye({redirect_uris:_(j),token_endpoint_auth_method:l().optional(),grant_types:_(l()).optional(),response_types:_(l()).optional(),client_name:l().optional(),client_uri:j.optional(),logo_uri:$o,scope:l().optional(),contacts:_(l()).optional(),tos_uri:$o,policy_uri:l().optional(),jwks_uri:j.optional(),jwks:Fn().optional(),software_id:l().optional(),software_version:l().optional(),software_statement:l().optional()}).strip(),rr=ye({client_id:l(),client_secret:l().optional(),client_id_issued_at:Sr().optional(),client_secret_expires_at:Sr().optional()}).strip(),ft=nd.merge(rr),Zh=ye({error:l(),error_description:l().optional()}).strip(),Kh=ye({token:l(),token_type_hint:l().optional()}).strip();function Ko(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}n(Ko,"resourceUrlFromServerUrl");function Wo({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 i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",a=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return i.startsWith(a)}n(Wo,"checkResourceAllowed");var A=class extends Error{static{n(this,"OAuthError")}constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},ht=class extends A{static{n(this,"InvalidRequestError")}};ht.errorCode="invalid_request";var Ue=class extends A{static{n(this,"InvalidClientError")}};Ue.errorCode="invalid_client";var Pe=class extends A{static{n(this,"InvalidGrantError")}};Pe.errorCode="invalid_grant";var Ee=class extends A{static{n(this,"UnauthorizedClientError")}};Ee.errorCode="unauthorized_client";var gt=class extends A{static{n(this,"UnsupportedGrantTypeError")}};gt.errorCode="unsupported_grant_type";var yt=class extends A{static{n(this,"InvalidScopeError")}};yt.errorCode="invalid_scope";var _t=class extends A{static{n(this,"AccessDeniedError")}};_t.errorCode="access_denied";var pe=class extends A{static{n(this,"ServerError")}};pe.errorCode="server_error";var wt=class extends A{static{n(this,"TemporarilyUnavailableError")}};wt.errorCode="temporarily_unavailable";var Rt=class extends A{static{n(this,"UnsupportedResponseTypeError")}};Rt.errorCode="unsupported_response_type";var bt=class extends A{static{n(this,"UnsupportedTokenTypeError")}};bt.errorCode="unsupported_token_type";var It=class extends A{static{n(this,"InvalidTokenError")}};It.errorCode="invalid_token";var St=class extends A{static{n(this,"MethodNotAllowedError")}};St.errorCode="method_not_allowed";var Ct=class extends A{static{n(this,"TooManyRequestsError")}};Ct.errorCode="too_many_requests";var Oe=class extends A{static{n(this,"InvalidClientMetadataError")}};Oe.errorCode="invalid_client_metadata";var vt=class extends A{static{n(this,"InsufficientScopeError")}};vt.errorCode="insufficient_scope";var At=class extends A{static{n(this,"InvalidTargetError")}};At.errorCode="invalid_target";var Vo={[ht.errorCode]:ht,[Ue.errorCode]:Ue,[Pe.errorCode]:Pe,[Ee.errorCode]:Ee,[gt.errorCode]:gt,[yt.errorCode]:yt,[_t.errorCode]:_t,[pe.errorCode]:pe,[wt.errorCode]:wt,[Rt.errorCode]:Rt,[bt.errorCode]:bt,[It.errorCode]:It,[St.errorCode]:St,[Ct.errorCode]:Ct,[Oe.errorCode]:Oe,[vt.errorCode]:vt,[At.errorCode]:At};function od(e){return["client_secret_basic","client_secret_post","none"].includes(e)}n(od,"isClientAuthMethod");var Br="code",Lr="S256";function id(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&od(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(id,"selectClientAuthMethod");function ad(e,t,r,o){let{client_id:i,client_secret:a}=t;switch(e){case"client_secret_basic":sd(i,a,r);return;case"client_secret_post":cd(i,a,o);return;case"none":dd(i,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}n(ad,"applyClientAuthentication");function sd(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(sd,"applyBasicAuth");function cd(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}n(cd,"applyPostAuth");function dd(e,t){t.set("client_id",e)}n(dd,"applyPublicAuth");async function Xo(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let o=Zo.parse(JSON.parse(r)),{error:i,error_description:a,error_uri:c}=o,s=Vo[i]||pe;return new s(a||"",c)}catch(o){let i=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${r}`;return new pe(i)}}n(Xo,"parseErrorResponse");async function Gr(e,t){try{return await Nr(e,t)}catch(r){if(r instanceof Ue||r instanceof Ee)return await e.invalidateCredentials?.("all"),await Nr(e,t);if(r instanceof Pe)return await e.invalidateCredentials?.("tokens"),await Nr(e,t);throw r}}n(Gr,"auth");async function Nr(e,{serverUrl:t,authorizationCode:r,scope:o,resourceMetadataUrl:i,fetchFn:a}){let c=await e.discoveryState?.(),s,u,p,f=i;if(!f&&c?.resourceMetadataUrl&&(f=new URL(c.resourceMetadataUrl)),c?.authorizationServerUrl){if(u=c.authorizationServerUrl,s=c.resourceMetadata,p=c.authorizationServerMetadata??await ti(u,{fetchFn:a}),!s)try{s=await ei(t,{resourceMetadataUrl:f},a)}catch{}(p!==c.authorizationServerMetadata||s!==c.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:f?.toString(),resourceMetadata:s,authorizationServerMetadata:p})}else{let E=await hd(t,{resourceMetadataUrl:f,fetchFn:a});u=E.authorizationServerUrl,p=E.authorizationServerMetadata,s=E.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(u),resourceMetadataUrl:f?.toString(),resourceMetadata:s,authorizationServerMetadata:p})}let w=await ud(t,e,s),U=o||s?.scopes_supported?.join(" ")||e.clientMetadata.scope,y=await Promise.resolve(e.clientInformation());if(!y){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let E=p?.client_id_metadata_document_supported===!0,D=e.clientMetadataUrl;if(D&&!Fr(D))throw new Oe(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${D}`);if(E&&D)y={client_id:D},await e.saveClientInformation?.(y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let zn=await Rd(u,{metadata:p,clientMetadata:e.clientMetadata,scope:U,fetchFn:a});await e.saveClientInformation(zn),y=zn}}let P=!e.redirectUrl;if(r!==void 0||P){let E=await wd(e,u,{metadata:p,resource:w,authorizationCode:r,fetchFn:a});return await e.saveTokens(E),"AUTHORIZED"}let k=await e.tokens();if(k?.refresh_token)try{let E=await _d(u,{metadata:p,clientInformation:y,refreshToken:k.refresh_token,resource:w,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(E),"AUTHORIZED"}catch(E){if(!(!(E instanceof A)||E instanceof pe))throw E}let z=e.state?await e.state():void 0,{authorizationUrl:ze,codeVerifier:Q}=await gd(u,{metadata:p,clientInformation:y,state:z,redirectUrl:e.redirectUrl,scope:U,resource:w});return await e.saveCodeVerifier(Q),await e.redirectToAuthorization(ze),"REDIRECT"}n(Nr,"authInternal");function Fr(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}n(Fr,"isHttpsUrl");async function ud(e,t,r){let o=Ko(e);if(t.validateResourceURL)return await t.validateResourceURL(o,r?.resource);if(r){if(!Wo({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(ud,"selectResourceURL");function Qo(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,o]=t.split(" ");if(r.toLowerCase()!=="bearer"||!o)return{};let i=Jr(e,"resource_metadata")||void 0,a;if(i)try{a=new URL(i)}catch{}let c=Jr(e,"scope")||void 0,s=Jr(e,"error")||void 0;return{resourceMetadataUrl:a,scope:c,error:s}}n(Qo,"extractWWWAuthenticateParams");function Jr(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=r.match(o);return i?i[1]||i[2]:null}n(Jr,"extractFieldFromWwwAuth");async function ei(e,t,r=fetch){let o=await md(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 er.parse(await o.json())}n(ei,"discoverOAuthProtectedResourceMetadata");async function $r(e,t,r=fetch){try{return await r(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?$r(e,void 0,r):void 0;throw o}}n($r,"fetchWithCorsRetry");function ld(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}n(ld,"buildWellKnownPath");async function Yo(e,t,r=fetch){return await $r(e,{"MCP-Protocol-Version":t},r)}n(Yo,"tryMetadataDiscovery");function pd(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}n(pd,"shouldAttemptFallback");async function md(e,t,r,o){let i=new URL(e),a=o?.protocolVersion??Cr,c;if(o?.metadataUrl)c=new URL(o.metadataUrl);else{let u=ld(t,i.pathname);c=new URL(u,o?.metadataServerUrl??i),c.search=i.search}let s=await Yo(c,a,r);if(!o?.metadataUrl&&pd(s,i.pathname)){let u=new URL(`/.well-known/${t}`,i);s=await Yo(u,a,r)}return s}n(md,"discoverMetadataWithFallback");function fd(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 i=t.pathname;return i.endsWith("/")&&(i=i.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:"oidc"}),o.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}n(fd,"buildDiscoveryUrls");async function ti(e,{fetchFn:t=fetch,protocolVersion:r=Cr}={}){let o={"MCP-Protocol-Version":r,Accept:"application/json"},i=fd(e);for(let{url:a,type:c}of i){let s=await $r(a,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 ${a}`)}return c==="oauth"?mt.parse(await s.json()):tr.parse(await s.json())}}}n(ti,"discoverAuthorizationServerMetadata");async function hd(e,t){let r,o;try{r=await ei(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 i=await ti(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:i,resourceMetadata:r}}n(hd,"discoverOAuthServerInfo");async function gd(e,{metadata:t,clientInformation:r,redirectUrl:o,scope:i,state:a,resource:c}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Br))throw new Error(`Incompatible auth server: does not support response type ${Br}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Lr))throw new Error(`Incompatible auth server: does not support code challenge method ${Lr}`)}else s=new URL("/authorize",e);let u=await Hr(),p=u.code_verifier,f=u.code_challenge;return s.searchParams.set("response_type",Br),s.searchParams.set("client_id",r.client_id),s.searchParams.set("code_challenge",f),s.searchParams.set("code_challenge_method",Lr),s.searchParams.set("redirect_uri",String(o)),a&&s.searchParams.set("state",a),i&&s.searchParams.set("scope",i),i?.includes("offline_access")&&s.searchParams.append("prompt","consent"),c&&s.searchParams.set("resource",c.href),{authorizationUrl:s,codeVerifier:p}}n(gd,"startAuthorization");function yd(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}n(yd,"prepareAuthorizationCodeRequest");async function ri(e,{metadata:t,tokenRequestParams:r,clientInformation:o,addClientAuthentication:i,resource:a,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(a&&r.set("resource",a.href),i)await i(u,r,s,t);else if(o){let f=t?.token_endpoint_auth_methods_supported??[],w=id(o,f);ad(w,o,u,r)}let p=await(c??fetch)(s,{method:"POST",headers:u,body:r});if(!p.ok)throw await Xo(p);return $e.parse(await p.json())}n(ri,"executeTokenRequest");async function _d(e,{metadata:t,clientInformation:r,refreshToken:o,resource:i,addClientAuthentication:a,fetchFn:c}){let s=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),u=await ri(e,{metadata:t,tokenRequestParams:s,clientInformation:r,addClientAuthentication:a,resource:i,fetchFn:c});return{refresh_token:o,...u}}n(_d,"refreshAuthorization");async function wd(e,t,{metadata:r,resource:o,authorizationCode:i,fetchFn:a}={}){let c=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(c)),!s){if(!i)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=yd(i,p,e.redirectUrl)}let u=await e.clientInformation();return ri(t,{metadata:r,tokenRequestParams:s,clientInformation:u??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:a})}n(wd,"fetchToken");async function Rd(e,{metadata:t,clientMetadata:r,scope:o,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");a=new URL(t.registration_endpoint)}else a=new URL("/register",e);let c=await(i??fetch)(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...o!==void 0?{scope:o}:{}})});if(!c.ok)throw await Xo(c);return ft.parse(await c.json())}n(Rd,"registerClient");var Zr="zuplo.com",bd=new Set(["co.jp","co.kr","co.nz","co.uk","com.au","com.br","com.cn","com.mx","com.sg","co.in"]),Id=[".example.test",".example.com",".example.org",".invalid",".localhost",".test"];function ni(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}n(ni,"s2FaviconHref");function Sd(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(Sd,"strictFaviconHref");var nr=ni(Zr);function Kr(e){let t=e.toLowerCase();return t===Zr||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?ni(Zr):Sd(e)}n(Kr,"resolveIconHref");function Cd(e){try{return new URL(`http://${e}`).hostname}catch{return e}}n(Cd,"hostnameFromHost");function vd(e){return e==="localhost"||e.includes(":")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)}n(vd,"isLocalOrAddressHost");function Ad(e){let t=Cd(e).toLowerCase().replace(/\.$/,"");if(vd(t)||Id.some(a=>t===a.slice(1)||t.endsWith(a)))return t;let r=t.split(".").filter(Boolean);if(r.length<=2)return t;let o=r.slice(-2).join("."),i=bd.has(o)?3:2;return r.slice(-i).join(".")}n(Ad,"inferFaviconDomain");function Wr(e){return{src:Kr(Ad(e)),mimeType:"image/png",sizes:["128x128"]}}n(Wr,"resolveMcpFaviconIcon");function or(e){try{return Wr(new URL(e).host)}catch{return}}n(or,"resolveMcpFaviconIconFromUrl");function Ie(e){let t=te().connectionsById.get(e);if(!t)throw new B(`Unknown upstream server "${e}". Check the route's MCP upstream policy and ensure policies.json declares a matching upstream connection.`);return{displayName:t.displayName,description:t.description,serverInfo:t.serverInfo,transport:{baseUrl:t.mcpUrl,resourceMetadataUrl:t.protectedResourceMetadataUrl}}}n(Ie,"getUpstreamServerConfig");function ir(e){let t=te().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw new B(`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(ir,"getUpstreamAuthConfig");function Ze(e,t){let r=ir({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-oauth"&&r.mode!=="user-oauth")throw new B(`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(Ze,"requireUpstreamOAuthConfig");function oi(e,t){let r=ir({upstreamServerId:e,authProfileId:t});if(r.mode!=="id-jag")throw new B(`Upstream server "${e}" does not use upstream ID-JAG. Select authMode "id-jag" before requesting an upstream XAA token exchange.`);return r.idJag}n(oi,"requireUpstreamIdJagConfig");function ii(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(ii,"mergeAbortSignals");async function kd(e){try{await e.cancel()}catch{}}n(kd,"cancelReader");async function ar(e,t){if(!e)return new Uint8Array;let r=e.getReader(),o=[],i=0,a=await r.read();for(;!a.done;){let u=a.value;if(i+=u.byteLength,i>t.maxBytes)throw await kd(r),t.createLimitError();o.push(u),a=await r.read()}let c=new Uint8Array(i),s=0;for(let u of o)c.set(u,s),s+=u.byteLength;return c}n(ar,"readBoundedByteStream");var xd=2,Td=1024*1024,Ud=1e4,Pd=new Set([301,302,303,307,308]),Ed=["authorization","proxy-authorization","cookie","cookie2"];function Vr(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}n(Vr,"readRequestUrl");function Ke(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}n(Ke,"readRequestMethod");function Od(e,t,r){let o=e.headers.get("content-length");if(!o)return;let i=Number.parseInt(o,10);if(Number.isFinite(i)&&i>t)throw new h({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}})}n(Od,"assertContentLengthWithinLimit");async function qd(e,t,r){return Od(e,t,r),ar(e.body,{maxBytes:t,createLimitError:n(()=>new h({message:"Outbound response exceeded the maximum allowed size.",extensionMembers:{[g]:r}}),"createLimitError")})}n(qd,"readBoundedResponseBody");function Md(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(Md,"responseFromBufferedBody");function Dd(e,t){if(!Pd.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}n(Dd,"resolveRedirectUrl");function ai(e,t){try{return t.validateUrl(e)}catch(r){throw new h({message:"Outbound URL was not allowed.",extensionMembers:{[g]:t.problemCode}},{cause:r})}}n(ai,"validateOutboundUrl");function jd(e,t){throw e instanceof h&&Bt(e.extensionMembers?.[g])?e:new h({message:"Outbound fetch failed.",extensionMembers:{[g]:t}},{cause:e})}n(jd,"normalizeFetchError");function kt(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,i]of Object.entries(t.extra))i!==void 0&&(r[o]=i);t.error!==void 0&&N(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}n(kt,"logOutboundFailure");async function zd(e,t,r,o,i,a,c){let s=Ke(r,o);try{return await t(r,o)}catch(u){let p=u instanceof DOMException&&u.name==="AbortError";kt(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:i,method:s,host:O(a),error:u,extra:{abortReason:c()}}),jd(u,i)}}n(zd,"fetchWithNormalizedError");function Hd(e){if(e.redirects>=e.maxRedirects)throw new h({message:"Outbound redirects exceeded the maximum allowed depth.",extensionMembers:{[g]:e.problemCode}});if(e.method!=="GET"&&e.method!=="HEAD")throw new h({message:"Outbound redirect after a non-idempotent request was blocked.",extensionMembers:{[g]:e.problemCode}})}n(Hd,"assertRedirectAllowed");function Bd(e,t){let r=new Headers(e);for(let o of Ed)r.delete(o);for(let o of t)r.delete(o);return r}n(Bd,"stripCrossOriginHeaders");function Ld(e,t,r,o,i){let a={...e,method:t,redirect:"manual",signal:r};return o&&(a.headers=Bd(e.headers,i)),a}n(Ld,"buildRedirectInit");function Nd(e,t,r){let o={...t,redirect:"manual",signal:r};return o.headers===void 0&&e instanceof Request&&(o.headers=e.headers),o}n(Nd,"buildInitialRequestInit");function Jd(e){let t=Ke(e.currentInput,e.currentInit);Hd({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=ai(e.redirectUrl,{problemCode:e.problemCode,validateUrl:e.validateUrl}),o=new URL(e.currentUrl),i=r.origin!==o.origin,a=r.toString();return{currentInput:a,currentUrl:a,currentInit:Ld(e.currentInit,t,e.signal,i,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}n(Jd,"followRedirect");async function Yr(e,t,r){let o=r.problemCode??"invalid_request",i=r.maxRedirects??xd,a=r.maxResponseBytes??Td,c=r.timeoutMs??Ud,s=r.fetchImpl??fetch,u=r.additionalCrossOriginStrippedHeaders??[],p=r.context,f=new AbortController,w=ii(f,t.signal),U=!1,y=setTimeout(()=>{U=!0,f.abort()},c),P=e,k=Nd(e,t,f.signal),z;try{z=ai(Vr(e),{problemCode:o,validateUrl:r.validateUrl}).toString()}catch(Q){throw kt(p,{event:"outbound_url_blocked",problemCode:o,method:Ke(e,t),host:O(Vr(e)),error:Q}),clearTimeout(y),w?.(),Q}let ze=0;try{for(;;){let Q=await zd(p,s,P,k,o,z,()=>U?`timeout_after_${c}ms`:void 0),E=Dd(Q,z);if(E!==void 0)try{let D=Jd({currentInput:P,currentInit:k,currentUrl:z,redirectUrl:E,redirects:ze,maxRedirects:i,problemCode:o,validateUrl:r.validateUrl,signal:f.signal,additionalCrossOriginStrippedHeaders:u});P=D.currentInput,k=D.currentInit,z=D.currentUrl,ze=D.redirects;continue}catch(D){throw kt(p,{event:"outbound_redirect_blocked",problemCode:o,method:Ke(P,k),host:O(z),error:D,extra:{redirects:ze,maxRedirects:i,redirectTargetHost:O(E)}}),D}try{return Md(Q,await qd(Q,a,o))}catch(D){throw kt(p,{event:"outbound_response_size_exceeded",problemCode:o,method:Ke(P,k),host:O(z),error:D,extra:{maxResponseBytes:a,status:Q.status}}),D}}}finally{clearTimeout(y),w?.()}}n(Yr,"runSafeOutboundExchange");async function xt(e,t,r){let o=await Yr(e,t,r);try{return{response:o,json:await o.clone().json()}}catch(i){throw kt(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:Ke(e,t),host:O(Vr(e)),error:i,extra:{status:o.status,contentType:o.headers.get("content-type")??void 0}}),new h({message:"Outbound JSON response could not be parsed.",extensionMembers:{[g]:r.problemCode??"invalid_request"}},{cause:i})}}n(xt,"runSafeOutboundJsonExchange");function si(e,t={},r={}){return Yr(e,t,{...r,validateUrl:lt})}n(si,"fetchConfiguredOutbound");function ci(e,t={},r={}){return xt(e,t,{...r,validateUrl:lt})}n(ci,"fetchConfiguredOutboundJson");function sr(e,t={},r={}){return xt(e,t,{...r,validateUrl:Uo})}n(sr,"fetchIdentityProviderJson");function di(e,t={},r={}){return xt(e,t,{...r,validateUrl:Wt})}n(di,"fetchCimdClientMetadataJson");function ui(e,t={},r={}){return xt(e,t,{...r,validateUrl:pt})}n(ui,"fetchCimdClientJwksJson");K();import{errors as gi,jwtVerify as yi,SignJWT as _i}from"jose";var $="zuplo-mcp-gateway",V=$,Y="HS256";import{base64url as Gd}from"jose";var Fd=new TextEncoder,$d="MCP gateway could not initialize secure key material.",Zd=32,li=new Map,pi=new Map,Kd;function Wd(){return Kd??Hn.instance.authPrivateKey}n(Wd,"readAuthPrivateKey");function mi(e){return new ee($d,e===void 0?void 0:{cause:e})}n(mi,"createGeneratedKeyMaterialError");function fi(e,t){let r=Gd.decode(t);if(r.byteLength!==Zd)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}n(fi,"decodeJwkKeyField");function Vd(e){let t=Wd();if(!t)throw mi();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=fi("d",r.d);fi("x",r.x);let i=Fd.encode(`zuplo-mcp-gateway:${e}:Ed25519:`),a=new Uint8Array(i.byteLength+o.byteLength);return a.set(i),a.set(o,i.byteLength),a}catch(r){throw mi(r)}}n(Vd,"decodeGeneratedKeyMaterial");function Yd(e){let t=li.get(e);return t||(t=Vd(e),li.set(e,t)),t}n(Yd,"getMasterKeyMaterial");async function ie(e){let t=pi.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(Yd(e.keyMaterialPurpose));return pi.set(e.purpose,r),r}n(ie,"readCachedDerivedKey");var Xd="SHA-256",Qd=32,eu="zuplo-mcp-gateway:",tu=new TextEncoder,hi=new WeakMap;async function Se(e,t){let r=hi.get(e);r||(r=new Map,hi.set(e,r));let o=r.get(t);if(o)return o;let i=await ru(e,t);return r.set(t,i),i}n(Se,"deriveGatewaySigningKey");async function ru(e,t){let r=G(e),o=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),i=tu.encode(`${eu}${t}`),a=await crypto.subtle.deriveBits({name:"HKDF",hash:Xd,salt:new Uint8Array,info:G(i)},o,Qd*8);return new Uint8Array(a)}n(ru,"hkdfExpand");var wi=900,nu=900,ou=po.extend({id:Mo}),iu=ou.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),Ri=vr.extend({id:Do,purpose:d.literal("browser_connect")}),au=vr.extend({purpose:d.literal("browser_connect")}),su=Ri.extend({exp:d.number().int().positive(),iat:d.number().int().positive().optional()}),bi=wi*1e3;async function Ii(){return ie({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Se(e,"oauth-state"),"derive")})}n(Ii,"getOAuthStateKey");async function Si(){return ie({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:n(e=>Se(e,"browser-connect"),"derive")})}n(Si,"getBrowserConnectKey");async function Ci(e){let t=Math.floor(Date.now()/1e3)+wi;return new _i(e).setProtectedHeader({alg:Y,typ:"JWT"}).setIssuer($).setAudience(V).setIssuedAt().setExpirationTime(t).sign(await Ii())}n(Ci,"signOAuthState");async function cr(e){try{let{payload:t}=await yi(e,await Ii(),{algorithms:[Y],issuer:$,audience:V});return iu.parse(t)}catch(t){throw t instanceof gi.JWTExpired?new h({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new h({message:"OAuth state could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(cr,"verifyOAuthState");async function vi(e){let t=Math.floor(Date.now()/1e3)+nu,r=au.parse(e),o=Ri.parse({...r,id:Ho()});return new _i(o).setProtectedHeader({alg:Y,typ:"JWT"}).setIssuer($).setAudience(V).setIssuedAt().setExpirationTime(t).sign(await Si())}n(vi,"signBrowserConnectTicket");async function Ai(e){try{let{payload:t}=await yi(e,await Si(),{algorithms:[Y],issuer:$,audience:V});return su.parse(t)}catch(t){throw t instanceof gi.JWTExpired?new h({message:"Browser connect ticket has expired",extensionMembers:{[g]:"oauth_state_expired"}},{cause:t}):new h({message:"Browser connect ticket could not be verified",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:t})}}n(Ai,"verifyBrowserConnectTicket");async function ki(e){if((await b().consumeBrowserConnectTicket({id:e.id,expiresAt:I(new Date(e.exp*1e3)),now:I(new Date)})).kind==="consumed")throw new h({message:"Browser connect ticket has already been used",extensionMembers:{[g]:"oauth_state_reused"}})}n(ki,"consumeBrowserConnectTicket");function cu(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(cu,"buildConnectRequiredMessage");async function du(e){let t=q(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 vi({...dt(e),purpose:"browser_connect"})),r.toString()}n(du,"buildGatewayBrowserTicketUrl");function uu(e){return H().actionPath(`/auth/connections/${encodeURIComponent(e)}/connect`)}n(uu,"buildGatewayConnectPath");async function Xr(e){return du({...e,path:uu(e.upstreamServerId),redirect:!0})}n(Xr,"buildGatewayConnectUrl");async function dr(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 Xr(t),message:cu(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}n(dr,"buildRedirectConnectRequiredResponse");function xi(e){return lu({...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(xi,"buildAdminConnectRequiredResponse");function lu(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(lu,"buildAdminSetupRequiredResponse");var Ti=12;async function Ui(e){let t=await crypto.subtle.digest("SHA-256",G(new TextEncoder().encode(e)));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}n(Ui,"sha256Hex");async function We(e){if(e)return(await Ui(e)).slice(0,Ti)}n(We,"fingerprintSecret");async function Ve(e){let t=JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId]);return(await Ui(t)).slice(0,Ti)}n(Ve,"fingerprintConnectionIdentity");function Tt(e){return e?e.status!=="active"?"inactive":e.encryptedAccessToken?e.expiresAt&&new Date(e.expiresAt).getTime()<=Date.now()?"expired":"usable":"no_access_token":"no_connection"}n(Tt,"describeAccessTokenState");K();var Pi=new Set(["client_id","code_challenge","code_challenge_method","display","login_hint","nonce","prompt","redirect_uri","response_mode","response_type","state"]);function pu(e,t){return e&&e.length>0?e.join(t):void 0}n(pu,"joinOAuthScopes");function mu(e){if(e?.authorization_endpoint===void 0)return e;let t=new URL(e.authorization_endpoint);for(let r of Pi)t.searchParams.delete(r);return{...e,authorization_endpoint:t.toString()}}n(mu,"sanitizeAuthorizationServerMetadata");function Ei(e){let t=mu(e.authorizationServerMetadata);return t===e.authorizationServerMetadata?e:{...e,authorizationServerMetadata:t}}n(Ei,"sanitizeOAuthDiscoveryState");function Oi(e){let t=new URL(e);for(let r of Pi){let o=t.searchParams.getAll(r);o.length<=1||(t.searchParams.delete(r),t.searchParams.set(r,o.at(-1)??""))}return t}n(Oi,"dedupeSingletonAuthorizationRequestParams");function ur(e){let t=new URL(e);return W(t)&&Vn(t.hostname)!=="localhost"&&(t.hostname="localhost"),t}n(ur,"normalizeLoopbackOAuthRedirectUri");function qi(e){return pu(e.state?.resourceMetadata?.scopes_supported,e.delimiter)}n(qi,"readProtectedResourceMetadataScope");function fu(e){return`Zuplo MCP Gateway - ${e}`}n(fu,"buildGatewayOAuthClientName");function hu(e,t){return e&&e.length>0?e.join(t):void 0}n(hu,"joinOAuthScopeList");function gu(e){if(e.clientRegistration.mode!=="auto")return hu(e.scopes,e.scopeDelimiter)}n(gu,"readPublicClientMetadataScope");function Qr(e){return new URL(H().actionPath(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`),e.origin).toString()}n(Qr,"buildOAuthClientMetadataDocumentUrl");function en(e){let t=Ie(e.upstreamServerId);return{client_name:fu(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(en,"buildGatewayOAuthClientMetadata");function Mi(e,t,r){let o=Ze(t,r),i=gu(o);return{client_id:Qr({origin:e,upstreamServerId:t}),...en({origin:e,upstreamServerId:t,redirectUri:ur(new URL(o.redirectPath,e)).toString(),scope:i})}}n(Mi,"buildOAuthClientMetadataDocument");K();import{base64url as Ce}from"jose";var yu="SHA-256",Ye="AES-GCM",_u=12,rn="zuplo-secret",nn=1,Di="generated:auth_private_key:token-encryption",wu=d.object({version:d.literal(nn),keyId:d.literal(Di),algorithm:d.literal(Ye),iv:d.string().min(1),ciphertext:d.string().min(1)}).strict();async function tn(){return ie({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:n(async e=>{let t=await crypto.subtle.digest(yu,G(e));return crypto.subtle.importKey("raw",t,{name:Ye},!1,["encrypt","decrypt"])},"derive")})}n(tn,"getEncryptionKey");function ji(e){return G(new TextEncoder().encode(`${rn}:v${e.version}:${e.keyId}`))}n(ji,"getAssociatedData");function Ru(e){return`${rn}:v${e.version}:${Ce.encode(new TextEncoder().encode(JSON.stringify(e)))}`}n(Ru,"encodeEnvelope");function bu(e){let t=`${rn}:v${nn}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),o=new TextDecoder().decode(Ce.decode(r));return wu.parse(JSON.parse(o))}n(bu,"decodeEnvelope");async function me(e){let t=await tn(),r=crypto.getRandomValues(new Uint8Array(_u)),o={version:nn,keyId:Di},i=await crypto.subtle.encrypt({name:Ye,iv:r,additionalData:ji(o)},t,new TextEncoder().encode(e));return Ru({...o,algorithm:Ye,iv:Ce.encode(r),ciphertext:Ce.encode(new Uint8Array(i))})}n(me,"encryptSecret");async function ve(e){let t=bu(e);if(t){let c=await tn(),s=await crypto.subtle.decrypt({name:Ye,iv:G(Ce.decode(t.iv)),additionalData:ji(t)},c,G(Ce.decode(t.ciphertext)));return new TextDecoder().decode(s)}let[r,o]=e.split(".");if(!r||!o)throw new ee("Encrypted payload is malformed");let i=await tn(),a=await crypto.subtle.decrypt({name:Ye,iv:G(Ce.decode(r))},i,G(Ce.decode(o)));return new TextDecoder().decode(a)}n(ve,"decryptSecret");var Iu=d.union([ft,rr]),Su=d.object({authorizationServerUrl:d.url(),resourceMetadataUrl:d.url().optional(),resourceMetadata:er.optional(),authorizationServerMetadata:d.union([mt,tr]).optional()}).passthrough(),Cu="Bearer",vu="__zuplo_refresh_only_upstream_access_token__";function Au(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}n(Au,"splitScopes");function ku(e){return Be.parse(e)}n(ku,"parsePkceCodeVerifier");function xu(e){if(typeof e.expires_in=="number")return I(new Date(Date.now()+e.expires_in*1e3))}n(xu,"readTokenExpiry");async function Tu(e){if(e!==void 0)return me(JSON.stringify(e))}n(Tu,"encryptJson");async function Uu(e,t){if(!e)return;let r=await ve(e);try{return t.parse(JSON.parse(r))}catch(o){throw new h({message:"Stored upstream OAuth JSON state is invalid.",extensionMembers:{[g]:"oauth_state_invalid"}},{cause:o})}}n(Uu,"decryptJson");function Pu(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}n(Pu,"clientInformationAllowsRedirectUri");function Eu(e){return e.clientMetadataUrl===void 0?"redirect_uris"in e.clientInformation:"redirect_uris"in e.clientInformation||e.clientInformation.client_id===e.clientMetadataUrl}n(Eu,"clientInformationMatchesCurrentClientMetadataUrl");function Ou(e){return e.clientMetadataUrl!==void 0&&!("redirect_uris"in e.clientInformation)&&e.clientInformation.client_id===e.clientMetadataUrl}n(Ou,"isUrlBasedClientInformation");function qu(e,t){return t===void 0?e:{...e,scope:t}}n(qu,"applyOAuthClientMetadataScope");function Mu(e,t){return qi({state:e,delimiter:t})}n(Mu,"readResourceMetadataScope");function Du(e,t){return e&&e.length>0?e.join(t):void 0}n(Du,"joinOAuthScopeList");function ju(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw new B(`Manual OAuth registration for upstream "${e.upstreamServerId}" requires clientSecret. Set the env var that backs the client secret or use tokenEndpointAuthMethod "none".`);return ft.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}n(ju,"buildManualOAuthClientInformation");function zu(e,t){let r=Qr({origin:new URL(t).origin,upstreamServerId:e});return Fr(r)?r:void 0}n(zu,"buildClientMetadataUrl");function Hu(e){for(let t of e)if(t!==void 0)return t}n(Hu,"firstDefined");function Bu(e){let t=Ze(e.target.upstreamServerId,e.target.authProfileId),r=Du(t.scopes,t.scopeDelimiter),o=en({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:ju({clientMetadata:o,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let i=zu(e.target.upstreamServerId,e.redirectUri);return i===void 0?{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter}:{clientMetadata:o,configuredScope:r,scopeDelimiter:t.scopeDelimiter,clientMetadataUrl:i}}n(Bu,"buildInitialOAuthClientSetup");function Lu(e,t){if(t===void 0)return Hu([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}n(Lu,"readEncryptedClientInformation");var qe=class{static{n(this,"UpstreamOAuthProvider")}clientMetadataUrl;target;redirectUriValue;returnOrigin;clientMetadataValue;configuredScope;scopeDelimiter;configuredClientInformation;challengeScope;inferredScope;authorizationUrlValue;connection;pendingState;encryptedClientInformation;cachedClientInformation;clientInformationLoaded=!1;cachedDiscoveryState;discoveryStateLoaded=!1;cachedTokens;tokensLoaded=!1;connectionFingerprintValue;usedRefreshTokenFingerprintValue;constructor(t){let r=Bu({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=Lu(t,this.configuredClientInformation)}get authorizationUrl(){return this.authorizationUrlValue}get usedRefreshTokenFingerprint(){return this.usedRefreshTokenFingerprintValue}async connectionFingerprint(){return this.connectionFingerprintValue===void 0&&(this.connectionFingerprintValue=await Ve({owner:this.target.owner,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId})),this.connectionFingerprintValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return qu(this.clientMetadataValue,this.readEffectiveScope())}async state(){let t=await this.createPendingState();return Ci({id:t.id,...dt({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,J()?.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"),!Ou({clientInformation:t,clientMetadataUrl:this.clientMetadataUrl})&&(this.encryptedClientInformation=await Tu(t),await this.syncPendingState(!1)))}async discoveryState(){return this.readCachedDiscoveryState()}applyChallengeScope(t){this.challengeScope=t}async saveDiscoveryState(t){let r=Ei(Su.parse(t));this.cachedDiscoveryState=r,this.discoveryStateLoaded=!0,J()?.info({event:"upstream_oauth_discovery_resolved",upstreamServerId:this.target.upstreamServerId,authorizationServerHost:O(r.authorizationServerUrl),resourceMetadataHost:O(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=Mu(r,this.scopeDelimiter)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=$e.parse(t),o=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0,i=this.connection,a=!r.refresh_token&&!!i?.encryptedRefreshToken,c=r.refresh_token?await me(r.refresh_token):this.connection?.encryptedRefreshToken;this.cachedTokens=r.refresh_token||!this.connection?.encryptedRefreshToken?r:$e.parse({...r,refresh_token:await ve(this.connection.encryptedRefreshToken)}),this.tokensLoaded=!0;let s={id:this.connection?.id??Vt(),ownerMode:this.target.owner.mode,subjectId:o,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await me(r.access_token),encryptedRefreshToken:c,scopes:Au(r.scope??this.readEffectiveScope()),expiresAt:xu(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await b().upsertUpstreamConnection(s),J()?.info({event:"upstream_oauth_tokens_persisted",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,ownerMode:this.target.owner.mode,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.connection.id,hasRefreshToken:!!c,priorStatus:i?.status,priorUpdatedAt:i?.updatedAt,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,newRefreshTokenFingerprint:await We(r.refresh_token),reusedSnapshotRefreshToken:a,scopeCount:s.scopes.length,expiresAt:s.expiresAt},"Upstream OAuth tokens persisted; upstream connection is active")}async redirectToAuthorization(t){let r=Oi(t);this.authorizationUrlValue=r.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:ku(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw new h({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",i=t==="all"||t==="discovery",a=t==="all"||t==="verifier";o&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),i&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.challengeScope=void 0,this.inferredScope=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(a),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:zo(),...dt({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()+bi)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await b().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await Uu(this.encryptedClientInformation,Iu)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&(!Pu(t,this.redirectUriValue)||!Eu({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=rr.parse({client_id:this.clientMetadataUrl})),this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.cachedClientInformation}async readCachedDiscoveryState(){if(this.discoveryStateLoaded)return this.cachedDiscoveryState;this.discoveryStateLoaded=!0}readEffectiveScope(){return this.configuredScope??this.challengeScope??this.inferredScope}async loadStoredTokens(){if(this.tokensLoaded)return this.cachedTokens;if(this.tokensLoaded=!0,!this.connection||this.connection.status!=="active"){J()?.debug({event:"upstream_oauth_tokens_not_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.connection?.id,status:this.connection?.status??"not_connected"},"Upstream OAuth tokens not loaded; connection is not active");return}let t=this.connection.encryptedAccessToken?await ve(this.connection.encryptedAccessToken):void 0,r=this.connection.encryptedRefreshToken?await ve(this.connection.encryptedRefreshToken):void 0;if(!t&&!r)return;let o=J();this.usedRefreshTokenFingerprintValue=o?await We(r):void 0,o?.debug({event:"upstream_oauth_tokens_loaded",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.connection.id,hasAccessToken:!!t,hasRefreshToken:!!r,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue,expiresAt:this.connection.expiresAt},"Upstream OAuth tokens loaded from stored connection");let i=$e.parse({access_token:t??vu,token_type:Cu,refresh_token:r,scope:this.connection.scopes.length>0?this.connection.scopes.join(" "):void 0});return this.cachedTokens=i,i}async persistCredentialInvalidation(t){if(!this.connection)return;let r=this.connection.status,o=this.connection.updatedAt,i={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&&(i.status="reconsent_required",i.encryptedAccessToken=void 0,i.encryptedRefreshToken=void 0,i.scopes=[],i.expiresAt=void 0),i.metadata=this.readStoredOAuthPersistence(this.connection.metadata?.connectedBySubjectId),this.connection=await b().upsertUpstreamConnection(i);let a=J();if(a){let c={event:"upstream_oauth_credentials_invalidated",upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,connectionFingerprint:await this.connectionFingerprint(),connectionId:this.connection.id,clearedTokens:t,priorStatus:r,newStatus:this.connection.status,priorUpdatedAt:o,usedRefreshTokenFingerprint:this.usedRefreshTokenFingerprintValue};t?a.warn(c,"Upstream OAuth credentials invalidated; connection now requires reconsent"):a.debug(c,"Upstream OAuth credential metadata rewritten")}}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!t))return{encryptedClientInformation:this.encryptedClientInformation,connectedBySubjectId:t}}};var Nu=3e4,Ju=256*1024,Gu=2,Fu="does not support dynamic client registration",$u=["Resource server does not implement OAuth 2.0 Protected Resource Metadata","trying to load well-known OAuth protected resource metadata"],Zu=["HTTP 403 Forbidden","Access Denied","permission to access"],Ku=new Set(["access_denied","invalid_client","invalid_grant","invalid_request","invalid_scope","invalid_target","unauthorized_client","unsupported_grant_type"]);function Wu(e){return e instanceof Error&&e.message.includes(Fu)}n(Wu,"isDynamicClientRegistrationUnsupported");function Vu(e){return e instanceof Error&&$u.some(t=>e.message.includes(t))}n(Vu,"isProtectedResourceMetadataUnavailable");function Yu(e){return e instanceof Error&&Zu.some(t=>e.message.includes(t))}n(Yu,"isUpstreamProviderAccessDenied");function Xu(e){return e instanceof A&&Ku.has(e.errorCode)}n(Xu,"isStoredConnectionReconsentError");function Qu(e){if(e.error instanceof h&&e.error.extensionMembers?.[g]!==void 0)return e.error;if(Wu(e.error))return new h({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(Vu(e.error))return new h({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(Yu(e.error))return new h({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(Qu,"mapUpstreamOAuthSetupError");function el(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}n(el,"readOAuthFetchRequest");function tl(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}n(tl,"responseLooksJson");function rl(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(rl,"responseLooksHtml");function nl(e){let t=e.response.statusText?` ${e.response.statusText}`:"",r=e.response.headers.get("content-type")??"text/html";throw new h({message:`The upstream provider returned ${e.response.status}${t} (${r}) from ${e.request.url.toString()} while connecting ${e.upstreamServerId}.`,extensionMembers:{[g]:e.response.status===403?"upstream_provider_access_denied":"upstream_token_exchange_failed",[_e]:e.response.status,[Le]:r,[we]:e.request.url.toString(),[Ne]:e.body}})}n(nl,"throwUpstreamHtmlError");function ol(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(ol,"readUpstreamOAuthErrorBody");function il(e){let{error:t,errorDescription:r}=ol(e.body);e.log?.warn({event:"upstream_oauth_http_error",upstreamServerId:e.upstreamServerId,method:e.request.method??"GET",host:O(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(il,"logUpstreamOAuthHttpError");function Hi(e){return async(t,r)=>{let o=el(t),i=J(),a=Date.now(),c=await si(t,r,{maxRedirects:Gu,maxResponseBytes:Ju,problemCode:"upstream_token_exchange_failed",timeoutMs:Nu}),s=await c.clone().text();if(i?.debug({event:"upstream_oauth_http_request",upstreamServerId:e,method:o.method??"GET",host:O(o.url),path:o.url.pathname,status:c.status,durationMs:Date.now()-a,responseChars:s.length},"Upstream OAuth HTTP request completed"),c.ok||il({log:i,upstreamServerId:e,request:o,response:c,body:s}),!c.ok&&rl(c,s)&&nl({upstreamServerId:e,request:o,response:c,body:s}),!tl(c,s))return c;try{JSON.parse(s)}catch(u){throw new h({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(Hi,"createUpstreamOAuthFetch");function Bi(e){J()?.debug({event:e.phase==="authorize"?"upstream_oauth_authorize_started":"upstream_oauth_token_exchange_started",upstreamServerId:e.upstreamServerId,serverHost:O(e.serverUrl),resourceMetadataHost:O(e.resourceMetadataUrl),hasRequestedScope:e.requestedScope!==void 0},e.phase==="authorize"?"Upstream OAuth authorization flow started":"Upstream OAuth authorization-code exchange started")}n(Bi,"logUpstreamOAuthFlowStarted");function Li(e){let t={event:"upstream_oauth_flow_failed",phase:e.phase,upstreamServerId:e.upstreamServerId},r=O(e.serverUrl);r!==void 0&&(t.serverHost=r);let o=e.error instanceof h?e.error.extensionMembers?.[g]:void 0;typeof o=="string"&&(t.code=o),N(t,"error",e.error),J()?.warn(t,"Upstream OAuth flow failed before a connection was established")}n(Li,"logUpstreamOAuthFlowFailed");async function Ni(e,t){e.applyChallengeScope(t.requestedScope),Bi({phase:"authorize",...t});try{let r={serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Hi(t.upstreamServerId)};return t.requestedScope!==void 0&&(r.scope=t.requestedScope),await Gr(e,r)}catch(r){Li({phase:"authorize",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:r});let o=Qu({upstreamServerId:t.upstreamServerId,resourceMetadataUrl:t.resourceMetadataUrl,error:r});throw o!==void 0?o:r}}n(Ni,"runUpstreamOAuth");async function al(e,t){e.applyChallengeScope(t.requestedScope),Bi({phase:"token_exchange",...t});let r={serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:Hi(t.upstreamServerId)};t.requestedScope!==void 0&&(r.scope=t.requestedScope);try{return await Gr(e,r)}catch(o){throw Li({phase:"token_exchange",upstreamServerId:t.upstreamServerId,serverUrl:t.serverUrl,error:o}),o}}n(al,"exchangeUpstreamAuthorizationCode");async function Ji(e,t){let r=await Ni(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?new h({message:`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new h({message:`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Ji,"requireUpstreamAuthorizationRedirect");async function Gi(e){let t=Tt(e.connection),r=!!e.forceRefresh,o=!r&&t==="usable",i=J(),a=i?await Ve({owner:e.target.owner,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId}):void 0;if(i?.debug({event:"upstream_oauth_refresh_decision",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,ownerMode:e.target.owner.mode,connectionFingerprint:a,connectionId:e.connection?.id,accessTokenState:t,forceRefresh:r,willRefresh:!o,expiresAt:e.connection?.expiresAt,connectionUpdatedAt:e.connection?.updatedAt},o?"Reusing stored upstream access token":"Refreshing upstream credential"),o)return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let c;try{c=await Ni(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl,...e.requestedScope===void 0?{}:{requestedScope:e.requestedScope}})}catch(s){if(e.connection===void 0||!Xu(s))throw s;return i?.warn({event:"upstream_oauth_connection_reconsent_required",upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,oauthError:s.errorCode,connectionFingerprint:a,connectionId:e.connection.id,rejectedRefreshTokenFingerprint:e.provider.usedRefreshTokenFingerprint,connectionUpdatedAt:e.connection.updatedAt,connectionExpiresAt:e.connection.expiresAt},"Stored upstream OAuth connection was rejected by the upstream provider"),await e.provider.invalidateCredentials("all"),{kind:"connect_required",payload:await zi({requestUrl:e.target.request.url,requestHeaders:e.target.request.headers,connection:e.connection,owner:e.target.owner,initiatedBySubjectId:e.target.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,upstreamDisplayName:e.upstreamDisplayName,operationId:e.target.operationId,...e.target.returnTo===void 0?{}:{returnTo:e.target.returnTo}})}}if(c==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(c!=="REDIRECT")throw new h({message:`Unexpected OAuth result for ${e.target.upstreamServerId}: ${c}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}});if(!e.provider.authorizationUrl)throw new h({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 zi({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(Gi,"authorizeUpstreamOAuthSession");async function sl(e){let t=await cr(e.stateToken),r=await b().consumeUpstreamOAuthState({id:t.id,now:I(new Date)}),o=cl(r);return dl({storedState:o,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),ul(o),o}n(sl,"consumeStoredCallbackState");function cl(e){switch(e.kind){case"consumed":throw new h({message:"OAuth state has already been used",extensionMembers:{[g]:"oauth_state_reused"}});case"missing":throw new h({message:"OAuth state is missing or expired",extensionMembers:{[g]:"oauth_state_expired"}});case"available":return e.record}}n(cl,"readConsumedCallbackState");function dl(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 h({message:"OAuth callback did not match the initiating request",extensionMembers:{[g]:"oauth_callback_mismatch"}})}n(dl,"assertStoredCallbackStateMatches");function ul(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw new h({message:"OAuth state has expired",extensionMembers:{[g]:"oauth_state_expired"}})}n(ul,"assertStoredCallbackStateFresh");async function zi(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),xi(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),dr(t)}n(zi,"buildOAuthConnectRequiredResponse");async function Fi(e){let t=await sl({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Ft(t),[o]=await b().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),i={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&&(i.connection=o);let a=new qe(i),c=await al(a,{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 h({message:`Unexpected OAuth result for ${e.upstreamServerId}: ${c}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}}):new h({message:`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`,extensionMembers:{[g]:"upstream_token_exchange_failed"}})}n(Fi,"finishUpstreamOAuthCallback");K();import{importPKCS8 as ll,SignJWT as pl}from"jose";var Zi=1e4,Ki=64*1024,Wi=2,ml=300,oe=d.string().min(1),fl=d.object({access_token:oe,issued_token_type:d.literal(kr),token_type:d.string().optional(),expires_in:d.number().int().positive().optional(),scope:oe.optional()}).passthrough(),hl=d.object({id_token:oe,token_type:oe.optional(),expires_in:d.number().int().positive().optional(),refresh_token:oe.optional(),scope:oe.optional()}).passthrough(),gl=d.object({access_token:oe,token_type:oe,expires_in:d.number().int().positive().optional(),scope:oe.optional(),resource:oe.optional(),refresh_token:oe.optional()}).passthrough();function $i(e){return encodeURIComponent(e).replace(/%20/g,"+")}n($i,"formEncodeClientCredential");function yl(e){return e.replaceAll("\\n",`
26
26
  `)}n(yl,"normalizePem");async function _l(e){let t=e.clientAuth.algorithm??"RS256",r=e.clientAuth.expiresInSeconds??ml,o=await ll(yl(e.clientAuth.privateKeyPem),t),i={alg:t,typ:"JWT",...e.clientAuth.keyId===void 0?{}:{kid:e.clientAuth.keyId}};return new pl({jti:crypto.randomUUID()}).setProtectedHeader(i).setIssuer(e.clientAuth.clientId).setSubject(e.clientAuth.clientId).setAudience(e.clientAuth.audience??e.tokenUrl).setIssuedAt().setExpirationTime(`${r}s`).sign(o)}n(_l,"createPrivateKeyJwtClientAssertion");async function wl(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=$i(e.clientAuth.clientId),r=$i(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",Zt),e.form.set("client_assertion",await _l({clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}));return}}n(wl,"appendClientAuthentication");async function on(e){let t={"Content-Type":"application/x-www-form-urlencoded"};return await wl({form:e.form,headers:t,clientAuth:e.clientAuth,tokenUrl:e.tokenUrl}),{method:"POST",headers:t,body:e.form.toString()}}n(on,"buildFormRequest");function Vi(e){return(t,r)=>sr(t,r,{context:e,maxRedirects:Wi,maxResponseBytes:Ki,problemCode:"upstream_token_exchange_failed",timeoutMs:Zi})}n(Vi,"defaultIdpFetchJson");function Rl(e){return(t,r)=>ci(t,r,{context:e,maxRedirects:Wi,maxResponseBytes:Ki,problemCode:"upstream_token_exchange_failed",timeoutMs:Zi})}n(Rl,"defaultResourceAsFetchJson");function lr(e){let t={[g]:e.code,[we]:e.tokenUrl};return e.response!==void 0&&(t[_e]=e.response.status),new h({message:e.message,extensionMembers:t},e.cause===void 0?void 0:{cause:e.cause})}n(lr,"runtimeError");function an(e){if(!e.response.ok)throw lr({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(an,"assertTokenEndpointSucceeded");function bl(e){let t=hl.safeParse(e.json);if(!t.success)throw lr({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(bl,"parseIdpRefreshTokenResponse");function Il(e){let t=fl.safeParse(e.json);if(!t.success)throw lr({code:"upstream_token_response_invalid",message:"IdP token exchange returned an invalid ID-JAG response.",tokenUrl:e.tokenUrl,response:e.response,cause:t.error});let r={assertion:t.data.access_token};return t.data.expires_in!==void 0&&(r.expiresIn=t.data.expires_in),t.data.scope!==void 0&&(r.scope=t.data.scope),r}n(Il,"parseIdJagTokenExchangeResponse");function Sl(e){let t=gl.safeParse(e.json);if(!t.success)throw lr({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(Sl,"parseAccessTokenResponse");async function Yi(e){let t=new URLSearchParams({grant_type:$t,requested_token_type:kr,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??Vi(e.context),{response:o,json:i}=await r(e.idp.tokenUrl,await on({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return an({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_token_exchange"}),Il({json:i,response:o,tokenUrl:e.idp.tokenUrl})}n(Yi,"requestIdJag");async function Xi(e){let t=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken}),r=e.fetchJson??Vi(e.context),{response:o,json:i}=await r(e.idp.tokenUrl,await on({form:t,clientAuth:e.clientAuth,tokenUrl:e.idp.tokenUrl}));return an({response:o,tokenUrl:e.idp.tokenUrl,stage:"idp_refresh_token"}),bl({json:i,response:o,tokenUrl:e.idp.tokenUrl})}n(Xi,"refreshIdpSubjectToken");async function Qi(e){let t=new URLSearchParams({grant_type:be,assertion:e.assertion});e.resource!==void 0&&t.set("resource",e.resource),e.scope!==void 0&&t.set("scope",e.scope);let r=e.fetchJson??Rl(e.context),{response:o,json:i}=await r(e.resourceAs.tokenUrl,await on({form:t,clientAuth:e.clientAuth,tokenUrl:e.resourceAs.tokenUrl}));return an({response:o,tokenUrl:e.resourceAs.tokenUrl,stage:"resource_as_jwt_bearer"}),Sl({json:i,response:o,tokenUrl:e.resourceAs.tokenUrl})}n(Qi,"exchangeIdJagForAccessToken");function Cl(e){return Tt(e)==="usable"}n(Cl,"hasUsableAccessToken");function vl(e){if(e.tokenType.toLowerCase()!=="bearer")throw new h({message:"Upstream Resource AS returned a token type the MCP gateway cannot send as a bearer token.",extensionMembers:{[g]:"upstream_token_response_invalid"}})}n(vl,"assertBearerToken");function ea(e,t){if(t===Fe)return!1;let r=e?.metadata?.idpSubjectTokenExpiresAt;return r!==void 0&&new Date(r).getTime()<=Date.now()}n(ea,"hasExpiredSubjectToken");async function Al(e){let t=await ve(e.encryptedSubjectToken);if(e.subjectTokenType!==Fe)return{connection:e.connection,subjectToken:t,subjectTokenType:e.subjectTokenType};let r=await Xi({idp:e.idp,refreshToken:t,clientAuth:e.clientAuth,context:e.context});if(r.refreshToken===void 0)return{connection:e.connection,subjectToken:r.idToken,subjectTokenType:ut};let o=await b().upsertUpstreamConnection({id:e.connection.id,ownerMode:e.connection.ownerMode,subjectId:e.connection.subjectId,upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,status:"active",encryptedAccessToken:e.connection.encryptedAccessToken,encryptedRefreshToken:e.connection.encryptedRefreshToken,scopes:e.connection.scopes,expiresAt:e.connection.expiresAt,metadata:{...e.connection.metadata??{},encryptedIdpSubjectToken:await me(r.refreshToken),idpSubjectTokenType:Fe,idpSubjectTokenExpiresAt:void 0}});return J()?.info({event:"upstream_id_jag_subject_token_rotated",upstreamServerId:e.connection.upstreamServerId,authProfileId:e.connection.authProfileId,connectionFingerprint:e.connectionFingerprint,connectionId:o.id,priorStatus:e.connection.status,priorUpdatedAt:e.connection.updatedAt,usedSubjectRefreshTokenFingerprint:await We(t),newSubjectRefreshTokenFingerprint:await We(r.refreshToken)},"Upstream ID-JAG IdP subject refresh token rotated and persisted"),{connection:o,subjectToken:r.idToken,subjectTokenType:ut}}n(Al,"resolveIdJagSubjectToken");async function ta(e){let t="preloadedConnection"in e?e.preloadedConnection:(await b().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0],r=Tt(t),o=!!e.forceRefresh,i=!o&&r==="usable",a=J(),c=a?await Ve({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}):void 0;if(a?.debug({event:"upstream_id_jag_auth_decision",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,ownerMode:e.owner.mode,connectionFingerprint:c,connectionId:t?.id,accessTokenState:r,forceRefresh:o,willMint:!i,expiresAt:t?.expiresAt,connectionUpdatedAt:t?.updatedAt},i?"Reusing stored upstream ID-JAG access token":"Minting upstream ID-JAG access token"),!e.forceRefresh&&Cl(t))return{kind:"authorized",credential:{type:"bearer_token",token:await ve(t.encryptedAccessToken)}};let s=t?.metadata?.encryptedIdpSubjectToken,u=t?.metadata?.idpSubjectTokenType;if(t?.status!=="active"||s===void 0||u===void 0||ea(t,u))return a?.debug({event:"upstream_id_jag_connect_required",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:c,connectionId:t?.id,status:t?.status??"not_connected",hasSubjectToken:s!==void 0,subjectTokenType:u,subjectTokenExpired:u!==void 0&&ea(t,u)},"Upstream ID-JAG requires an admin subject-token binding"),{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 p=Ie(e.upstreamServerId),f=oi(e.upstreamServerId,e.authProfileId),w=f.resourceAs.resource??p.transport.baseUrl,U=e.requestedScope??(f.scopes.length===0?void 0:f.scopes.join(f.scopeDelimiter)),y=await Al({connection:t,connectionFingerprint:c,encryptedSubjectToken:s,subjectTokenType:u,idp:{tokenUrl:f.idp.tokenUrl},clientAuth:f.idp.clientAuth,context:e.context}),P=await Yi({idp:{tokenUrl:f.idp.tokenUrl},subjectToken:y.subjectToken,subjectTokenType:y.subjectTokenType,audience:f.resourceAs.audience,resource:w,scope:U,clientAuth:f.idp.clientAuth,context:e.context}),k=P.scope??U,z=await Qi({resourceAs:{tokenUrl:f.resourceAs.tokenUrl},assertion:P.assertion,resource:w,scope:k,clientAuth:f.resourceAs.clientAuth,context:e.context});if(vl(z),t!==void 0){let Q=(z.scope??k)?.split(/[,\s]+/).filter(Boolean)??[],E=z.expiresIn===void 0?void 0:I(new Date(Date.now()+z.expiresIn*1e3)),D=await b().upsertUpstreamConnection({id:y.connection.id,ownerMode:y.connection.ownerMode,subjectId:y.connection.subjectId,upstreamServerId:y.connection.upstreamServerId,authProfileId:y.connection.authProfileId,status:"active",encryptedAccessToken:await me(z.accessToken),encryptedRefreshToken:y.connection.encryptedRefreshToken,scopes:Q,expiresAt:E,metadata:y.connection.metadata});a?.info({event:"upstream_id_jag_access_token_persisted",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,connectionFingerprint:c,connectionId:D.id,priorStatus:y.connection.status,priorUpdatedAt:y.connection.updatedAt,scopeCount:Q.length,expiresAt:E},"Upstream ID-JAG access token persisted; connection is active")}return{kind:"authorized",credential:{type:"bearer_token",token:z.accessToken}}}n(ta,"authorizeUpstreamIdJagRequest");function kl(e){return ur(new URL(e.callbackPath,q(e.requestUrl,e.requestHeaders))).toString()}n(kl,"buildGatewayOAuthRedirectUri");async function ra(e){let t=Ie(e.upstreamServerId),r=Ze(e.upstreamServerId,e.authProfileId),o=kl({callbackPath:r.redirectPath,requestUrl:e.request.url,requestHeaders:e.request.headers}),i="preloadedConnection"in e?e.preloadedConnection:(await b().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:i,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,operationId:e.operationId,returnTo:e.returnTo},redirectUri:o,returnOrigin:q(e.request.url,e.request.headers)}}}n(ra,"prepareUpstreamOAuthRequest");async function na(e){let t=await ra(e),r=new qe({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return Ji(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}n(na,"startUpstreamConnect");async function oa(e){let t=await ra(e),r=new qe({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return Gi({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(oa,"authorizeUpstreamRequest");async function Xe(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return oa({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 ta({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 ee(`Unsupported upstream auth route context ${JSON.stringify(r)}.`)}n(Xe,"resolveUpstreamCredentialForRoute");async function ia(e){if(e.connectRequest.authMode==="id-jag")throw new ee(`Upstream server ${e.connectRequest.upstreamServerId} uses XAA / ID-JAG and does not support browser OAuth connection flows.`);let t=await na({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(ia,"startUpstreamConnectForRequest");async function aa(e){let r=(await cr(e.callbackRequest.state)).authProfileId;if(ir({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r}).mode==="id-jag")throw new ee(`Upstream server ${e.callbackRequest.upstreamServerId} uses XAA / ID-JAG and does not support OAuth callbacks.`);return Fi({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:Ie(e.callbackRequest.upstreamServerId)})}n(aa,"finishUpstreamCallbackForRequest");function xl(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(xl,"buildRouteAuthBaseFromConnection");function sa(e){return{upstreamServerId:e.connection.id,operationId:e.operationId,authProfileId:mo(e.connection.id,e.connection.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.connection.authMode,ownerMode:e.connection.ownerMode}}n(sa,"buildRouteAuthBaseFromPolicyOptions");function pr(e,t){let o=te().byOperationId.get(t);if(!o)throw new B(`Unknown MCP route "${t}". Ensure routes.oas.json declares this operationId before starting an upstream connection flow.`);if(o.connection===void 0)throw new B(`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 B(`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 xl({connection:o.connection,operationId:t})}n(pr,"resolveRouteAuthBase");function sn(e,t){switch(e){case"user":return Je(t);case"shared":return lo()}}n(sn,"buildOwnerForSubject");function Qe(e,t){switch(e.authMode){case"shared-oauth":return{...e,authMode:"shared-oauth",ownerMode:"shared",owner:sn("shared",t),initiatedBySubjectId:t};case"user-oauth":return{...e,authMode:"user-oauth",ownerMode:"user",owner:sn("user",t),initiatedBySubjectId:t};case"id-jag":return{...e,authMode:"id-jag",ownerMode:"user",owner:sn("user",t),initiatedBySubjectId:t}}}n(Qe,"resolveRouteAuthForSubject");var Tl=st.InvalidRequest,Ul=new Set(["connection","keep-alive","proxy-authenticate","te","trailer","transfer-encoding","upgrade"]);function Pl(e,t){return{credentialType:e.type,forceRefresh:t}}n(Pl,"buildCredentialResolvedAttributes");function El(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required"}}n(El,"connectRequiredReasonCode");function ca(e){v(e.context,{eventType:S.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:Pl(e.credential,e.forceRefresh===!0)})}n(ca,"emitCredentialResolvedAnalyticsEvent");function da(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:El(e.payload.state),reasonClass:"auth",attributes:t})}n(da,"emitCredentialMissingAnalyticsEvents");function Ol(e){let t=e.route.raw();return Nt.parse(t?.operationId)}n(Ol,"readOperationId");async function ql(e,t,r,o){let i=await Xe({request:e,context:o,routeAuth:t});if(i.kind==="connect_required")return da({context:o,payload:i.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:i.payload};let a=i.credential;if(ca({context:o,credential:a,routeBinding:t}),a.type==="bearer_token")return{kind:"headers",headers:[["authorization",`Bearer ${a.token}`]]};let c=await a.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(ql,"buildCredentialHeaders");var Ml=new Set(["authorization","cookie","cookie2"]);function Dl(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(Dl,"readJsonRequestMethod");function jl(e){let t=e.headers.get("content-type")??"";return/\bapplication\/(?:[\w.+-]+\+)?json\b/i.test(t)}n(jl,"isJsonResponse");function cn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}n(cn,"isRecord");function zl(e){return Array.isArray(e)&&e.length>0}n(zl,"hasIconList");function Hl(e){if(e.connection.serverInfo?.icons!==void 0&&e.connection.serverInfo.icons.length>0)return e.connection.serverInfo.icons;try{let t=or(no(e.context.route.handler));return t===void 0?void 0:[t]}catch{return}}n(Hl,"readFallbackServerIcons");function Bl(e){if(!cn(e.body))return e.body;let t=e.body.result;if(!cn(t))return e.body;let r=t.serverInfo;return!cn(r)||zl(r.icons)?e.body:{...e.body,result:{...t,serverInfo:{...r,icons:e.icons}}}}n(Bl,"addMissingServerIcons");function Ll(e,t){let r=new Headers(e.headers);for(let o of Ml)r.delete(o);for(let[o,i]of t)r.set(o,i);return new Ln(e,{headers:r})}n(Ll,"applyUpstreamHeaders");function Nl(e){let t=new Headers(e.headers);for(let r of Ul)t.delete(r);return t}n(Nl,"buildProxyHeaders");async function Jl(e){if(!(e.method==="GET"||e.method==="HEAD"))return e.clone().arrayBuffer()}n(Jl,"readRetryBody");function ua(e,t){let r=t.authUrl===void 0?void 0:Lo({message:t.message,elicitationId:["connect",t.operationId,t.upstreamServerId,t.authProfileId].join(":"),url:t.authUrl});return Response.json(Xt({id:Bo(e),error:{code:r?.code??Tl,message:t.message,data:{...r?.data??{},connectRequired:t}}}))}n(ua,"connectRequiredJsonRpcResponse");async function Gl(e){let{scope:t}=Qo(e.upstreamResponse),r=await Xe({request:e.request,context:e.context,routeAuth:e.routeAuth,forceRefresh:!0,requestedScope:t});if(r.kind==="connect_required")return da({context:e.context,payload:r.payload,routeBinding:e.routeAuth,forceRefresh:!0}),{kind:"connect_required",payload:r.payload};let o=new Headers(e.headers),i=r.credential;if(ca({context:e.context,credential:i,routeBinding:e.routeAuth,forceRefresh:!0}),i.type==="bearer_token")return o.set("authorization",`Bearer ${i.token}`),{kind:"headers",headers:o};let a=await i.provider.tokens();return a?(o.set("authorization",`${a.token_type??"Bearer"} ${a.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(Gl,"applyRefreshedCredentialHeaders");function Fl(e){e.context.addResponseSendingHook(async(t,r)=>{if(t.status!==401)return t;let o=await Gl({request:e.request,context:e.context,headers:Nl(r),routeAuth:e.routeAuth,upstreamResponse:t});if(o.kind==="connect_required")return ua(e.requestBody,o.payload);if(o.kind==="response")return o.response;let i=oo({handler:e.context.route.handler,request:r,body:e.requestBody,headers:o.headers});return jt.fetch(i.url,i.init)})}n(Fl,"installUpstreamAuthRetryHook");function $l(e){if(Dl(e.requestBody)!=="initialize")return;let t=Hl({connection:e.connection,context:e.context});t===void 0||t.length===0||e.context.addResponseSendingHook(async r=>{if(!jl(r))return r;let o;try{o=await r.clone().json()}catch{return r}let i=Bl({body:o,icons:t});if(i===o)return r;let a=new Headers(r.headers);return a.delete("content-length"),new Response(JSON.stringify(i),{status:r.status,statusText:r.statusText,headers:a})})}n($l,"installInitializeIconHook");async function dn(e,t,r){let o=Ol(t),i=await Jl(e),a=sa({connection:r,operationId:o}),c=Te(e.user,e.url,e.headers);t.log.setLogProperties?.({requestId:t.requestId}),wo(t,c);let s=Qe(a,c.subjectId),u=await ql(e,s,r,t);if(!(u instanceof Response)&&u.kind==="connect_required")return ua(i,u.payload);if(u instanceof Response)return u;let p=Ll(e,u.headers);return Fl({request:p,context:t,requestBody:i,routeAuth:s}),$l({context:t,requestBody:i,connection:r}),p}n(dn,"mcpTokenExchangePolicy");var un=class extends zt{static{n(this,"McpTokenExchangeInboundPolicy")}constructor(t,r){let o=fo(t,r);super(o,r)}async handler(t,r){return Z("policy.inbound.mcp-token-exchange"),dn(t,r,this.options)}};K();var la=Symbol("Html");function Zl(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}n(Zl,"escapeHtml");function Kl(e){return e===null||typeof e!="object"?!1:e[la]===!0}n(Kl,"isHtml");function pa(e){return e==null||e===!1?"":Array.isArray(e)?e.map(pa).join(""):Kl(e)?e.value:Zl(String(e))}n(pa,"renderValue");function fe(e){return{[la]:!0,value:e}}n(fe,"trustedHtml");var re=fe("");function C(e,...t){let r=e[0]??"";for(let o=0;o<t.length;o+=1)r+=pa(t[o]),r+=e[o+1]??"";return fe(r)}n(C,"html");function et(e){return e.value}n(et,"renderHtml");function ma(e){return C`<p class="card__description">${e.detail}</p>${e.guidance} ${e.technicalDetails} ${e.action}`}n(ma,"renderBrowserErrorPage");var tt=fe('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;justify-content:center;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;min-height:40px;padding:8px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.reconnect-action{align-items:center;margin-right:auto;display:inline-flex;position:relative}.reconnect-button{gap:7px}.tooltip{width:16px;height:16px;color:var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);cursor:help;border:1.5px solid;border-radius:50%;justify-content:center;align-items:center;font-size:10.5px;font-weight:700;line-height:1;display:inline-flex;position:relative}.tooltip:after{content:attr(aria-label);z-index:10;border-radius:var(--radius-sm);background:var(--accent);width:280px;max-width:min(280px,100vw - 48px);color:var(--accent-text);box-shadow:var(--shadow);text-align:left;white-space:normal;opacity:0;pointer-events:none;padding:12px 14px;font-size:13px;font-weight:600;line-height:1.45;transition:opacity .12s;position:absolute;bottom:calc(100% + 12px);left:50%;transform:translate(-50%)}.tooltip:before{content:"";z-index:11;border-left:7px solid #0000;border-right:7px solid #0000;border-top:8px solid var(--accent);opacity:0;pointer-events:none;transition:opacity .12s;position:absolute;bottom:calc(100% + 5px);left:50%;transform:translate(-50%)}.tooltip:hover:after,.tooltip:hover:before,.tooltip:focus-visible:after,.tooltip:focus-visible:before{opacity:1}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}.reconnect-action{justify-content:center;width:100%;margin-right:0}.reconnect-action .button{flex:1}.tooltip:after{left:auto;right:0;transform:none}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function rt(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
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(rt,"renderShell");var Wl="text/html; charset=utf-8";function nt(e){try{return new URL(e).host}catch{return""}}n(nt,"safeHostFromUrl");function ae(e){let t=Yl(e.kind??"authorization_failed"),r=Vl(e);return new Response(et(rt({title:e.title??t.title,iconHref:"",styles:tt,headerIcon:re,heading:e.title??t.title,subhead:"",body:ma({detail:e.detail,guidance:C`<p class="card__description">${t.guidance}</p>`,technicalDetails:rp({diagnostic:r,upstreamHtml:e.upstreamHtml}),action:ep(e.action)}),footer:""})),{status:e.status??400,headers:{"content-type":Wl,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}n(ae,"browserErrorPageResponse");function Vl(e){let t=e.diagnostic?.code??e.code??"unknown";return{code:t,stage:e.diagnostic?.stage??Xl(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??Ql(t),underlyingError:e.diagnostic?.underlyingError??e.developerDetail}}n(Vl,"buildBrowserErrorDiagnostic");function Yl(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(Yl,"readBrowserErrorPagePresentation");function Xl(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(Xl,"readBrowserErrorStage");function Ql(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(Ql,"readBrowserErrorSuggestedFix");function ep(e){return e===void 0?re:C`<a class="button button--primary button--block" href="${e.href}">${e.label}</a>`}n(ep,"renderAction");function tp(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(`