UNPKG

decocms

Version:

Deco CMS — Self-hostable MCP Gateway for managing AI connections and tools

2 lines (1 loc) • 7.69 kB
import{d as V,a as N,e as H,b as z}from"./auth-C82OPjUx.js";import{bJ as M}from"./index-ztdGKvBm.js";function D(){return window.location.origin}function C(){try{const e=window.location.hostname;return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="::1"}catch{return!1}}const R="mcp:oauth:callback:",J=1e3,K=10*6e4,v=15e3;class W{_clientMetadata;_redirectUrl;_windowMode;_state=null;_codeVerifier=null;_clientInfo=null;_tokens=null;constructor(t){this._redirectUrl=t.callbackUrl??`${D()}/oauth/callback`,this._windowMode=t.windowMode??"popup";const n=t.scope?Array.isArray(t.scope)?t.scope.join(" "):t.scope:void 0;this._clientMetadata={redirect_uris:[this._redirectUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:t.clientName??"@decocms/studio MCP client",...n&&{scope:n}}}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}state(){return this._state||(this._state=crypto.randomUUID()),this._state}getStoredState(){return this._state}clientInformation(){return this._clientInfo??void 0}saveClientInformation(t){this._clientInfo=t}tokens(){return this._tokens??void 0}saveTokens(t){this._tokens=t}redirectToAuthorization(t){if(this._windowMode==="tab"){if(!window.open(t.toString(),"_blank"))throw new Error("Tab was blocked")}else{const i=window.screenX+(window.outerWidth-600)/2,o=window.screenY+(window.outerHeight-700)/2;if(!window.open(t.toString(),"mcp-oauth",`width=600,height=700,left=${i},top=${o},popup=yes`)&&!window.open(t.toString(),"_blank"))throw new Error("Popup was blocked")}}saveCodeVerifier(t){this._codeVerifier=t}codeVerifier(){if(!this._codeVerifier)throw new Error("Code verifier not found");return this._codeVerifier}invalidateCredentials(){this._clientInfo=null,this._tokens=null,this._codeVerifier=null,this._state=null}}async function Q(e){const t=M(e,window.location.origin),n=e.orgSlug?`/api/${encodeURIComponent(e.orgSlug)}/mcp/${e.connectionId}`:`/mcp/${e.connectionId}`,r=new URL(n,t),i=new W({serverUrl:r.href,clientName:e.clientName,clientUri:e.clientUri,callbackUrl:e.callbackUrl,scope:e.scope,windowMode:e.windowMode}),o={fn:null};try{const s=new Promise((a,d)=>{const p=e.timeout||K;let _,S,f=!1;const L=i.state(),b=`${R}${L}`,w=()=>{window.removeEventListener("message",T),window.removeEventListener("storage",y),clearTimeout(_),clearInterval(S);try{localStorage.removeItem(b)}catch{}};o.fn=c=>{f||(f=!0,w(),d(c))};const I=async c=>{if(f)return;if(f=!0,!c.success){w(),d(new Error(c.error||"OAuth authentication failed"));return}const{code:g,state:$}=c;if(!g){w(),d(new Error("Missing authorization code"));return}if(i.getStoredState()!==$){w(),d(new Error("OAuth state mismatch - possible CSRF attack"));return}try{const U=(await V(r))?.authorization_servers?.[0]||r,A=await N(U),k=i.clientInformation();if(!k){w(),d(new Error("Client information not found"));return}const P=i.codeVerifier(),x=await H(U,{metadata:A,clientInformation:k,authorizationCode:g,codeVerifier:P,redirectUri:i.redirectUrl,resource:new URL(r)});w(),a({tokens:x,clientId:k.client_id??null,clientSecret:k.client_secret??null,tokenEndpoint:A?.token_endpoint??null,userinfoEndpoint:A?.userinfo_endpoint??null})}catch(E){w(),d(E)}},T=async c=>{!C()&&c.origin!==window.location.origin||c.data?.type==="mcp:oauth:callback"&&await I(c.data)},y=async c=>{if(!(c.key!==b||!c.newValue))try{const g=JSON.parse(c.newValue);await I(g)}catch{}};window.addEventListener("message",T),window.addEventListener("storage",y),S=setInterval(()=>{if(f)return;let c=null;try{c=localStorage.getItem(b)}catch{return}if(c)try{I(JSON.parse(c))}catch{}},J),_=setTimeout(()=>{f||(f=!0,w(),d(new Error("OAuth authentication timeout")))},p)});if(s.catch(()=>{}),await z(i,{serverUrl:r})==="REDIRECT"){const a=await s;return{token:a.tokens.access_token,tokenInfo:{accessToken:a.tokens.access_token,refreshToken:a.tokens.refresh_token??null,expiresIn:a.tokens.expires_in??null,scope:a.tokens.scope??null,clientId:a.clientId,clientSecret:a.clientSecret,tokenEndpoint:a.tokenEndpoint,userinfoEndpoint:a.userinfoEndpoint,idToken:a.tokens.id_token??null},error:null}}const l=i.tokens(),h=i.clientInformation();return{token:l?.access_token||null,tokenInfo:l?{accessToken:l.access_token,refreshToken:l.refresh_token??null,expiresIn:l.expires_in??null,scope:l.scope??null,clientId:h?.client_id??null,clientSecret:h?.client_secret??null,tokenEndpoint:null,userinfoEndpoint:null,idToken:l.id_token??null}:null,error:null}}catch(s){return o.fn&&o.fn(s instanceof Error?s:new Error(String(s))),{token:null,tokenInfo:null,error:s instanceof Error?s.message:String(s)}}}function O(e,t){if(window.opener&&!window.opener.closed){const n=C()?"*":window.location.origin;return window.opener.postMessage(e,n),!0}if(t)try{const n=`${R}${t}`;return localStorage.setItem(n,JSON.stringify(e)),!0}catch{}return!1}async function Z(){const e=new URLSearchParams(window.location.search),t=e.get("code");let n=e.get("state");const r=e.get("error"),i=e.get("error_description");let o=n;if(n)try{const u=atob(n),l=JSON.parse(u);l.clientState&&(o=l.clientState)}catch{}if(r){const u=i||r;return O({type:"mcp:oauth:callback",success:!1,error:u},o),{success:!1,error:u}}if(!t||!n){const u="Missing code or state parameter";return O({type:"mcp:oauth:callback",success:!1,error:u},o),{success:!1,error:u}}return n=o||n,O({type:"mcp:oauth:callback",success:!0,code:t,state:n},n)?{success:!0}:{success:!1,error:"Parent window not available"}}function m(){if(typeof window<"u"&&window.location?.origin)return window.location.origin}function j(e){try{const t=m(),n=t?new URL(e,t):new URL(e),r=n.pathname.match(/^\/api\/[^/]+\/mcp\/([^/]+)/);return r?r[1]??null:n.pathname.match(/^\/mcp\/([^/]+)/)?.[1]??null}catch{return null}}function F(e){try{const t=m();return(t?new URL(e,t):new URL(e)).pathname.match(/^\/api\/([^/]+)\/mcp\//)?.[1]??null}catch{return null}}async function G(e,t,n){const r={hasToken:!1,usable:!1,sandboxSignIn:!1};try{const i=`/api/${encodeURIComponent(t)}/connections/${e}/oauth-token/status`,o=n?new URL(i,n).href:i,s=m(),u=!n||new URL(n).origin===s,l=await fetch(o,{credentials:u?"include":"omit"});if(!l.ok)return r;const h=await l.json();return{hasToken:h.hasToken===!0,usable:h.hasToken===!0&&(h.isExpired!==!0||h.canRefresh===!0),sandboxSignIn:h.sandboxSignIn===!0}}catch{return r}}async function B({url:e,token:t,orgId:n,studioUrl:r,meshUrl:i}){try{const o=j(e),s=F(e),u=m(),l=M({studioUrl:r,meshUrl:i},u?new URL(e,u).origin:new URL(e).origin),h=o&&s?await G(o,s,l):null;if(h?.sandboxSignIn)return{isAuthenticated:h.usable,supportsOAuth:!0,hasOAuthToken:h.hasToken};const a=new Headers;a.set("Content-Type","application/json"),a.set("Accept","application/json, text/event-stream");const d=await fetch(e,{method:"POST",headers:a,body:JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"@decocms/studio MCP client",version:"1.0.0"}}}),signal:AbortSignal.timeout(v)});if(d.ok)return{isAuthenticated:!0,supportsOAuth:!1,hasOAuthToken:h?.hasToken??!1};let p;try{const f=await d.json();p=f.error||f.message}catch{}return d.status>=500?{isAuthenticated:!1,supportsOAuth:!1,hasOAuthToken:!1,error:p||`HTTP ${d.status}`,isServerError:!0}:{isAuthenticated:!1,supportsOAuth:!!d.headers.get("WWW-Authenticate"),hasOAuthToken:!1,error:p||`HTTP ${d.status}`}}catch(o){return console.error("[isConnectionAuthenticated] Error:",o),{isAuthenticated:!1,supportsOAuth:!1,hasOAuthToken:!1,error:o instanceof Error&&o.name==="TimeoutError"?`Connection check timed out after ${v/1e3}s`:o.message}}}export{Q as a,Z as h,B as i};