@decocms/mesh 1.0.0-alpha.12 → 1.0.0-alpha.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/cli.js +131 -129
- package/dist/server/migrate.js +1 -1
- package/dist/server/server.js +1 -1
- package/package.json +1 -1
package/dist/server/migrate.js
CHANGED
|
@@ -1019,7 +1019,7 @@ Please refer to the documentation here: https://better-auth.com/docs/plugins/org
|
|
|
1019
1019
|
</script>
|
|
1020
1020
|
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference" ${Y}></script>
|
|
1021
1021
|
</body>
|
|
1022
|
-
</html>`},nk=(Q)=>{let J=Q?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:E0("/open-api/generate-schema",{method:"GET"},async(X)=>{let Y=await r00(X.context,X.context.options);return X.json(Y)}),openAPIReference:E0(J,{method:"GET",metadata:{isAction:!1}},async(X)=>{if(Q?.disableDefaultReference)throw new m("NOT_FOUND");let Y=await r00(X.context,X.context.options);return new Response(uk0(Y,Q?.theme,Q?.nonce),{headers:{"Content-Type":"text/html"}})})}}};O9();DJ();Z6();y6();x1();var BL1=D4(async()=>{return{}}),OL1=D4({use:[T8]},async(Q)=>{return{session:Q.context.session}}),ML1=i4({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role"});var DL1=Number.POSITIVE_INFINITY;var a00=R(),dk0=z1(["pending","accepted","rejected","canceled"]).default("pending"),TL1=s({id:R().default(N6),name:R(),slug:R(),logo:R().nullish().optional(),metadata:X1(R(),ZQ()).or(R().transform((Q)=>JSON.parse(Q))).optional(),createdAt:R1()}),AL1=s({id:R().default(N6),organizationId:R(),userId:w1.string(),role:a00,createdAt:R1().default(()=>new Date)}),EL1=s({id:R().default(N6),organizationId:R(),email:R(),role:a00,status:dk0,teamId:R().nullish(),inviterId:R(),expiresAt:R1(),createdAt:R1().default(()=>new Date)}),RL1=s({id:R().default(N6),name:R().min(1),organizationId:R(),createdAt:R1(),updatedAt:R1().optional()}),SL1=s({id:R().default(N6),teamId:R(),userId:R(),createdAt:R1().default(()=>new Date)}),vL1=s({id:R().default(N6),organizationId:R(),role:R(),permission:X1(R(),a0(R())),createdAt:R1().default(()=>new Date),updatedAt:R1().optional()}),i00=["admin","member","owner"],CL1=S8([z1(i00),a0(z1(i00))]);E8();Z6();y6();var xL1=i4({INVALID_PHONE_NUMBER:"Invalid phone number",PHONE_NUMBER_EXIST:"Phone number already exists",PHONE_NUMBER_NOT_EXIST:"phone number isn't registered",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found",OTP_EXPIRED:"OTP expired",INVALID_OTP:"Invalid OTP",PHONE_NUMBER_NOT_VERIFIED:"Phone number not verified",PHONE_NUMBER_CANNOT_BE_UPDATED:"Phone number cannot be updated",SEND_OTP_NOT_IMPLEMENTED:"sendOTP not implemented",TOO_MANY_ATTEMPTS:"Too many attempts"});E8();M9();Z6();y6();C6();V8();var pk0=i4({OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code",INVALID_CODE:"Invalid code",TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:"Too many attempts. Please request a new code.",INVALID_TWO_FACTOR_COOKIE:"Invalid two factor cookie"});Z6();y6();var ck0=i4({INVALID_USERNAME_OR_PASSWORD:"Invalid username or password",EMAIL_NOT_VERIFIED:"Email not verified",UNEXPECTED_ERROR:"Unexpected error",USERNAME_IS_ALREADY_TAKEN:"Username is already taken. Please try another.",USERNAME_TOO_SHORT:"Username is too short",USERNAME_TOO_LONG:"Username is too long",INVALID_USERNAME:"Username is invalid",INVALID_DISPLAY_USERNAME:"Display username is invalid"});var e3={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"};import{existsSync as o00,readFileSync as s00}from"fs";var eP={emailAndPassword:{enabled:!0}},t00="./config.json",e00="./auth-config.json";function nk0(){if(o00(t00))try{let Q=s00(t00,"utf-8"),J=JSON.parse(Q);return{auth:eP,monitoring:e3,...J}}catch{return{auth:eP,monitoring:e3}}if(o00(e00))try{let Q=s00(e00,"utf-8");return{auth:JSON.parse(Q),monitoring:e3}}catch{return{auth:eP,monitoring:e3}}return{auth:eP,monitoring:e3}}var rk=nk0();import{existsSync as hf0,mkdirSync as gf0}from"fs";import{Kysely as B80,PostgresDialect as O80,sql as w80}from"kysely";import{BunWorkerDialect as M80}from"kysely-bun-worker";import*as D80 from"path";var kQ=E5(T_(),1),mP1=kQ.default.Client,S_=kQ.default.Pool,xP1=kQ.default.Connection,uP1=kQ.default.types,lP1=kQ.default.Query,dP1=kQ.default.DatabaseError,pP1=kQ.default.escapeIdentifier,cP1=kQ.default.escapeLiteral,nP1=kQ.default.Result,rP1=kQ.default.TypeOverrides,iP1=kQ.default.defaults;function mf0(Q){let J=new S_({connectionString:Q.connectionString,max:Q.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1}),X=new O80({pool:J});return{type:"postgres",db:new B80({dialect:X}),pool:J}}function T80(Q){if(Q===":memory:")return":memory:";if(Q.includes("://"))return new URL(Q).pathname;return Q}function A80(Q){if(Q!==":memory:"&&Q!=="/"&&Q){let J=Q.substring(0,Q.lastIndexOf("/"));if(J&&J!=="/"&&!hf0(J))try{gf0(J,{recursive:!0})}catch{return console.warn(`Failed to create directory ${J}, using in-memory database`),":memory:"}}return Q}function xf0(Q){let J=T80(Q.connectionString);J=A80(J);let X=new M80({url:J||":memory:"}),Y=new B80({dialect:X});if(J!==":memory:"&&Q.options?.enableWAL!==!1)w80`PRAGMA journal_mode = WAL;`.execute(Y).catch(()=>{});if(J!==":memory:"){let W=Q.options?.busyTimeout||5000;w80`PRAGMA busy_timeout = ${W};`.execute(Y).catch(()=>{})}return{type:"sqlite",db:Y}}function E80(Q){let J=Q||"file:./data/mesh.db";if(J===":memory:")return{type:"sqlite",connectionString:":memory:"};J=J.startsWith("/")?`file://${J}`:J;let X=URL.canParse(J)?new URL(J):null,Y=X?.protocol.replace(":","")??J.split("://")[0];switch(Y){case"postgres":case"postgresql":return{type:"postgres",connectionString:J};case"sqlite":case"file":if(!X?.pathname)throw Error("Invalid database URL: "+J);return{type:"sqlite",connectionString:X.pathname};default:throw Error(`Unsupported database protocol: ${Y}. Supported protocols: postgres://, postgresql://, sqlite://, file://`)}}function C_(){return process.env.DATABASE_URL||`file:${D80.join(process.cwd(),"data/mesh.db")}`}function R80(Q){let J=E80(Q);if(J.type==="postgres")return new O80({pool:new S_({connectionString:J.connectionString,max:J.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1})});let X=T80(J.connectionString);return X=A80(X),new M80({url:X||":memory:"})}function uf0(Q){let J=E80(Q);if(J.type==="postgres")return mf0(J);return xf0(J)}async function I_(Q){if(await Q.db.destroy(),Q.type==="postgres"&&!Q.pool.ended)await Q.pool.end()}var v_=null;function gF(){if(!v_)v_=uf0(C_());return v_}class k_{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:J,subject:X,html:Y}){let W=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:Q,from:J,subject:X,html:Y})});if(!W.ok)throw Error(`Failed to send email: ${W.statusText}`)}}class __{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:J,subject:X,html:Y}){let W=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:Q}]}],from:{email:J},subject:X,content:[{type:"text/html",value:Y}]})});if(!W.ok){let G=await W.text();throw Error(`Failed to send email via SendGrid: ${W.statusText} - ${G}`)}}}var lf0=(Q)=>{let J=new k_(Q.config.apiKey);return async({to:X,subject:Y,html:W})=>{await J.sendEmail({to:X,from:Q.config.fromEmail,subject:Y,html:W})}},df0=(Q)=>{let J=new __(Q.config.apiKey);return async({to:X,subject:Y,html:W})=>{await J.sendEmail({to:X,from:Q.config.fromEmail,subject:Y,html:W})}},pf0={resend:lf0,sendgrid:df0};function Fw(Q){let J=pf0[Q.provider];if(!J)throw Error(`Unknown email provider: ${Q.provider}`);return J(Q)}function Vw(Q,J){return Q.find((X)=>X.id===J)}var S80=(Q,J)=>{let X=Vw(J,Q.emailProviderId);if(!X)throw Error(`Email provider with id '${Q.emailProviderId}' not found`);let Y=Fw(X);return{sendMagicLink:async({email:W,url:G})=>{await Y({to:W,subject:"Magic Link",html:`<p>Click <a href="${G}">here</a> to login</p>`})}}};mF();import{createCipheriv as cf0,createDecipheriv as nf0,randomBytes as I80}from"crypto";var k80="aes-256-gcm",xF=16,_80=16,y80=32;class y_{key;constructor(Q){if(Buffer.from(Q,"base64").length===y80)this.key=Buffer.from(Q,"base64");else{let J=K1("crypto");this.key=J.createHash("sha256").update(Q).digest()}}async encrypt(Q){let J=I80(xF),X=cf0(k80,this.key,J),Y=X.update(Q,"utf8");Y=Buffer.concat([Y,X.final()]);let W=X.getAuthTag();return Buffer.concat([J,W,Y]).toString("base64")}async decrypt(Q){let J=Buffer.from(Q,"base64"),X=J.subarray(0,xF),Y=J.subarray(xF,xF+_80),W=J.subarray(xF+_80),G=nf0(k80,this.key,X);G.setAuthTag(Y);let $=G.update(W);return $=Buffer.concat([$,G.final()]),$.toString("utf8")}static generateKey(){return I80(y80).toString("base64")}}import{webcrypto as f80}from"crypto";var b80="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var rf0=128,DG,qZ;function if0(Q){if(!DG||DG.length<Q)DG=Buffer.allocUnsafe(Q*rf0),f80.getRandomValues(DG),qZ=0;else if(qZ+Q>DG.length)f80.getRandomValues(DG),qZ=0;qZ+=Q}function h80(Q=21){if0(Q|=0);let J="";for(let X=qZ-Q;X<qZ;X++)J+=b80[DG[X]&63];return J}function B7(Q){return`${Q}_${h80()}`}var af0=["connection_headers","oauth_config","configuration_scopes","metadata","tools","bindings"];class b_{db;vault;constructor(Q,J){this.db=Q;this.vault=J}async create(Q){let J=Q.id??B7("conn"),X=new Date().toISOString();if(await this.findById(J))return this.update(J,Q);let W=await this.serializeConnection({...Q,id:Q.id??J,status:"active",created_at:X,updated_at:X});await this.db.insertInto("connections").values(W).execute();let G=await this.findById(J);if(!G)throw Error(`Failed to create connection with id: ${J}`);return G}async findById(Q,J){let X=this.db.selectFrom("connections").selectAll().where("id","=",Q);if(J)X=X.where("organization_id","=",J);let Y=await X.executeTakeFirst();return Y?this.deserializeConnection(Y):null}async list(Q){let J=await this.db.selectFrom("connections").selectAll().where("organization_id","=",Q).execute();return Promise.all(J.map((X)=>this.deserializeConnection(X)))}async update(Q,J){if(Object.keys(J).length===0){let W=await this.findById(Q);if(!W)throw Error("Connection not found");return W}let X=await this.serializeConnection({...J,updated_at:new Date().toISOString()});await this.db.updateTable("connections").set(X).where("id","=",Q).execute();let Y=await this.findById(Q);if(!Y)throw Error("Connection not found after update");return Y}async delete(Q){await this.db.deleteFrom("connections").where("id","=",Q).execute()}async testConnection(Q,J){let X=await this.findById(Q);if(!X)throw Error("Connection not found");let Y=Date.now();try{let W=await fetch(X.connection_url,{method:"POST",headers:{"Content-Type":"application/json",...X.connection_token&&{Authorization:`Bearer ${X.connection_token}`},...J},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})});return{healthy:W.ok||W.status===404,latencyMs:Date.now()-Y}}catch{return{healthy:!1,latencyMs:Date.now()-Y}}}async serializeConnection(Q){let J={};for(let[X,Y]of Object.entries(Q)){if(Y===void 0)continue;if(X==="connection_token"&&Y)J[X]=await this.vault.encrypt(Y);else if(X==="configuration_state"&&Y){let W=JSON.stringify(Y);J[X]=await this.vault.encrypt(W)}else if(af0.includes(X))J[X]=Y?JSON.stringify(Y):null;else J[X]=Y}return J}async deserializeConnection(Q){let J=null;if(Q.connection_token)try{J=await this.vault.decrypt(Q.connection_token)}catch(W){console.error("Failed to decrypt connection token:",W)}let X=null;if(Q.configuration_state)try{let W=await this.vault.decrypt(Q.configuration_state);X=JSON.parse(W)}catch(W){console.error("Failed to decrypt configuration state:",W)}let Y=(W)=>{if(W===null)return null;if(typeof W==="string")try{return JSON.parse(W)}catch{return null}return W};return{id:Q.id,organization_id:Q.organization_id,created_by:Q.created_by,title:Q.title,description:Q.description,icon:Q.icon,app_name:Q.app_name,app_id:Q.app_id,connection_type:Q.connection_type,connection_url:Q.connection_url,connection_token:J,connection_headers:Y(Q.connection_headers),oauth_config:Y(Q.oauth_config),configuration_state:X,configuration_scopes:Y(Q.configuration_scopes),metadata:Y(Q.metadata),tools:Y(Q.tools),bindings:Y(Q.bindings),status:Q.status,created_at:Q.created_at,updated_at:Q.updated_at}}}class f_{db;constructor(Q){this.db=Q}async create(Q,J,X){let Y=B7("gw"),W=new Date().toISOString();if(X.isDefault)return await this.db.transaction().execute(async($)=>{if(await $.updateTable("gateways").set({is_default:0,updated_at:W,updated_by:J}).where("organization_id","=",Q).where("is_default","=",1).execute(),await $.insertInto("gateways").values({id:Y,organization_id:Q,title:X.title,description:X.description??null,tool_selection_strategy:X.toolSelectionStrategy??"passthrough",tool_selection_mode:X.toolSelectionMode??"inclusion",icon:X.icon??null,status:X.status??"active",is_default:1,created_at:W,updated_at:W,created_by:J,updated_by:null}).execute(),X.connections.length>0)await $.insertInto("gateway_connections").values(X.connections.map((K)=>({id:B7("gwc"),gateway_id:Y,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,created_at:W}))).execute();let Z=await this.findByIdInternal($,Y);if(!Z)throw Error(`Failed to create gateway with id: ${Y}`);return Z});if(await this.db.insertInto("gateways").values({id:Y,organization_id:Q,title:X.title,description:X.description??null,tool_selection_strategy:X.toolSelectionStrategy??"passthrough",tool_selection_mode:X.toolSelectionMode??"inclusion",icon:X.icon??null,status:X.status??"active",is_default:0,created_at:W,updated_at:W,created_by:J,updated_by:null}).execute(),X.connections.length>0)await this.db.insertInto("gateway_connections").values(X.connections.map(($)=>({id:B7("gwc"),gateway_id:Y,connection_id:$.connectionId,selected_tools:$.selectedTools?JSON.stringify($.selectedTools):null,created_at:W}))).execute();let G=await this.findById(Y);if(!G)throw Error(`Failed to create gateway with id: ${Y}`);return G}async findById(Q){return this.findByIdInternal(this.db,Q)}async findByIdInternal(Q,J){let X=await Q.selectFrom("gateways").selectAll().where("id","=",J).executeTakeFirst();if(!X)return null;let Y=await Q.selectFrom("gateway_connections").selectAll().where("gateway_id","=",J).execute();return this.deserializeGatewayWithConnections(X,Y)}async list(Q){let J=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).execute(),X=J.map((G)=>G.id);if(X.length===0)return[];let Y=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",X).execute(),W=new Map;for(let G of Y){let $=W.get(G.gateway_id)??[];$.push(G),W.set(G.gateway_id,$)}return J.map((G)=>this.deserializeGatewayWithConnections(G,W.get(G.id)??[]))}async listByConnectionId(Q,J){let Y=(await this.db.selectFrom("gateway_connections").select("gateway_id").where("connection_id","=",J).execute()).map((K)=>K.gateway_id);if(Y.length===0)return[];let W=await this.db.selectFrom("gateways").selectAll().where("id","in",Y).where("organization_id","=",Q).execute();if(W.length===0)return[];let G=W.map((K)=>K.id),$=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",G).execute(),Z=new Map;for(let K of $){let H=Z.get(K.gateway_id)??[];H.push(K),Z.set(K.gateway_id,H)}return W.map((K)=>this.deserializeGatewayWithConnections(K,Z.get(K.id)??[]))}async update(Q,J,X){let Y=new Date().toISOString(),W={updated_at:Y,updated_by:J};if(X.title!==void 0)W.title=X.title;if(X.description!==void 0)W.description=X.description;if(X.toolSelectionStrategy!==void 0)W.tool_selection_strategy=X.toolSelectionStrategy;if(X.toolSelectionMode!==void 0)W.tool_selection_mode=X.toolSelectionMode;if(X.icon!==void 0)W.icon=X.icon;if(X.status!==void 0)W.status=X.status;if(X.isDefault===!1)W.is_default=0;if(X.isDefault===!0)W.is_default=1;if(X.isDefault===!0){let $=await this.findById(Q);if(!$)throw Error(`Gateway not found: ${Q}`);await this.db.transaction().execute(async(Z)=>{if(await Z.updateTable("gateways").set({is_default:0,updated_at:Y,updated_by:J}).where("organization_id","=",$.organizationId).where("is_default","=",1).execute(),await Z.updateTable("gateways").set(W).where("id","=",Q).execute(),X.connections!==void 0){if(await Z.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),X.connections.length>0)await Z.insertInto("gateway_connections").values(X.connections.map((K)=>({id:B7("gwc"),gateway_id:Q,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,created_at:Y}))).execute()}})}else if(await this.db.updateTable("gateways").set(W).where("id","=",Q).execute(),X.connections!==void 0){if(await this.db.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),X.connections.length>0)await this.db.insertInto("gateway_connections").values(X.connections.map(($)=>({id:B7("gwc"),gateway_id:Q,connection_id:$.connectionId,selected_tools:$.selectedTools?JSON.stringify($.selectedTools):null,created_at:Y}))).execute()}let G=await this.findById(Q);if(!G)throw Error("Gateway not found after update");return G}async delete(Q){await this.db.deleteFrom("gateways").where("id","=",Q).execute()}async getDefaultByOrgId(Q){let J=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).where("is_default","=",1).executeTakeFirst();if(!J)return null;let X=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","=",J.id).execute();return this.deserializeGatewayWithConnections(J,X)}async getDefaultByOrgSlug(Q){let J=await this.db.selectFrom("organization").select("id").where("slug","=",Q).executeTakeFirst();if(!J)return null;return this.getDefaultByOrgId(J.id)}async setDefault(Q,J){let X=await this.findById(Q);if(!X)throw Error(`Gateway not found: ${Q}`);let Y=new Date().toISOString();await this.db.transaction().execute(async(G)=>{await G.updateTable("gateways").set({is_default:0,updated_at:Y,updated_by:J}).where("organization_id","=",X.organizationId).where("is_default","=",1).execute(),await G.updateTable("gateways").set({is_default:1,updated_at:Y,updated_by:J}).where("id","=",Q).execute()});let W=await this.findById(Q);if(!W)throw Error("Gateway not found after setting default");return W}deserializeGatewayWithConnections(Q,J){return{...this.deserializeGateway(Q),connections:J.map((Y)=>({connectionId:Y.connection_id,selectedTools:this.parseJson(Y.selected_tools)}))}}deserializeGateway(Q){return{id:Q.id,organizationId:Q.organization_id,title:Q.title,description:Q.description,toolSelectionStrategy:this.parseToolSelectionStrategy(Q.tool_selection_strategy),toolSelectionMode:this.parseToolSelectionMode(Q.tool_selection_mode),icon:Q.icon,status:Q.status,isDefault:Q.is_default===1,createdAt:Q.created_at,updatedAt:Q.updated_at,createdBy:Q.created_by,updatedBy:Q.updated_by}}parseToolSelectionStrategy(Q){if(Q==="smart_tool_selection")return"smart_tool_selection";if(Q==="code_execution")return"code_execution";return"passthrough"}parseToolSelectionMode(Q){if(Q==="exclusion")return"exclusion";return"inclusion"}parseJson(Q){if(Q===null)return null;if(typeof Q==="string")try{return JSON.parse(Q)}catch{return null}return Q}}NB();RB();function ln0(){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (xG0(),mG0));return Q.map((J)=>{return{name:J.name,inputSchema:IZ(J.inputSchema),outputSchema:J.outputSchema?IZ(J.outputSchema):void 0,description:J.description}})},data:C80(process.env.BASE_URL||"http://localhost:3000")},{data:v80()}]}async function uG0(Q,J){try{let X=gF(),Y=new y_(process.env.ENCRYPTION_KEY||""),W=new b_(X.db,Y),G=new f_(X.db),$=ln0(),Z=[];await Promise.all($.map(async(K)=>{let H=null;if(K.permissions)H=(await YK.api.createApiKey({body:{name:`${K.data.app_name??crypto.randomUUID()}-mcp`,userId:J,permissions:K.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Q},purpose:"default-org-connections"}}}))?.key;let q=await K.getTools?.()??await CZ({id:"pending",title:K.data.title,connection_url:K.data.connection_url,connection_token:K.data.connection_token,connection_headers:K.data.connection_headers}).catch(()=>null),F=K.data.id?`${Q}_${K.data.id}`:void 0,V=await W.create({...K.data,id:F,tools:q,organization_id:Q,created_by:J,connection_token:K.data.connection_token??H});Z.push(V.id)})),await G.create(Q,J,{title:"Default Gateway",description:"Auto-created gateway that includes all connections",toolSelectionStrategy:"passthrough",toolSelectionMode:"exclusion",status:"active",isDefault:!0,connections:Z.map((K)=>({connectionId:K}))})}catch(X){console.error("Error creating default MCP connections:",X)}}var lG0=["owner","admin"];var dn0=(Q)=>{return{defaultSSO:[{domain:Q.domain,providerId:Q.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Q.MS_CLIENT_ID,clientSecret:Q.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Q.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},dG0=(Q)=>{if(Q.providerId==="microsoft")return dn0(Q);throw Error(`Unsupported provider: ${Q.providerId}`)};function pn0(Q){return Q.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var pG0=["labs","hub","studio","workspace","systems","core","cloud","works"],cG0=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];function cn0(){let Q=Math.floor(Math.random()*cG0.length),J=Math.floor(Math.random()*pG0.length),X=cG0[Q]??"deco",Y=pG0[J]??"studio";return`${X}-${Y}`}var nn0=Object.values(GS()).map((Q)=>Q.map((J)=>J.name)).flat(),rn0={...mP,self:["*",...nn0]},OO=XX(rn0),in0=OO.newRole({self:["*"],...BF.statements}),an0=OO.newRole({self:["*"],...BF.statements}),on0=OO.newRole({self:["*"],...BF.statements}),nG0=Object.values(GS()).map((Q)=>Q.map((J)=>`self:${J.name}`)).flat(),o5=rk.auth,rG0=void 0;if(o5.inviteEmailProviderId&&o5.emailProviders&&o5.emailProviders.length>0){let Q=Vw(o5.emailProviders,o5.inviteEmailProviderId);if(Q){let J=Fw(Q);rG0=async(X)=>{let Y=X.inviter.user?.name||X.inviter.user?.email,W=`${process.env.BASE_URL||"http://localhost:3000"}/auth/accept-invitation?invitationId=${X.invitation.id}`;await J({to:X.email,subject:`Invitation to join ${X.organization.name}`,html:`
|
|
1022
|
+
</html>`},nk=(Q)=>{let J=Q?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:E0("/open-api/generate-schema",{method:"GET"},async(X)=>{let Y=await r00(X.context,X.context.options);return X.json(Y)}),openAPIReference:E0(J,{method:"GET",metadata:{isAction:!1}},async(X)=>{if(Q?.disableDefaultReference)throw new m("NOT_FOUND");let Y=await r00(X.context,X.context.options);return new Response(uk0(Y,Q?.theme,Q?.nonce),{headers:{"Content-Type":"text/html"}})})}}};O9();DJ();Z6();y6();x1();var BL1=D4(async()=>{return{}}),OL1=D4({use:[T8]},async(Q)=>{return{session:Q.context.session}}),ML1=i4({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role"});var DL1=Number.POSITIVE_INFINITY;var a00=R(),dk0=z1(["pending","accepted","rejected","canceled"]).default("pending"),TL1=s({id:R().default(N6),name:R(),slug:R(),logo:R().nullish().optional(),metadata:X1(R(),ZQ()).or(R().transform((Q)=>JSON.parse(Q))).optional(),createdAt:R1()}),AL1=s({id:R().default(N6),organizationId:R(),userId:w1.string(),role:a00,createdAt:R1().default(()=>new Date)}),EL1=s({id:R().default(N6),organizationId:R(),email:R(),role:a00,status:dk0,teamId:R().nullish(),inviterId:R(),expiresAt:R1(),createdAt:R1().default(()=>new Date)}),RL1=s({id:R().default(N6),name:R().min(1),organizationId:R(),createdAt:R1(),updatedAt:R1().optional()}),SL1=s({id:R().default(N6),teamId:R(),userId:R(),createdAt:R1().default(()=>new Date)}),vL1=s({id:R().default(N6),organizationId:R(),role:R(),permission:X1(R(),a0(R())),createdAt:R1().default(()=>new Date),updatedAt:R1().optional()}),i00=["admin","member","owner"],CL1=S8([z1(i00),a0(z1(i00))]);E8();Z6();y6();var xL1=i4({INVALID_PHONE_NUMBER:"Invalid phone number",PHONE_NUMBER_EXIST:"Phone number already exists",PHONE_NUMBER_NOT_EXIST:"phone number isn't registered",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found",OTP_EXPIRED:"OTP expired",INVALID_OTP:"Invalid OTP",PHONE_NUMBER_NOT_VERIFIED:"Phone number not verified",PHONE_NUMBER_CANNOT_BE_UPDATED:"Phone number cannot be updated",SEND_OTP_NOT_IMPLEMENTED:"sendOTP not implemented",TOO_MANY_ATTEMPTS:"Too many attempts"});E8();M9();Z6();y6();C6();V8();var pk0=i4({OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code",INVALID_CODE:"Invalid code",TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:"Too many attempts. Please request a new code.",INVALID_TWO_FACTOR_COOKIE:"Invalid two factor cookie"});Z6();y6();var ck0=i4({INVALID_USERNAME_OR_PASSWORD:"Invalid username or password",EMAIL_NOT_VERIFIED:"Email not verified",UNEXPECTED_ERROR:"Unexpected error",USERNAME_IS_ALREADY_TAKEN:"Username is already taken. Please try another.",USERNAME_TOO_SHORT:"Username is too short",USERNAME_TOO_LONG:"Username is too long",INVALID_USERNAME:"Username is invalid",INVALID_DISPLAY_USERNAME:"Display username is invalid"});var e3={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"};import{existsSync as o00,readFileSync as s00}from"fs";var eP={emailAndPassword:{enabled:!0}},t00=process.env.CONFIG_PATH||"./config.json",e00=process.env.AUTH_CONFIG_PATH||"./auth-config.json";function nk0(){if(o00(t00))try{let Q=s00(t00,"utf-8"),J=JSON.parse(Q);return{auth:eP,monitoring:e3,...J}}catch{return{auth:eP,monitoring:e3}}if(o00(e00))try{let Q=s00(e00,"utf-8");return{auth:JSON.parse(Q),monitoring:e3}}catch{return{auth:eP,monitoring:e3}}return{auth:eP,monitoring:e3}}var rk=nk0();import{existsSync as hf0,mkdirSync as gf0}from"fs";import{Kysely as B80,PostgresDialect as O80,sql as w80}from"kysely";import{BunWorkerDialect as M80}from"kysely-bun-worker";import*as D80 from"path";var kQ=E5(T_(),1),mP1=kQ.default.Client,S_=kQ.default.Pool,xP1=kQ.default.Connection,uP1=kQ.default.types,lP1=kQ.default.Query,dP1=kQ.default.DatabaseError,pP1=kQ.default.escapeIdentifier,cP1=kQ.default.escapeLiteral,nP1=kQ.default.Result,rP1=kQ.default.TypeOverrides,iP1=kQ.default.defaults;function mf0(Q){let J=new S_({connectionString:Q.connectionString,max:Q.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1}),X=new O80({pool:J});return{type:"postgres",db:new B80({dialect:X}),pool:J}}function T80(Q){if(Q===":memory:")return":memory:";if(Q.includes("://"))return new URL(Q).pathname;return Q}function A80(Q){if(Q!==":memory:"&&Q!=="/"&&Q){let J=Q.substring(0,Q.lastIndexOf("/"));if(J&&J!=="/"&&!hf0(J))try{gf0(J,{recursive:!0})}catch{return console.warn(`Failed to create directory ${J}, using in-memory database`),":memory:"}}return Q}function xf0(Q){let J=T80(Q.connectionString);J=A80(J);let X=new M80({url:J||":memory:"}),Y=new B80({dialect:X});if(J!==":memory:"&&Q.options?.enableWAL!==!1)w80`PRAGMA journal_mode = WAL;`.execute(Y).catch(()=>{});if(J!==":memory:"){let W=Q.options?.busyTimeout||5000;w80`PRAGMA busy_timeout = ${W};`.execute(Y).catch(()=>{})}return{type:"sqlite",db:Y}}function E80(Q){let J=Q||"file:./data/mesh.db";if(J===":memory:")return{type:"sqlite",connectionString:":memory:"};J=J.startsWith("/")?`file://${J}`:J;let X=URL.canParse(J)?new URL(J):null,Y=X?.protocol.replace(":","")??J.split("://")[0];switch(Y){case"postgres":case"postgresql":return{type:"postgres",connectionString:J};case"sqlite":case"file":if(!X?.pathname)throw Error("Invalid database URL: "+J);return{type:"sqlite",connectionString:X.pathname};default:throw Error(`Unsupported database protocol: ${Y}. Supported protocols: postgres://, postgresql://, sqlite://, file://`)}}function C_(){return process.env.DATABASE_URL||`file:${D80.join(process.cwd(),"data/mesh.db")}`}function R80(Q){let J=E80(Q);if(J.type==="postgres")return new O80({pool:new S_({connectionString:J.connectionString,max:J.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1})});let X=T80(J.connectionString);return X=A80(X),new M80({url:X||":memory:"})}function uf0(Q){let J=E80(Q);if(J.type==="postgres")return mf0(J);return xf0(J)}async function I_(Q){if(await Q.db.destroy(),Q.type==="postgres"&&!Q.pool.ended)await Q.pool.end()}var v_=null;function gF(){if(!v_)v_=uf0(C_());return v_}class k_{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:J,subject:X,html:Y}){let W=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:Q,from:J,subject:X,html:Y})});if(!W.ok)throw Error(`Failed to send email: ${W.statusText}`)}}class __{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:J,subject:X,html:Y}){let W=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:Q}]}],from:{email:J},subject:X,content:[{type:"text/html",value:Y}]})});if(!W.ok){let G=await W.text();throw Error(`Failed to send email via SendGrid: ${W.statusText} - ${G}`)}}}var lf0=(Q)=>{let J=new k_(Q.config.apiKey);return async({to:X,subject:Y,html:W})=>{await J.sendEmail({to:X,from:Q.config.fromEmail,subject:Y,html:W})}},df0=(Q)=>{let J=new __(Q.config.apiKey);return async({to:X,subject:Y,html:W})=>{await J.sendEmail({to:X,from:Q.config.fromEmail,subject:Y,html:W})}},pf0={resend:lf0,sendgrid:df0};function Fw(Q){let J=pf0[Q.provider];if(!J)throw Error(`Unknown email provider: ${Q.provider}`);return J(Q)}function Vw(Q,J){return Q.find((X)=>X.id===J)}var S80=(Q,J)=>{let X=Vw(J,Q.emailProviderId);if(!X)throw Error(`Email provider with id '${Q.emailProviderId}' not found`);let Y=Fw(X);return{sendMagicLink:async({email:W,url:G})=>{await Y({to:W,subject:"Magic Link",html:`<p>Click <a href="${G}">here</a> to login</p>`})}}};mF();import{createCipheriv as cf0,createDecipheriv as nf0,randomBytes as I80}from"crypto";var k80="aes-256-gcm",xF=16,_80=16,y80=32;class y_{key;constructor(Q){if(Buffer.from(Q,"base64").length===y80)this.key=Buffer.from(Q,"base64");else{let J=K1("crypto");this.key=J.createHash("sha256").update(Q).digest()}}async encrypt(Q){let J=I80(xF),X=cf0(k80,this.key,J),Y=X.update(Q,"utf8");Y=Buffer.concat([Y,X.final()]);let W=X.getAuthTag();return Buffer.concat([J,W,Y]).toString("base64")}async decrypt(Q){let J=Buffer.from(Q,"base64"),X=J.subarray(0,xF),Y=J.subarray(xF,xF+_80),W=J.subarray(xF+_80),G=nf0(k80,this.key,X);G.setAuthTag(Y);let $=G.update(W);return $=Buffer.concat([$,G.final()]),$.toString("utf8")}static generateKey(){return I80(y80).toString("base64")}}import{webcrypto as f80}from"crypto";var b80="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var rf0=128,DG,qZ;function if0(Q){if(!DG||DG.length<Q)DG=Buffer.allocUnsafe(Q*rf0),f80.getRandomValues(DG),qZ=0;else if(qZ+Q>DG.length)f80.getRandomValues(DG),qZ=0;qZ+=Q}function h80(Q=21){if0(Q|=0);let J="";for(let X=qZ-Q;X<qZ;X++)J+=b80[DG[X]&63];return J}function B7(Q){return`${Q}_${h80()}`}var af0=["connection_headers","oauth_config","configuration_scopes","metadata","tools","bindings"];class b_{db;vault;constructor(Q,J){this.db=Q;this.vault=J}async create(Q){let J=Q.id??B7("conn"),X=new Date().toISOString();if(await this.findById(J))return this.update(J,Q);let W=await this.serializeConnection({...Q,id:Q.id??J,status:"active",created_at:X,updated_at:X});await this.db.insertInto("connections").values(W).execute();let G=await this.findById(J);if(!G)throw Error(`Failed to create connection with id: ${J}`);return G}async findById(Q,J){let X=this.db.selectFrom("connections").selectAll().where("id","=",Q);if(J)X=X.where("organization_id","=",J);let Y=await X.executeTakeFirst();return Y?this.deserializeConnection(Y):null}async list(Q){let J=await this.db.selectFrom("connections").selectAll().where("organization_id","=",Q).execute();return Promise.all(J.map((X)=>this.deserializeConnection(X)))}async update(Q,J){if(Object.keys(J).length===0){let W=await this.findById(Q);if(!W)throw Error("Connection not found");return W}let X=await this.serializeConnection({...J,updated_at:new Date().toISOString()});await this.db.updateTable("connections").set(X).where("id","=",Q).execute();let Y=await this.findById(Q);if(!Y)throw Error("Connection not found after update");return Y}async delete(Q){await this.db.deleteFrom("connections").where("id","=",Q).execute()}async testConnection(Q,J){let X=await this.findById(Q);if(!X)throw Error("Connection not found");let Y=Date.now();try{let W=await fetch(X.connection_url,{method:"POST",headers:{"Content-Type":"application/json",...X.connection_token&&{Authorization:`Bearer ${X.connection_token}`},...J},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})});return{healthy:W.ok||W.status===404,latencyMs:Date.now()-Y}}catch{return{healthy:!1,latencyMs:Date.now()-Y}}}async serializeConnection(Q){let J={};for(let[X,Y]of Object.entries(Q)){if(Y===void 0)continue;if(X==="connection_token"&&Y)J[X]=await this.vault.encrypt(Y);else if(X==="configuration_state"&&Y){let W=JSON.stringify(Y);J[X]=await this.vault.encrypt(W)}else if(af0.includes(X))J[X]=Y?JSON.stringify(Y):null;else J[X]=Y}return J}async deserializeConnection(Q){let J=null;if(Q.connection_token)try{J=await this.vault.decrypt(Q.connection_token)}catch(W){console.error("Failed to decrypt connection token:",W)}let X=null;if(Q.configuration_state)try{let W=await this.vault.decrypt(Q.configuration_state);X=JSON.parse(W)}catch(W){console.error("Failed to decrypt configuration state:",W)}let Y=(W)=>{if(W===null)return null;if(typeof W==="string")try{return JSON.parse(W)}catch{return null}return W};return{id:Q.id,organization_id:Q.organization_id,created_by:Q.created_by,title:Q.title,description:Q.description,icon:Q.icon,app_name:Q.app_name,app_id:Q.app_id,connection_type:Q.connection_type,connection_url:Q.connection_url,connection_token:J,connection_headers:Y(Q.connection_headers),oauth_config:Y(Q.oauth_config),configuration_state:X,configuration_scopes:Y(Q.configuration_scopes),metadata:Y(Q.metadata),tools:Y(Q.tools),bindings:Y(Q.bindings),status:Q.status,created_at:Q.created_at,updated_at:Q.updated_at}}}class f_{db;constructor(Q){this.db=Q}async create(Q,J,X){let Y=B7("gw"),W=new Date().toISOString();if(X.isDefault)return await this.db.transaction().execute(async($)=>{if(await $.updateTable("gateways").set({is_default:0,updated_at:W,updated_by:J}).where("organization_id","=",Q).where("is_default","=",1).execute(),await $.insertInto("gateways").values({id:Y,organization_id:Q,title:X.title,description:X.description??null,tool_selection_strategy:X.toolSelectionStrategy??"passthrough",tool_selection_mode:X.toolSelectionMode??"inclusion",icon:X.icon??null,status:X.status??"active",is_default:1,created_at:W,updated_at:W,created_by:J,updated_by:null}).execute(),X.connections.length>0)await $.insertInto("gateway_connections").values(X.connections.map((K)=>({id:B7("gwc"),gateway_id:Y,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,created_at:W}))).execute();let Z=await this.findByIdInternal($,Y);if(!Z)throw Error(`Failed to create gateway with id: ${Y}`);return Z});if(await this.db.insertInto("gateways").values({id:Y,organization_id:Q,title:X.title,description:X.description??null,tool_selection_strategy:X.toolSelectionStrategy??"passthrough",tool_selection_mode:X.toolSelectionMode??"inclusion",icon:X.icon??null,status:X.status??"active",is_default:0,created_at:W,updated_at:W,created_by:J,updated_by:null}).execute(),X.connections.length>0)await this.db.insertInto("gateway_connections").values(X.connections.map(($)=>({id:B7("gwc"),gateway_id:Y,connection_id:$.connectionId,selected_tools:$.selectedTools?JSON.stringify($.selectedTools):null,created_at:W}))).execute();let G=await this.findById(Y);if(!G)throw Error(`Failed to create gateway with id: ${Y}`);return G}async findById(Q){return this.findByIdInternal(this.db,Q)}async findByIdInternal(Q,J){let X=await Q.selectFrom("gateways").selectAll().where("id","=",J).executeTakeFirst();if(!X)return null;let Y=await Q.selectFrom("gateway_connections").selectAll().where("gateway_id","=",J).execute();return this.deserializeGatewayWithConnections(X,Y)}async list(Q){let J=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).execute(),X=J.map((G)=>G.id);if(X.length===0)return[];let Y=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",X).execute(),W=new Map;for(let G of Y){let $=W.get(G.gateway_id)??[];$.push(G),W.set(G.gateway_id,$)}return J.map((G)=>this.deserializeGatewayWithConnections(G,W.get(G.id)??[]))}async listByConnectionId(Q,J){let Y=(await this.db.selectFrom("gateway_connections").select("gateway_id").where("connection_id","=",J).execute()).map((K)=>K.gateway_id);if(Y.length===0)return[];let W=await this.db.selectFrom("gateways").selectAll().where("id","in",Y).where("organization_id","=",Q).execute();if(W.length===0)return[];let G=W.map((K)=>K.id),$=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",G).execute(),Z=new Map;for(let K of $){let H=Z.get(K.gateway_id)??[];H.push(K),Z.set(K.gateway_id,H)}return W.map((K)=>this.deserializeGatewayWithConnections(K,Z.get(K.id)??[]))}async update(Q,J,X){let Y=new Date().toISOString(),W={updated_at:Y,updated_by:J};if(X.title!==void 0)W.title=X.title;if(X.description!==void 0)W.description=X.description;if(X.toolSelectionStrategy!==void 0)W.tool_selection_strategy=X.toolSelectionStrategy;if(X.toolSelectionMode!==void 0)W.tool_selection_mode=X.toolSelectionMode;if(X.icon!==void 0)W.icon=X.icon;if(X.status!==void 0)W.status=X.status;if(X.isDefault===!1)W.is_default=0;if(X.isDefault===!0)W.is_default=1;if(X.isDefault===!0){let $=await this.findById(Q);if(!$)throw Error(`Gateway not found: ${Q}`);await this.db.transaction().execute(async(Z)=>{if(await Z.updateTable("gateways").set({is_default:0,updated_at:Y,updated_by:J}).where("organization_id","=",$.organizationId).where("is_default","=",1).execute(),await Z.updateTable("gateways").set(W).where("id","=",Q).execute(),X.connections!==void 0){if(await Z.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),X.connections.length>0)await Z.insertInto("gateway_connections").values(X.connections.map((K)=>({id:B7("gwc"),gateway_id:Q,connection_id:K.connectionId,selected_tools:K.selectedTools?JSON.stringify(K.selectedTools):null,created_at:Y}))).execute()}})}else if(await this.db.updateTable("gateways").set(W).where("id","=",Q).execute(),X.connections!==void 0){if(await this.db.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),X.connections.length>0)await this.db.insertInto("gateway_connections").values(X.connections.map(($)=>({id:B7("gwc"),gateway_id:Q,connection_id:$.connectionId,selected_tools:$.selectedTools?JSON.stringify($.selectedTools):null,created_at:Y}))).execute()}let G=await this.findById(Q);if(!G)throw Error("Gateway not found after update");return G}async delete(Q){await this.db.deleteFrom("gateways").where("id","=",Q).execute()}async getDefaultByOrgId(Q){let J=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).where("is_default","=",1).executeTakeFirst();if(!J)return null;let X=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","=",J.id).execute();return this.deserializeGatewayWithConnections(J,X)}async getDefaultByOrgSlug(Q){let J=await this.db.selectFrom("organization").select("id").where("slug","=",Q).executeTakeFirst();if(!J)return null;return this.getDefaultByOrgId(J.id)}async setDefault(Q,J){let X=await this.findById(Q);if(!X)throw Error(`Gateway not found: ${Q}`);let Y=new Date().toISOString();await this.db.transaction().execute(async(G)=>{await G.updateTable("gateways").set({is_default:0,updated_at:Y,updated_by:J}).where("organization_id","=",X.organizationId).where("is_default","=",1).execute(),await G.updateTable("gateways").set({is_default:1,updated_at:Y,updated_by:J}).where("id","=",Q).execute()});let W=await this.findById(Q);if(!W)throw Error("Gateway not found after setting default");return W}deserializeGatewayWithConnections(Q,J){return{...this.deserializeGateway(Q),connections:J.map((Y)=>({connectionId:Y.connection_id,selectedTools:this.parseJson(Y.selected_tools)}))}}deserializeGateway(Q){return{id:Q.id,organizationId:Q.organization_id,title:Q.title,description:Q.description,toolSelectionStrategy:this.parseToolSelectionStrategy(Q.tool_selection_strategy),toolSelectionMode:this.parseToolSelectionMode(Q.tool_selection_mode),icon:Q.icon,status:Q.status,isDefault:Q.is_default===1,createdAt:Q.created_at,updatedAt:Q.updated_at,createdBy:Q.created_by,updatedBy:Q.updated_by}}parseToolSelectionStrategy(Q){if(Q==="smart_tool_selection")return"smart_tool_selection";if(Q==="code_execution")return"code_execution";return"passthrough"}parseToolSelectionMode(Q){if(Q==="exclusion")return"exclusion";return"inclusion"}parseJson(Q){if(Q===null)return null;if(typeof Q==="string")try{return JSON.parse(Q)}catch{return null}return Q}}NB();RB();function ln0(){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (xG0(),mG0));return Q.map((J)=>{return{name:J.name,inputSchema:IZ(J.inputSchema),outputSchema:J.outputSchema?IZ(J.outputSchema):void 0,description:J.description}})},data:C80(process.env.BASE_URL||"http://localhost:3000")},{data:v80()}]}async function uG0(Q,J){try{let X=gF(),Y=new y_(process.env.ENCRYPTION_KEY||""),W=new b_(X.db,Y),G=new f_(X.db),$=ln0(),Z=[];await Promise.all($.map(async(K)=>{let H=null;if(K.permissions)H=(await YK.api.createApiKey({body:{name:`${K.data.app_name??crypto.randomUUID()}-mcp`,userId:J,permissions:K.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Q},purpose:"default-org-connections"}}}))?.key;let q=await K.getTools?.()??await CZ({id:"pending",title:K.data.title,connection_url:K.data.connection_url,connection_token:K.data.connection_token,connection_headers:K.data.connection_headers}).catch(()=>null),F=K.data.id?`${Q}_${K.data.id}`:void 0,V=await W.create({...K.data,id:F,tools:q,organization_id:Q,created_by:J,connection_token:K.data.connection_token??H});Z.push(V.id)})),await G.create(Q,J,{title:"Default Gateway",description:"Auto-created gateway that includes all connections",toolSelectionStrategy:"passthrough",toolSelectionMode:"exclusion",status:"active",isDefault:!0,connections:Z.map((K)=>({connectionId:K}))})}catch(X){console.error("Error creating default MCP connections:",X)}}var lG0=["owner","admin"];var dn0=(Q)=>{return{defaultSSO:[{domain:Q.domain,providerId:Q.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Q.MS_CLIENT_ID,clientSecret:Q.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Q.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},dG0=(Q)=>{if(Q.providerId==="microsoft")return dn0(Q);throw Error(`Unsupported provider: ${Q.providerId}`)};function pn0(Q){return Q.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var pG0=["labs","hub","studio","workspace","systems","core","cloud","works"],cG0=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];function cn0(){let Q=Math.floor(Math.random()*cG0.length),J=Math.floor(Math.random()*pG0.length),X=cG0[Q]??"deco",Y=pG0[J]??"studio";return`${X}-${Y}`}var nn0=Object.values(GS()).map((Q)=>Q.map((J)=>J.name)).flat(),rn0={...mP,self:["*",...nn0]},OO=XX(rn0),in0=OO.newRole({self:["*"],...BF.statements}),an0=OO.newRole({self:["*"],...BF.statements}),on0=OO.newRole({self:["*"],...BF.statements}),nG0=Object.values(GS()).map((Q)=>Q.map((J)=>`self:${J.name}`)).flat(),o5=rk.auth,rG0=void 0;if(o5.inviteEmailProviderId&&o5.emailProviders&&o5.emailProviders.length>0){let Q=Vw(o5.emailProviders,o5.inviteEmailProviderId);if(Q){let J=Fw(Q);rG0=async(X)=>{let Y=X.inviter.user?.name||X.inviter.user?.email,W=`${process.env.BASE_URL||"http://localhost:3000"}/auth/accept-invitation?invitationId=${X.invitation.id}`;await J({to:X.email,subject:`Invitation to join ${X.organization.name}`,html:`
|
|
1023
1023
|
<h2>You've been invited!</h2>
|
|
1024
1024
|
<p>${Y} has invited you to join <strong>${X.organization.name}</strong>.</p>
|
|
1025
1025
|
<p><a href="${W}">Click here to accept the invitation</a></p>
|
package/dist/server/server.js
CHANGED
|
@@ -1061,7 +1061,7 @@ Please refer to the documentation here: https://better-auth.com/docs/plugins/org
|
|
|
1061
1061
|
</script>
|
|
1062
1062
|
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference" ${G}></script>
|
|
1063
1063
|
</body>
|
|
1064
|
-
</html>`},H00=(Q)=>{let J=Q?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:l0("/open-api/generate-schema",{method:"GET"},async(X)=>{let G=await ae0(X.context,X.context.options);return X.json(G)}),openAPIReference:l0(J,{method:"GET",metadata:{isAction:!1}},async(X)=>{if(Q?.disableDefaultReference)throw new c("NOT_FOUND");let G=await ae0(X.context,X.context.options);return new Response(bU4(G,Q?.theme,Q?.nonce),{headers:{"Content-Type":"text/html"}})})}}};FQ();I7();Q9();p9();H4();var pO6=s4(async()=>{return{}}),cO6=s4({use:[Z8]},async(Q)=>{return{session:Q.context.session}}),nO6=j6({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role"});var iO6=Number.POSITIVE_INFINITY;var se0=C(),gU4=S1(["pending","accepted","rejected","canceled"]).default("pending"),rO6=J0({id:C().default(V9),name:C(),slug:C(),logo:C().nullish().optional(),metadata:D1(C(),EX()).or(C().transform((Q)=>JSON.parse(Q))).optional(),createdAt:r1()}),aO6=J0({id:C().default(V9),organizationId:C(),userId:b1.string(),role:se0,createdAt:r1().default(()=>new Date)}),oO6=J0({id:C().default(V9),organizationId:C(),email:C(),role:se0,status:gU4,teamId:C().nullish(),inviterId:C(),expiresAt:r1(),createdAt:r1().default(()=>new Date)}),sO6=J0({id:C().default(V9),name:C().min(1),organizationId:C(),createdAt:r1(),updatedAt:r1().optional()}),tO6=J0({id:C().default(V9),teamId:C(),userId:C(),createdAt:r1().default(()=>new Date)}),eO6=J0({id:C().default(V9),organizationId:C(),role:C(),permission:D1(C(),F1(C())),createdAt:r1().default(()=>new Date),updatedAt:r1().optional()}),oe0=["admin","member","owner"],QD6=N8([S1(oe0),F1(S1(oe0))]);M8();Q9();p9();var qD6=j6({INVALID_PHONE_NUMBER:"Invalid phone number",PHONE_NUMBER_EXIST:"Phone number already exists",PHONE_NUMBER_NOT_EXIST:"phone number isn't registered",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found",OTP_EXPIRED:"OTP expired",INVALID_OTP:"Invalid OTP",PHONE_NUMBER_NOT_VERIFIED:"Phone number not verified",PHONE_NUMBER_CANNOT_BE_UPDATED:"Phone number cannot be updated",SEND_OTP_NOT_IMPLEMENTED:"sendOTP not implemented",TOO_MANY_ATTEMPTS:"Too many attempts"});M8();VQ();Q9();p9();u9();s6();var uU4=j6({OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code",INVALID_CODE:"Invalid code",TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:"Too many attempts. Please request a new code.",INVALID_TWO_FACTOR_COOKIE:"Invalid two factor cookie"});Q9();p9();var mU4=j6({INVALID_USERNAME_OR_PASSWORD:"Invalid username or password",EMAIL_NOT_VERIFIED:"Email not verified",UNEXPECTED_ERROR:"Unexpected error",USERNAME_IS_ALREADY_TAKEN:"Username is already taken. Please try another.",USERNAME_TOO_SHORT:"Username is too short",USERNAME_TOO_LONG:"Username is too long",INVALID_USERNAME:"Username is invalid",INVALID_DISPLAY_USERNAME:"Display username is invalid"});var TH={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"};import{existsSync as te0,readFileSync as ee0}from"fs";var cS={emailAndPassword:{enabled:!0}},Q01="./config.json",J01="./auth-config.json";function lU4(){if(te0(Q01))try{let Q=ee0(Q01,"utf-8"),J=JSON.parse(Q);return{auth:cS,monitoring:TH,...J}}catch{return{auth:cS,monitoring:TH}}if(te0(J01))try{let Q=ee0(J01,"utf-8");return{auth:JSON.parse(Q),monitoring:TH}}catch{return{auth:cS,monitoring:TH}}return{auth:cS,monitoring:TH}}var nS=lU4();function X01(){return{...TH,...nS.monitoring}}import{existsSync as _D4,mkdirSync as yD4}from"fs";import{Kysely as A41,PostgresDialect as T41,sql as M41}from"kysely";import{BunWorkerDialect as E41}from"kysely-bun-worker";import*as j41 from"path";var vX=p4(u00(),1),KP6=vX.default.Client,p00=vX.default.Pool,ZP6=vX.default.Connection,HP6=vX.default.types,qP6=vX.default.Query,FP6=vX.default.DatabaseError,VP6=vX.default.escapeIdentifier,zP6=vX.default.escapeLiteral,UP6=vX.default.Result,NP6=vX.default.TypeOverrides,BP6=vX.default.defaults;function hD4(Q){let J=new p00({connectionString:Q.connectionString,max:Q.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1}),X=new T41({pool:J});return{type:"postgres",db:new A41({dialect:X}),pool:J}}function I41(Q){if(Q===":memory:")return":memory:";if(Q.includes("://"))return new URL(Q).pathname;return Q}function R41(Q){if(Q!==":memory:"&&Q!=="/"&&Q){let J=Q.substring(0,Q.lastIndexOf("/"));if(J&&J!=="/"&&!_D4(J))try{yD4(J,{recursive:!0})}catch{return console.warn(`Failed to create directory ${J}, using in-memory database`),":memory:"}}return Q}function fD4(Q){let J=I41(Q.connectionString);J=R41(J);let X=new E41({url:J||":memory:"}),G=new A41({dialect:X});if(J!==":memory:"&&Q.options?.enableWAL!==!1)M41`PRAGMA journal_mode = WAL;`.execute(G).catch(()=>{});if(J!==":memory:"){let Y=Q.options?.busyTimeout||5000;M41`PRAGMA busy_timeout = ${Y};`.execute(G).catch(()=>{})}return{type:"sqlite",db:G}}function C41(Q){let J=Q||"file:./data/mesh.db";if(J===":memory:")return{type:"sqlite",connectionString:":memory:"};J=J.startsWith("/")?`file://${J}`:J;let X=URL.canParse(J)?new URL(J):null,G=X?.protocol.replace(":","")??J.split("://")[0];switch(G){case"postgres":case"postgresql":return{type:"postgres",connectionString:J};case"sqlite":case"file":if(!X?.pathname)throw Error("Invalid database URL: "+J);return{type:"sqlite",connectionString:X.pathname};default:throw Error(`Unsupported database protocol: ${G}. Supported protocols: postgres://, postgresql://, sqlite://, file://`)}}function n00(){return process.env.DATABASE_URL||`file:${j41.join(process.cwd(),"data/mesh.db")}`}function S41(Q){let J=C41(Q);if(J.type==="postgres")return new T41({pool:new p00({connectionString:J.connectionString,max:J.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1})});let X=I41(J.connectionString);return X=R41(X),new E41({url:X||":memory:"})}function bD4(Q){let J=C41(Q);if(J.type==="postgres")return hD4(J);return fD4(J)}var c00=null;function Gv(){if(!c00)c00=bD4(n00());return c00}class i00{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:J,subject:X,html:G}){let Y=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:Q,from:J,subject:X,html:G})});if(!Y.ok)throw Error(`Failed to send email: ${Y.statusText}`)}}class r00{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:J,subject:X,html:G}){let Y=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:Q}]}],from:{email:J},subject:X,content:[{type:"text/html",value:G}]})});if(!Y.ok){let W=await Y.text();throw Error(`Failed to send email via SendGrid: ${Y.statusText} - ${W}`)}}}var xD4=(Q)=>{let J=new i00(Q.config.apiKey);return async({to:X,subject:G,html:Y})=>{await J.sendEmail({to:X,from:Q.config.fromEmail,subject:G,html:Y})}},gD4=(Q)=>{let J=new r00(Q.config.apiKey);return async({to:X,subject:G,html:Y})=>{await J.sendEmail({to:X,from:Q.config.fromEmail,subject:G,html:Y})}},uD4={resend:xD4,sendgrid:gD4};function Wv(Q){let J=uD4[Q.provider];if(!J)throw Error(`Unknown email provider: ${Q.provider}`);return J(Q)}function $v(Q,J){return Q.find((X)=>X.id===J)}var v41=(Q,J)=>{let X=$v(J,Q.emailProviderId);if(!X)throw Error(`Email provider with id '${Q.emailProviderId}' not found`);let G=Wv(X);return{sendMagicLink:async({email:Y,url:W})=>{await G({to:Y,subject:"Magic Link",html:`<p>Click <a href="${W}">here</a> to login</p>`})}}};IH();import{createCipheriv as mD4,createDecipheriv as lD4,randomBytes as y41}from"crypto";var h41="aes-256-gcm",Bw=16,f41=16,b41=32;class Ow{key;constructor(Q){if(Buffer.from(Q,"base64").length===b41)this.key=Buffer.from(Q,"base64");else{let J=E0("crypto");this.key=J.createHash("sha256").update(Q).digest()}}async encrypt(Q){let J=y41(Bw),X=mD4(h41,this.key,J),G=X.update(Q,"utf8");G=Buffer.concat([G,X.final()]);let Y=X.getAuthTag();return Buffer.concat([J,Y,G]).toString("base64")}async decrypt(Q){let J=Buffer.from(Q,"base64"),X=J.subarray(0,Bw),G=J.subarray(Bw,Bw+f41),Y=J.subarray(Bw+f41),W=lD4(h41,this.key,X);W.setAuthTag(G);let $=W.update(Y);return $=Buffer.concat([$,W.final()]),$.toString("utf8")}static generateKey(){return y41(b41).toString("base64")}}import{webcrypto as g41}from"crypto";var x41="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var dD4=128,RH,hz;function pD4(Q){if(!RH||RH.length<Q)RH=Buffer.allocUnsafe(Q*dD4),g41.getRandomValues(RH),hz=0;else if(hz+Q>RH.length)g41.getRandomValues(RH),hz=0;hz+=Q}function u41(Q=21){pD4(Q|=0);let J="";for(let X=hz-Q;X<hz;X++)J+=x41[RH[X]&63];return J}function l7(Q){return`${Q}_${u41()}`}var cD4=["connection_headers","oauth_config","configuration_scopes","metadata","tools","bindings"];class Dw{db;vault;constructor(Q,J){this.db=Q;this.vault=J}async create(Q){let J=Q.id??l7("conn"),X=new Date().toISOString();if(await this.findById(J))return this.update(J,Q);let Y=await this.serializeConnection({...Q,id:Q.id??J,status:"active",created_at:X,updated_at:X});await this.db.insertInto("connections").values(Y).execute();let W=await this.findById(J);if(!W)throw Error(`Failed to create connection with id: ${J}`);return W}async findById(Q,J){let X=this.db.selectFrom("connections").selectAll().where("id","=",Q);if(J)X=X.where("organization_id","=",J);let G=await X.executeTakeFirst();return G?this.deserializeConnection(G):null}async list(Q){let J=await this.db.selectFrom("connections").selectAll().where("organization_id","=",Q).execute();return Promise.all(J.map((X)=>this.deserializeConnection(X)))}async update(Q,J){if(Object.keys(J).length===0){let Y=await this.findById(Q);if(!Y)throw Error("Connection not found");return Y}let X=await this.serializeConnection({...J,updated_at:new Date().toISOString()});await this.db.updateTable("connections").set(X).where("id","=",Q).execute();let G=await this.findById(Q);if(!G)throw Error("Connection not found after update");return G}async delete(Q){await this.db.deleteFrom("connections").where("id","=",Q).execute()}async testConnection(Q,J){let X=await this.findById(Q);if(!X)throw Error("Connection not found");let G=Date.now();try{let Y=await fetch(X.connection_url,{method:"POST",headers:{"Content-Type":"application/json",...X.connection_token&&{Authorization:`Bearer ${X.connection_token}`},...J},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})});return{healthy:Y.ok||Y.status===404,latencyMs:Date.now()-G}}catch{return{healthy:!1,latencyMs:Date.now()-G}}}async serializeConnection(Q){let J={};for(let[X,G]of Object.entries(Q)){if(G===void 0)continue;if(X==="connection_token"&&G)J[X]=await this.vault.encrypt(G);else if(X==="configuration_state"&&G){let Y=JSON.stringify(G);J[X]=await this.vault.encrypt(Y)}else if(cD4.includes(X))J[X]=G?JSON.stringify(G):null;else J[X]=G}return J}async deserializeConnection(Q){let J=null;if(Q.connection_token)try{J=await this.vault.decrypt(Q.connection_token)}catch(Y){console.error("Failed to decrypt connection token:",Y)}let X=null;if(Q.configuration_state)try{let Y=await this.vault.decrypt(Q.configuration_state);X=JSON.parse(Y)}catch(Y){console.error("Failed to decrypt configuration state:",Y)}let G=(Y)=>{if(Y===null)return null;if(typeof Y==="string")try{return JSON.parse(Y)}catch{return null}return Y};return{id:Q.id,organization_id:Q.organization_id,created_by:Q.created_by,title:Q.title,description:Q.description,icon:Q.icon,app_name:Q.app_name,app_id:Q.app_id,connection_type:Q.connection_type,connection_url:Q.connection_url,connection_token:J,connection_headers:G(Q.connection_headers),oauth_config:G(Q.oauth_config),configuration_state:X,configuration_scopes:G(Q.configuration_scopes),metadata:G(Q.metadata),tools:G(Q.tools),bindings:G(Q.bindings),status:Q.status,created_at:Q.created_at,updated_at:Q.updated_at}}}class Lw{db;constructor(Q){this.db=Q}async create(Q,J,X){let G=l7("gw"),Y=new Date().toISOString();if(X.isDefault)return await this.db.transaction().execute(async($)=>{if(await $.updateTable("gateways").set({is_default:0,updated_at:Y,updated_by:J}).where("organization_id","=",Q).where("is_default","=",1).execute(),await $.insertInto("gateways").values({id:G,organization_id:Q,title:X.title,description:X.description??null,tool_selection_strategy:X.toolSelectionStrategy??"passthrough",tool_selection_mode:X.toolSelectionMode??"inclusion",icon:X.icon??null,status:X.status??"active",is_default:1,created_at:Y,updated_at:Y,created_by:J,updated_by:null}).execute(),X.connections.length>0)await $.insertInto("gateway_connections").values(X.connections.map((Z)=>({id:l7("gwc"),gateway_id:G,connection_id:Z.connectionId,selected_tools:Z.selectedTools?JSON.stringify(Z.selectedTools):null,created_at:Y}))).execute();let K=await this.findByIdInternal($,G);if(!K)throw Error(`Failed to create gateway with id: ${G}`);return K});if(await this.db.insertInto("gateways").values({id:G,organization_id:Q,title:X.title,description:X.description??null,tool_selection_strategy:X.toolSelectionStrategy??"passthrough",tool_selection_mode:X.toolSelectionMode??"inclusion",icon:X.icon??null,status:X.status??"active",is_default:0,created_at:Y,updated_at:Y,created_by:J,updated_by:null}).execute(),X.connections.length>0)await this.db.insertInto("gateway_connections").values(X.connections.map(($)=>({id:l7("gwc"),gateway_id:G,connection_id:$.connectionId,selected_tools:$.selectedTools?JSON.stringify($.selectedTools):null,created_at:Y}))).execute();let W=await this.findById(G);if(!W)throw Error(`Failed to create gateway with id: ${G}`);return W}async findById(Q){return this.findByIdInternal(this.db,Q)}async findByIdInternal(Q,J){let X=await Q.selectFrom("gateways").selectAll().where("id","=",J).executeTakeFirst();if(!X)return null;let G=await Q.selectFrom("gateway_connections").selectAll().where("gateway_id","=",J).execute();return this.deserializeGatewayWithConnections(X,G)}async list(Q){let J=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).execute(),X=J.map((W)=>W.id);if(X.length===0)return[];let G=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",X).execute(),Y=new Map;for(let W of G){let $=Y.get(W.gateway_id)??[];$.push(W),Y.set(W.gateway_id,$)}return J.map((W)=>this.deserializeGatewayWithConnections(W,Y.get(W.id)??[]))}async listByConnectionId(Q,J){let G=(await this.db.selectFrom("gateway_connections").select("gateway_id").where("connection_id","=",J).execute()).map((Z)=>Z.gateway_id);if(G.length===0)return[];let Y=await this.db.selectFrom("gateways").selectAll().where("id","in",G).where("organization_id","=",Q).execute();if(Y.length===0)return[];let W=Y.map((Z)=>Z.id),$=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",W).execute(),K=new Map;for(let Z of $){let H=K.get(Z.gateway_id)??[];H.push(Z),K.set(Z.gateway_id,H)}return Y.map((Z)=>this.deserializeGatewayWithConnections(Z,K.get(Z.id)??[]))}async update(Q,J,X){let G=new Date().toISOString(),Y={updated_at:G,updated_by:J};if(X.title!==void 0)Y.title=X.title;if(X.description!==void 0)Y.description=X.description;if(X.toolSelectionStrategy!==void 0)Y.tool_selection_strategy=X.toolSelectionStrategy;if(X.toolSelectionMode!==void 0)Y.tool_selection_mode=X.toolSelectionMode;if(X.icon!==void 0)Y.icon=X.icon;if(X.status!==void 0)Y.status=X.status;if(X.isDefault===!1)Y.is_default=0;if(X.isDefault===!0)Y.is_default=1;if(X.isDefault===!0){let $=await this.findById(Q);if(!$)throw Error(`Gateway not found: ${Q}`);await this.db.transaction().execute(async(K)=>{if(await K.updateTable("gateways").set({is_default:0,updated_at:G,updated_by:J}).where("organization_id","=",$.organizationId).where("is_default","=",1).execute(),await K.updateTable("gateways").set(Y).where("id","=",Q).execute(),X.connections!==void 0){if(await K.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),X.connections.length>0)await K.insertInto("gateway_connections").values(X.connections.map((Z)=>({id:l7("gwc"),gateway_id:Q,connection_id:Z.connectionId,selected_tools:Z.selectedTools?JSON.stringify(Z.selectedTools):null,created_at:G}))).execute()}})}else if(await this.db.updateTable("gateways").set(Y).where("id","=",Q).execute(),X.connections!==void 0){if(await this.db.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),X.connections.length>0)await this.db.insertInto("gateway_connections").values(X.connections.map(($)=>({id:l7("gwc"),gateway_id:Q,connection_id:$.connectionId,selected_tools:$.selectedTools?JSON.stringify($.selectedTools):null,created_at:G}))).execute()}let W=await this.findById(Q);if(!W)throw Error("Gateway not found after update");return W}async delete(Q){await this.db.deleteFrom("gateways").where("id","=",Q).execute()}async getDefaultByOrgId(Q){let J=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).where("is_default","=",1).executeTakeFirst();if(!J)return null;let X=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","=",J.id).execute();return this.deserializeGatewayWithConnections(J,X)}async getDefaultByOrgSlug(Q){let J=await this.db.selectFrom("organization").select("id").where("slug","=",Q).executeTakeFirst();if(!J)return null;return this.getDefaultByOrgId(J.id)}async setDefault(Q,J){let X=await this.findById(Q);if(!X)throw Error(`Gateway not found: ${Q}`);let G=new Date().toISOString();await this.db.transaction().execute(async(W)=>{await W.updateTable("gateways").set({is_default:0,updated_at:G,updated_by:J}).where("organization_id","=",X.organizationId).where("is_default","=",1).execute(),await W.updateTable("gateways").set({is_default:1,updated_at:G,updated_by:J}).where("id","=",Q).execute()});let Y=await this.findById(Q);if(!Y)throw Error("Gateway not found after setting default");return Y}deserializeGatewayWithConnections(Q,J){return{...this.deserializeGateway(Q),connections:J.map((G)=>({connectionId:G.connection_id,selectedTools:this.parseJson(G.selected_tools)}))}}deserializeGateway(Q){return{id:Q.id,organizationId:Q.organization_id,title:Q.title,description:Q.description,toolSelectionStrategy:this.parseToolSelectionStrategy(Q.tool_selection_strategy),toolSelectionMode:this.parseToolSelectionMode(Q.tool_selection_mode),icon:Q.icon,status:Q.status,isDefault:Q.is_default===1,createdAt:Q.created_at,updatedAt:Q.updated_at,createdBy:Q.created_by,updatedBy:Q.updated_by}}parseToolSelectionStrategy(Q){if(Q==="smart_tool_selection")return"smart_tool_selection";if(Q==="code_execution")return"code_execution";return"passthrough"}parseToolSelectionMode(Q){if(Q==="exclusion")return"exclusion";return"inclusion"}parseJson(Q){if(Q===null)return null;if(typeof Q==="string")try{return JSON.parse(Q)}catch{return null}return Q}}Zk();Dk();function LE4(){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (Z_(),mX1));return Q.map((J)=>{return{name:J.name,inputSchema:XU(J.inputSchema),outputSchema:J.outputSchema?XU(J.outputSchema):void 0,description:J.description}})},data:_41(process.env.BASE_URL||"http://localhost:3000")},{data:k41()}]}async function lX1(Q,J){try{let X=Gv(),G=new Ow(process.env.ENCRYPTION_KEY||""),Y=new Dw(X.db,G),W=new Lw(X.db),$=LE4(),K=[];await Promise.all($.map(async(Z)=>{let H=null;if(Z.permissions)H=(await TW.api.createApiKey({body:{name:`${Z.data.app_name??crypto.randomUUID()}-mcp`,userId:J,permissions:Z.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Q},purpose:"default-org-connections"}}}))?.key;let q=await Z.getTools?.()??await JU({id:"pending",title:Z.data.title,connection_url:Z.data.connection_url,connection_token:Z.data.connection_token,connection_headers:Z.data.connection_headers}).catch(()=>null),F=Z.data.id?`${Q}_${Z.data.id}`:void 0,V=await Y.create({...Z.data,id:F,tools:q,organization_id:Q,created_by:J,connection_token:Z.data.connection_token??H});K.push(V.id)})),await W.create(Q,J,{title:"Default Gateway",description:"Auto-created gateway that includes all connections",toolSelectionStrategy:"passthrough",toolSelectionMode:"exclusion",status:"active",isDefault:!0,connections:K.map((Z)=>({connectionId:Z}))})}catch(X){console.error("Error creating default MCP connections:",X)}}var p80=["owner","admin","user"],dX1=["owner","admin"];var wE4=(Q)=>{return{defaultSSO:[{domain:Q.domain,providerId:Q.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Q.MS_CLIENT_ID,clientSecret:Q.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Q.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},pX1=(Q)=>{if(Q.providerId==="microsoft")return wE4(Q);throw Error(`Unsupported provider: ${Q.providerId}`)};function PE4(Q){return Q.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var cX1=["labs","hub","studio","workspace","systems","core","cloud","works"],nX1=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];function ME4(){let Q=Math.floor(Math.random()*nX1.length),J=Math.floor(Math.random()*cX1.length),X=nX1[Q]??"deco",G=cX1[J]??"studio";return`${X}-${G}`}var AE4=Object.values(dB()).map((Q)=>Q.map((J)=>J.name)).flat(),TE4={...vS,self:["*",...AE4]},H_=m7(TE4),EE4=H_.newRole({self:["*"],...tL.statements}),jE4=H_.newRole({self:["*"],...tL.statements}),IE4=H_.newRole({self:["*"],...tL.statements}),iX1=Object.values(dB()).map((Q)=>Q.map((J)=>`self:${J.name}`)).flat(),G9=nS.auth,rX1=void 0;if(G9.inviteEmailProviderId&&G9.emailProviders&&G9.emailProviders.length>0){let Q=$v(G9.emailProviders,G9.inviteEmailProviderId);if(Q){let J=Wv(Q);rX1=async(X)=>{let G=X.inviter.user?.name||X.inviter.user?.email,Y=`${process.env.BASE_URL||"http://localhost:3000"}/auth/accept-invitation?invitationId=${X.invitation.id}`;await J({to:X.email,subject:`Invitation to join ${X.organization.name}`,html:`
|
|
1064
|
+
</html>`},H00=(Q)=>{let J=Q?.path??"/reference";return{id:"open-api",endpoints:{generateOpenAPISchema:l0("/open-api/generate-schema",{method:"GET"},async(X)=>{let G=await ae0(X.context,X.context.options);return X.json(G)}),openAPIReference:l0(J,{method:"GET",metadata:{isAction:!1}},async(X)=>{if(Q?.disableDefaultReference)throw new c("NOT_FOUND");let G=await ae0(X.context,X.context.options);return new Response(bU4(G,Q?.theme,Q?.nonce),{headers:{"Content-Type":"text/html"}})})}}};FQ();I7();Q9();p9();H4();var pO6=s4(async()=>{return{}}),cO6=s4({use:[Z8]},async(Q)=>{return{session:Q.context.session}}),nO6=j6({YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_ORGANIZATION:"You are not allowed to create a new organization",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_ORGANIZATIONS:"You have reached the maximum number of organizations",ORGANIZATION_ALREADY_EXISTS:"Organization already exists",ORGANIZATION_SLUG_ALREADY_TAKEN:"Organization slug already taken",ORGANIZATION_NOT_FOUND:"Organization not found",USER_IS_NOT_A_MEMBER_OF_THE_ORGANIZATION:"User is not a member of the organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_ORGANIZATION:"You are not allowed to update this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_ORGANIZATION:"You are not allowed to delete this organization",NO_ACTIVE_ORGANIZATION:"No active organization",USER_IS_ALREADY_A_MEMBER_OF_THIS_ORGANIZATION:"User is already a member of this organization",MEMBER_NOT_FOUND:"Member not found",ROLE_NOT_FOUND:"Role not found",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM:"You are not allowed to create a new team",TEAM_ALREADY_EXISTS:"Team already exists",TEAM_NOT_FOUND:"Team not found",YOU_CANNOT_LEAVE_THE_ORGANIZATION_AS_THE_ONLY_OWNER:"You cannot leave the organization as the only owner",YOU_CANNOT_LEAVE_THE_ORGANIZATION_WITHOUT_AN_OWNER:"You cannot leave the organization without an owner",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_MEMBER:"You are not allowed to delete this member",YOU_ARE_NOT_ALLOWED_TO_INVITE_USERS_TO_THIS_ORGANIZATION:"You are not allowed to invite users to this organization",USER_IS_ALREADY_INVITED_TO_THIS_ORGANIZATION:"User is already invited to this organization",INVITATION_NOT_FOUND:"Invitation not found",YOU_ARE_NOT_THE_RECIPIENT_OF_THE_INVITATION:"You are not the recipient of the invitation",EMAIL_VERIFICATION_REQUIRED_BEFORE_ACCEPTING_OR_REJECTING_INVITATION:"Email verification required before accepting or rejecting invitation",YOU_ARE_NOT_ALLOWED_TO_CANCEL_THIS_INVITATION:"You are not allowed to cancel this invitation",INVITER_IS_NO_LONGER_A_MEMBER_OF_THE_ORGANIZATION:"Inviter is no longer a member of the organization",YOU_ARE_NOT_ALLOWED_TO_INVITE_USER_WITH_THIS_ROLE:"You are not allowed to invite a user with this role",FAILED_TO_RETRIEVE_INVITATION:"Failed to retrieve invitation",YOU_HAVE_REACHED_THE_MAXIMUM_NUMBER_OF_TEAMS:"You have reached the maximum number of teams",UNABLE_TO_REMOVE_LAST_TEAM:"Unable to remove last team",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_MEMBER:"You are not allowed to update this member",ORGANIZATION_MEMBERSHIP_LIMIT_REACHED:"Organization membership limit reached",YOU_ARE_NOT_ALLOWED_TO_CREATE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to create teams in this organization",YOU_ARE_NOT_ALLOWED_TO_DELETE_TEAMS_IN_THIS_ORGANIZATION:"You are not allowed to delete teams in this organization",YOU_ARE_NOT_ALLOWED_TO_UPDATE_THIS_TEAM:"You are not allowed to update this team",YOU_ARE_NOT_ALLOWED_TO_DELETE_THIS_TEAM:"You are not allowed to delete this team",INVITATION_LIMIT_REACHED:"Invitation limit reached",TEAM_MEMBER_LIMIT_REACHED:"Team member limit reached",USER_IS_NOT_A_MEMBER_OF_THE_TEAM:"User is not a member of the team",YOU_CAN_NOT_ACCESS_THE_MEMBERS_OF_THIS_TEAM:"You are not allowed to list the members of this team",YOU_DO_NOT_HAVE_AN_ACTIVE_TEAM:"You do not have an active team",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_NEW_TEAM_MEMBER:"You are not allowed to create a new member",YOU_ARE_NOT_ALLOWED_TO_REMOVE_A_TEAM_MEMBER:"You are not allowed to remove a team member",YOU_ARE_NOT_ALLOWED_TO_ACCESS_THIS_ORGANIZATION:"You are not allowed to access this organization as an owner",YOU_ARE_NOT_A_MEMBER_OF_THIS_ORGANIZATION:"You are not a member of this organization",MISSING_AC_INSTANCE:"Dynamic Access Control requires a pre-defined ac instance on the server auth plugin. Read server logs for more information",YOU_MUST_BE_IN_AN_ORGANIZATION_TO_CREATE_A_ROLE:"You must be in an organization to create a role",YOU_ARE_NOT_ALLOWED_TO_CREATE_A_ROLE:"You are not allowed to create a role",YOU_ARE_NOT_ALLOWED_TO_UPDATE_A_ROLE:"You are not allowed to update a role",YOU_ARE_NOT_ALLOWED_TO_DELETE_A_ROLE:"You are not allowed to delete a role",YOU_ARE_NOT_ALLOWED_TO_READ_A_ROLE:"You are not allowed to read a role",YOU_ARE_NOT_ALLOWED_TO_LIST_A_ROLE:"You are not allowed to list a role",YOU_ARE_NOT_ALLOWED_TO_GET_A_ROLE:"You are not allowed to get a role",TOO_MANY_ROLES:"This organization has too many roles",INVALID_RESOURCE:"The provided permission includes an invalid resource",ROLE_NAME_IS_ALREADY_TAKEN:"That role name is already taken",CANNOT_DELETE_A_PRE_DEFINED_ROLE:"Cannot delete a pre-defined role"});var iO6=Number.POSITIVE_INFINITY;var se0=C(),gU4=S1(["pending","accepted","rejected","canceled"]).default("pending"),rO6=J0({id:C().default(V9),name:C(),slug:C(),logo:C().nullish().optional(),metadata:D1(C(),EX()).or(C().transform((Q)=>JSON.parse(Q))).optional(),createdAt:r1()}),aO6=J0({id:C().default(V9),organizationId:C(),userId:b1.string(),role:se0,createdAt:r1().default(()=>new Date)}),oO6=J0({id:C().default(V9),organizationId:C(),email:C(),role:se0,status:gU4,teamId:C().nullish(),inviterId:C(),expiresAt:r1(),createdAt:r1().default(()=>new Date)}),sO6=J0({id:C().default(V9),name:C().min(1),organizationId:C(),createdAt:r1(),updatedAt:r1().optional()}),tO6=J0({id:C().default(V9),teamId:C(),userId:C(),createdAt:r1().default(()=>new Date)}),eO6=J0({id:C().default(V9),organizationId:C(),role:C(),permission:D1(C(),F1(C())),createdAt:r1().default(()=>new Date),updatedAt:r1().optional()}),oe0=["admin","member","owner"],QD6=N8([S1(oe0),F1(S1(oe0))]);M8();Q9();p9();var qD6=j6({INVALID_PHONE_NUMBER:"Invalid phone number",PHONE_NUMBER_EXIST:"Phone number already exists",PHONE_NUMBER_NOT_EXIST:"phone number isn't registered",INVALID_PHONE_NUMBER_OR_PASSWORD:"Invalid phone number or password",UNEXPECTED_ERROR:"Unexpected error",OTP_NOT_FOUND:"OTP not found",OTP_EXPIRED:"OTP expired",INVALID_OTP:"Invalid OTP",PHONE_NUMBER_NOT_VERIFIED:"Phone number not verified",PHONE_NUMBER_CANNOT_BE_UPDATED:"Phone number cannot be updated",SEND_OTP_NOT_IMPLEMENTED:"sendOTP not implemented",TOO_MANY_ATTEMPTS:"Too many attempts"});M8();VQ();Q9();p9();u9();s6();var uU4=j6({OTP_NOT_ENABLED:"OTP not enabled",OTP_HAS_EXPIRED:"OTP has expired",TOTP_NOT_ENABLED:"TOTP not enabled",TWO_FACTOR_NOT_ENABLED:"Two factor isn't enabled",BACKUP_CODES_NOT_ENABLED:"Backup codes aren't enabled",INVALID_BACKUP_CODE:"Invalid backup code",INVALID_CODE:"Invalid code",TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:"Too many attempts. Please request a new code.",INVALID_TWO_FACTOR_COOKIE:"Invalid two factor cookie"});Q9();p9();var mU4=j6({INVALID_USERNAME_OR_PASSWORD:"Invalid username or password",EMAIL_NOT_VERIFIED:"Email not verified",UNEXPECTED_ERROR:"Unexpected error",USERNAME_IS_ALREADY_TAKEN:"Username is already taken. Please try another.",USERNAME_TOO_SHORT:"Username is too short",USERNAME_TOO_LONG:"Username is too long",INVALID_USERNAME:"Username is invalid",INVALID_DISPLAY_USERNAME:"Display username is invalid"});var TH={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"};import{existsSync as te0,readFileSync as ee0}from"fs";var cS={emailAndPassword:{enabled:!0}},Q01=process.env.CONFIG_PATH||"./config.json",J01=process.env.AUTH_CONFIG_PATH||"./auth-config.json";function lU4(){if(te0(Q01))try{let Q=ee0(Q01,"utf-8"),J=JSON.parse(Q);return{auth:cS,monitoring:TH,...J}}catch{return{auth:cS,monitoring:TH}}if(te0(J01))try{let Q=ee0(J01,"utf-8");return{auth:JSON.parse(Q),monitoring:TH}}catch{return{auth:cS,monitoring:TH}}return{auth:cS,monitoring:TH}}var nS=lU4();function X01(){return{...TH,...nS.monitoring}}import{existsSync as _D4,mkdirSync as yD4}from"fs";import{Kysely as A41,PostgresDialect as T41,sql as M41}from"kysely";import{BunWorkerDialect as E41}from"kysely-bun-worker";import*as j41 from"path";var vX=p4(u00(),1),KP6=vX.default.Client,p00=vX.default.Pool,ZP6=vX.default.Connection,HP6=vX.default.types,qP6=vX.default.Query,FP6=vX.default.DatabaseError,VP6=vX.default.escapeIdentifier,zP6=vX.default.escapeLiteral,UP6=vX.default.Result,NP6=vX.default.TypeOverrides,BP6=vX.default.defaults;function hD4(Q){let J=new p00({connectionString:Q.connectionString,max:Q.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1}),X=new T41({pool:J});return{type:"postgres",db:new A41({dialect:X}),pool:J}}function I41(Q){if(Q===":memory:")return":memory:";if(Q.includes("://"))return new URL(Q).pathname;return Q}function R41(Q){if(Q!==":memory:"&&Q!=="/"&&Q){let J=Q.substring(0,Q.lastIndexOf("/"));if(J&&J!=="/"&&!_D4(J))try{yD4(J,{recursive:!0})}catch{return console.warn(`Failed to create directory ${J}, using in-memory database`),":memory:"}}return Q}function fD4(Q){let J=I41(Q.connectionString);J=R41(J);let X=new E41({url:J||":memory:"}),G=new A41({dialect:X});if(J!==":memory:"&&Q.options?.enableWAL!==!1)M41`PRAGMA journal_mode = WAL;`.execute(G).catch(()=>{});if(J!==":memory:"){let Y=Q.options?.busyTimeout||5000;M41`PRAGMA busy_timeout = ${Y};`.execute(G).catch(()=>{})}return{type:"sqlite",db:G}}function C41(Q){let J=Q||"file:./data/mesh.db";if(J===":memory:")return{type:"sqlite",connectionString:":memory:"};J=J.startsWith("/")?`file://${J}`:J;let X=URL.canParse(J)?new URL(J):null,G=X?.protocol.replace(":","")??J.split("://")[0];switch(G){case"postgres":case"postgresql":return{type:"postgres",connectionString:J};case"sqlite":case"file":if(!X?.pathname)throw Error("Invalid database URL: "+J);return{type:"sqlite",connectionString:X.pathname};default:throw Error(`Unsupported database protocol: ${G}. Supported protocols: postgres://, postgresql://, sqlite://, file://`)}}function n00(){return process.env.DATABASE_URL||`file:${j41.join(process.cwd(),"data/mesh.db")}`}function S41(Q){let J=C41(Q);if(J.type==="postgres")return new T41({pool:new p00({connectionString:J.connectionString,max:J.options?.maxConnections||10,ssl:process.env.DATABASE_PG_SSL==="true"?!0:!1})});let X=I41(J.connectionString);return X=R41(X),new E41({url:X||":memory:"})}function bD4(Q){let J=C41(Q);if(J.type==="postgres")return hD4(J);return fD4(J)}var c00=null;function Gv(){if(!c00)c00=bD4(n00());return c00}class i00{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:J,subject:X,html:G}){let Y=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:Q,from:J,subject:X,html:G})});if(!Y.ok)throw Error(`Failed to send email: ${Y.statusText}`)}}class r00{apiKey;constructor(Q){this.apiKey=Q}async sendEmail({to:Q,from:J,subject:X,html:G}){let Y=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:Q}]}],from:{email:J},subject:X,content:[{type:"text/html",value:G}]})});if(!Y.ok){let W=await Y.text();throw Error(`Failed to send email via SendGrid: ${Y.statusText} - ${W}`)}}}var xD4=(Q)=>{let J=new i00(Q.config.apiKey);return async({to:X,subject:G,html:Y})=>{await J.sendEmail({to:X,from:Q.config.fromEmail,subject:G,html:Y})}},gD4=(Q)=>{let J=new r00(Q.config.apiKey);return async({to:X,subject:G,html:Y})=>{await J.sendEmail({to:X,from:Q.config.fromEmail,subject:G,html:Y})}},uD4={resend:xD4,sendgrid:gD4};function Wv(Q){let J=uD4[Q.provider];if(!J)throw Error(`Unknown email provider: ${Q.provider}`);return J(Q)}function $v(Q,J){return Q.find((X)=>X.id===J)}var v41=(Q,J)=>{let X=$v(J,Q.emailProviderId);if(!X)throw Error(`Email provider with id '${Q.emailProviderId}' not found`);let G=Wv(X);return{sendMagicLink:async({email:Y,url:W})=>{await G({to:Y,subject:"Magic Link",html:`<p>Click <a href="${W}">here</a> to login</p>`})}}};IH();import{createCipheriv as mD4,createDecipheriv as lD4,randomBytes as y41}from"crypto";var h41="aes-256-gcm",Bw=16,f41=16,b41=32;class Ow{key;constructor(Q){if(Buffer.from(Q,"base64").length===b41)this.key=Buffer.from(Q,"base64");else{let J=E0("crypto");this.key=J.createHash("sha256").update(Q).digest()}}async encrypt(Q){let J=y41(Bw),X=mD4(h41,this.key,J),G=X.update(Q,"utf8");G=Buffer.concat([G,X.final()]);let Y=X.getAuthTag();return Buffer.concat([J,Y,G]).toString("base64")}async decrypt(Q){let J=Buffer.from(Q,"base64"),X=J.subarray(0,Bw),G=J.subarray(Bw,Bw+f41),Y=J.subarray(Bw+f41),W=lD4(h41,this.key,X);W.setAuthTag(G);let $=W.update(Y);return $=Buffer.concat([$,W.final()]),$.toString("utf8")}static generateKey(){return y41(b41).toString("base64")}}import{webcrypto as g41}from"crypto";var x41="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var dD4=128,RH,hz;function pD4(Q){if(!RH||RH.length<Q)RH=Buffer.allocUnsafe(Q*dD4),g41.getRandomValues(RH),hz=0;else if(hz+Q>RH.length)g41.getRandomValues(RH),hz=0;hz+=Q}function u41(Q=21){pD4(Q|=0);let J="";for(let X=hz-Q;X<hz;X++)J+=x41[RH[X]&63];return J}function l7(Q){return`${Q}_${u41()}`}var cD4=["connection_headers","oauth_config","configuration_scopes","metadata","tools","bindings"];class Dw{db;vault;constructor(Q,J){this.db=Q;this.vault=J}async create(Q){let J=Q.id??l7("conn"),X=new Date().toISOString();if(await this.findById(J))return this.update(J,Q);let Y=await this.serializeConnection({...Q,id:Q.id??J,status:"active",created_at:X,updated_at:X});await this.db.insertInto("connections").values(Y).execute();let W=await this.findById(J);if(!W)throw Error(`Failed to create connection with id: ${J}`);return W}async findById(Q,J){let X=this.db.selectFrom("connections").selectAll().where("id","=",Q);if(J)X=X.where("organization_id","=",J);let G=await X.executeTakeFirst();return G?this.deserializeConnection(G):null}async list(Q){let J=await this.db.selectFrom("connections").selectAll().where("organization_id","=",Q).execute();return Promise.all(J.map((X)=>this.deserializeConnection(X)))}async update(Q,J){if(Object.keys(J).length===0){let Y=await this.findById(Q);if(!Y)throw Error("Connection not found");return Y}let X=await this.serializeConnection({...J,updated_at:new Date().toISOString()});await this.db.updateTable("connections").set(X).where("id","=",Q).execute();let G=await this.findById(Q);if(!G)throw Error("Connection not found after update");return G}async delete(Q){await this.db.deleteFrom("connections").where("id","=",Q).execute()}async testConnection(Q,J){let X=await this.findById(Q);if(!X)throw Error("Connection not found");let G=Date.now();try{let Y=await fetch(X.connection_url,{method:"POST",headers:{"Content-Type":"application/json",...X.connection_token&&{Authorization:`Bearer ${X.connection_token}`},...J},body:JSON.stringify({jsonrpc:"2.0",method:"ping",id:1})});return{healthy:Y.ok||Y.status===404,latencyMs:Date.now()-G}}catch{return{healthy:!1,latencyMs:Date.now()-G}}}async serializeConnection(Q){let J={};for(let[X,G]of Object.entries(Q)){if(G===void 0)continue;if(X==="connection_token"&&G)J[X]=await this.vault.encrypt(G);else if(X==="configuration_state"&&G){let Y=JSON.stringify(G);J[X]=await this.vault.encrypt(Y)}else if(cD4.includes(X))J[X]=G?JSON.stringify(G):null;else J[X]=G}return J}async deserializeConnection(Q){let J=null;if(Q.connection_token)try{J=await this.vault.decrypt(Q.connection_token)}catch(Y){console.error("Failed to decrypt connection token:",Y)}let X=null;if(Q.configuration_state)try{let Y=await this.vault.decrypt(Q.configuration_state);X=JSON.parse(Y)}catch(Y){console.error("Failed to decrypt configuration state:",Y)}let G=(Y)=>{if(Y===null)return null;if(typeof Y==="string")try{return JSON.parse(Y)}catch{return null}return Y};return{id:Q.id,organization_id:Q.organization_id,created_by:Q.created_by,title:Q.title,description:Q.description,icon:Q.icon,app_name:Q.app_name,app_id:Q.app_id,connection_type:Q.connection_type,connection_url:Q.connection_url,connection_token:J,connection_headers:G(Q.connection_headers),oauth_config:G(Q.oauth_config),configuration_state:X,configuration_scopes:G(Q.configuration_scopes),metadata:G(Q.metadata),tools:G(Q.tools),bindings:G(Q.bindings),status:Q.status,created_at:Q.created_at,updated_at:Q.updated_at}}}class Lw{db;constructor(Q){this.db=Q}async create(Q,J,X){let G=l7("gw"),Y=new Date().toISOString();if(X.isDefault)return await this.db.transaction().execute(async($)=>{if(await $.updateTable("gateways").set({is_default:0,updated_at:Y,updated_by:J}).where("organization_id","=",Q).where("is_default","=",1).execute(),await $.insertInto("gateways").values({id:G,organization_id:Q,title:X.title,description:X.description??null,tool_selection_strategy:X.toolSelectionStrategy??"passthrough",tool_selection_mode:X.toolSelectionMode??"inclusion",icon:X.icon??null,status:X.status??"active",is_default:1,created_at:Y,updated_at:Y,created_by:J,updated_by:null}).execute(),X.connections.length>0)await $.insertInto("gateway_connections").values(X.connections.map((Z)=>({id:l7("gwc"),gateway_id:G,connection_id:Z.connectionId,selected_tools:Z.selectedTools?JSON.stringify(Z.selectedTools):null,created_at:Y}))).execute();let K=await this.findByIdInternal($,G);if(!K)throw Error(`Failed to create gateway with id: ${G}`);return K});if(await this.db.insertInto("gateways").values({id:G,organization_id:Q,title:X.title,description:X.description??null,tool_selection_strategy:X.toolSelectionStrategy??"passthrough",tool_selection_mode:X.toolSelectionMode??"inclusion",icon:X.icon??null,status:X.status??"active",is_default:0,created_at:Y,updated_at:Y,created_by:J,updated_by:null}).execute(),X.connections.length>0)await this.db.insertInto("gateway_connections").values(X.connections.map(($)=>({id:l7("gwc"),gateway_id:G,connection_id:$.connectionId,selected_tools:$.selectedTools?JSON.stringify($.selectedTools):null,created_at:Y}))).execute();let W=await this.findById(G);if(!W)throw Error(`Failed to create gateway with id: ${G}`);return W}async findById(Q){return this.findByIdInternal(this.db,Q)}async findByIdInternal(Q,J){let X=await Q.selectFrom("gateways").selectAll().where("id","=",J).executeTakeFirst();if(!X)return null;let G=await Q.selectFrom("gateway_connections").selectAll().where("gateway_id","=",J).execute();return this.deserializeGatewayWithConnections(X,G)}async list(Q){let J=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).execute(),X=J.map((W)=>W.id);if(X.length===0)return[];let G=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",X).execute(),Y=new Map;for(let W of G){let $=Y.get(W.gateway_id)??[];$.push(W),Y.set(W.gateway_id,$)}return J.map((W)=>this.deserializeGatewayWithConnections(W,Y.get(W.id)??[]))}async listByConnectionId(Q,J){let G=(await this.db.selectFrom("gateway_connections").select("gateway_id").where("connection_id","=",J).execute()).map((Z)=>Z.gateway_id);if(G.length===0)return[];let Y=await this.db.selectFrom("gateways").selectAll().where("id","in",G).where("organization_id","=",Q).execute();if(Y.length===0)return[];let W=Y.map((Z)=>Z.id),$=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","in",W).execute(),K=new Map;for(let Z of $){let H=K.get(Z.gateway_id)??[];H.push(Z),K.set(Z.gateway_id,H)}return Y.map((Z)=>this.deserializeGatewayWithConnections(Z,K.get(Z.id)??[]))}async update(Q,J,X){let G=new Date().toISOString(),Y={updated_at:G,updated_by:J};if(X.title!==void 0)Y.title=X.title;if(X.description!==void 0)Y.description=X.description;if(X.toolSelectionStrategy!==void 0)Y.tool_selection_strategy=X.toolSelectionStrategy;if(X.toolSelectionMode!==void 0)Y.tool_selection_mode=X.toolSelectionMode;if(X.icon!==void 0)Y.icon=X.icon;if(X.status!==void 0)Y.status=X.status;if(X.isDefault===!1)Y.is_default=0;if(X.isDefault===!0)Y.is_default=1;if(X.isDefault===!0){let $=await this.findById(Q);if(!$)throw Error(`Gateway not found: ${Q}`);await this.db.transaction().execute(async(K)=>{if(await K.updateTable("gateways").set({is_default:0,updated_at:G,updated_by:J}).where("organization_id","=",$.organizationId).where("is_default","=",1).execute(),await K.updateTable("gateways").set(Y).where("id","=",Q).execute(),X.connections!==void 0){if(await K.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),X.connections.length>0)await K.insertInto("gateway_connections").values(X.connections.map((Z)=>({id:l7("gwc"),gateway_id:Q,connection_id:Z.connectionId,selected_tools:Z.selectedTools?JSON.stringify(Z.selectedTools):null,created_at:G}))).execute()}})}else if(await this.db.updateTable("gateways").set(Y).where("id","=",Q).execute(),X.connections!==void 0){if(await this.db.deleteFrom("gateway_connections").where("gateway_id","=",Q).execute(),X.connections.length>0)await this.db.insertInto("gateway_connections").values(X.connections.map(($)=>({id:l7("gwc"),gateway_id:Q,connection_id:$.connectionId,selected_tools:$.selectedTools?JSON.stringify($.selectedTools):null,created_at:G}))).execute()}let W=await this.findById(Q);if(!W)throw Error("Gateway not found after update");return W}async delete(Q){await this.db.deleteFrom("gateways").where("id","=",Q).execute()}async getDefaultByOrgId(Q){let J=await this.db.selectFrom("gateways").selectAll().where("organization_id","=",Q).where("is_default","=",1).executeTakeFirst();if(!J)return null;let X=await this.db.selectFrom("gateway_connections").selectAll().where("gateway_id","=",J.id).execute();return this.deserializeGatewayWithConnections(J,X)}async getDefaultByOrgSlug(Q){let J=await this.db.selectFrom("organization").select("id").where("slug","=",Q).executeTakeFirst();if(!J)return null;return this.getDefaultByOrgId(J.id)}async setDefault(Q,J){let X=await this.findById(Q);if(!X)throw Error(`Gateway not found: ${Q}`);let G=new Date().toISOString();await this.db.transaction().execute(async(W)=>{await W.updateTable("gateways").set({is_default:0,updated_at:G,updated_by:J}).where("organization_id","=",X.organizationId).where("is_default","=",1).execute(),await W.updateTable("gateways").set({is_default:1,updated_at:G,updated_by:J}).where("id","=",Q).execute()});let Y=await this.findById(Q);if(!Y)throw Error("Gateway not found after setting default");return Y}deserializeGatewayWithConnections(Q,J){return{...this.deserializeGateway(Q),connections:J.map((G)=>({connectionId:G.connection_id,selectedTools:this.parseJson(G.selected_tools)}))}}deserializeGateway(Q){return{id:Q.id,organizationId:Q.organization_id,title:Q.title,description:Q.description,toolSelectionStrategy:this.parseToolSelectionStrategy(Q.tool_selection_strategy),toolSelectionMode:this.parseToolSelectionMode(Q.tool_selection_mode),icon:Q.icon,status:Q.status,isDefault:Q.is_default===1,createdAt:Q.created_at,updatedAt:Q.updated_at,createdBy:Q.created_by,updatedBy:Q.updated_by}}parseToolSelectionStrategy(Q){if(Q==="smart_tool_selection")return"smart_tool_selection";if(Q==="code_execution")return"code_execution";return"passthrough"}parseToolSelectionMode(Q){if(Q==="exclusion")return"exclusion";return"inclusion"}parseJson(Q){if(Q===null)return null;if(typeof Q==="string")try{return JSON.parse(Q)}catch{return null}return Q}}Zk();Dk();function LE4(){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Q}=await Promise.resolve().then(() => (Z_(),mX1));return Q.map((J)=>{return{name:J.name,inputSchema:XU(J.inputSchema),outputSchema:J.outputSchema?XU(J.outputSchema):void 0,description:J.description}})},data:_41(process.env.BASE_URL||"http://localhost:3000")},{data:k41()}]}async function lX1(Q,J){try{let X=Gv(),G=new Ow(process.env.ENCRYPTION_KEY||""),Y=new Dw(X.db,G),W=new Lw(X.db),$=LE4(),K=[];await Promise.all($.map(async(Z)=>{let H=null;if(Z.permissions)H=(await TW.api.createApiKey({body:{name:`${Z.data.app_name??crypto.randomUUID()}-mcp`,userId:J,permissions:Z.permissions,rateLimitEnabled:!1,metadata:{organization:{id:Q},purpose:"default-org-connections"}}}))?.key;let q=await Z.getTools?.()??await JU({id:"pending",title:Z.data.title,connection_url:Z.data.connection_url,connection_token:Z.data.connection_token,connection_headers:Z.data.connection_headers}).catch(()=>null),F=Z.data.id?`${Q}_${Z.data.id}`:void 0,V=await Y.create({...Z.data,id:F,tools:q,organization_id:Q,created_by:J,connection_token:Z.data.connection_token??H});K.push(V.id)})),await W.create(Q,J,{title:"Default Gateway",description:"Auto-created gateway that includes all connections",toolSelectionStrategy:"passthrough",toolSelectionMode:"exclusion",status:"active",isDefault:!0,connections:K.map((Z)=>({connectionId:Z}))})}catch(X){console.error("Error creating default MCP connections:",X)}}var p80=["owner","admin","user"],dX1=["owner","admin"];var wE4=(Q)=>{return{defaultSSO:[{domain:Q.domain,providerId:Q.providerId,oidcConfig:{issuer:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0`,pkce:!0,clientId:Q.MS_CLIENT_ID,clientSecret:Q.MS_CLIENT_SECRET,discoveryEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/v2.0/.well-known/openid-configuration`,authorizationEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/authorize`,tokenEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/oauth2/v2.0/token`,jwksEndpoint:`https://login.microsoftonline.com/${Q.MS_TENANT_ID}/discovery/v2.0/keys`,userInfoEndpoint:"https://graph.microsoft.com/oidc/userinfo",tokenEndpointAuthentication:"client_secret_post",scopes:Q.scopes,mapping:{id:"sub",email:"email",emailVerified:"email_verified",name:"name",image:"picture",extraFields:{emailVerified:"email_verified"}}}}]}},pX1=(Q)=>{if(Q.providerId==="microsoft")return wE4(Q);throw Error(`Unsupported provider: ${Q.providerId}`)};function PE4(Q){return Q.toLowerCase().trim().replace(/[^a-z0-9\s_-]+/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var cX1=["labs","hub","studio","workspace","systems","core","cloud","works"],nX1=["capybara","guarana","deco","samba","feijoada","capoeira","carnival"];function ME4(){let Q=Math.floor(Math.random()*nX1.length),J=Math.floor(Math.random()*cX1.length),X=nX1[Q]??"deco",G=cX1[J]??"studio";return`${X}-${G}`}var AE4=Object.values(dB()).map((Q)=>Q.map((J)=>J.name)).flat(),TE4={...vS,self:["*",...AE4]},H_=m7(TE4),EE4=H_.newRole({self:["*"],...tL.statements}),jE4=H_.newRole({self:["*"],...tL.statements}),IE4=H_.newRole({self:["*"],...tL.statements}),iX1=Object.values(dB()).map((Q)=>Q.map((J)=>`self:${J.name}`)).flat(),G9=nS.auth,rX1=void 0;if(G9.inviteEmailProviderId&&G9.emailProviders&&G9.emailProviders.length>0){let Q=$v(G9.emailProviders,G9.inviteEmailProviderId);if(Q){let J=Wv(Q);rX1=async(X)=>{let G=X.inviter.user?.name||X.inviter.user?.email,Y=`${process.env.BASE_URL||"http://localhost:3000"}/auth/accept-invitation?invitationId=${X.invitation.id}`;await J({to:X.email,subject:`Invitation to join ${X.organization.name}`,html:`
|
|
1065
1065
|
<h2>You've been invited!</h2>
|
|
1066
1066
|
<p>${G} has invited you to join <strong>${X.organization.name}</strong>.</p>
|
|
1067
1067
|
<p><a href="${Y}">Click here to accept the invitation</a></p>
|