corsair 0.1.69 → 0.1.71
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/chunk-6Q5ZX65O.js +26 -0
- package/dist/{chunk-AEZOR7GA.js → chunk-RCM2FWFL.js} +1 -1
- package/dist/core.d.ts +3 -3
- package/dist/core.js +1 -1
- package/dist/{index-DANE8UMK.d.ts → index-CN2IlLdT.d.ts} +18 -3
- package/dist/{index-D3gJMi1B.d.ts → index-Cadh5O_D.d.ts} +95 -2
- package/dist/index.d.ts +16 -4
- package/dist/index.js +2 -2
- package/dist/oauth.d.ts +5 -1
- package/dist/oauth.js +1 -1
- package/dist/setup.d.ts +1 -1
- package/dist/setup.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-XYRVJ76B.js +0 -26
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import{a as Pe,b as de}from"./chunk-OZHME3EO.js";import{a as xe}from"./chunk-ZGVIF3UY.js";var N=class extends Error{pluginId;constructor(n,r){super(r??`[auth-missing:${n}]`),Object.setPrototypeOf(this,new.target.prototype),this.name="AuthMissingError",this.pluginId=n}};import{createCipheriv as Ee,createDecipheriv as Re,randomBytes as ne,scrypt as on}from"crypto";import{promisify as sn}from"util";var Ie=sn(on),te="aes-256-gcm",De=12,re=16,an=16,V=32;function B(){return ne(V).toString("base64")}async function j(e,n){let r=ne(an),t=await Ie(n,r,V),o=ne(De),i=Ee(te,t,o,{authTagLength:re}),s=Buffer.concat([i.update(e,"utf8"),i.final()]),a=i.getAuthTag();return[r.toString("base64"),o.toString("base64"),a.toString("base64"),s.toString("base64")].join(":")}async function M(e,n){let[r,t,o,i]=e.split(":");if(!r||!t||!o||!i)throw new Error("Invalid encrypted DEK format");let s=Buffer.from(r,"base64"),a=Buffer.from(t,"base64"),d=Buffer.from(o,"base64"),p=Buffer.from(i,"base64"),c=await Ie(n,s,V),l=Re(te,c,a,{authTagLength:re});return l.setAuthTag(d),Buffer.concat([l.update(p),l.final()]).toString("utf8")}function ue(e,n){let r=Buffer.from(n,"base64"),t=ne(De),o=Ee(te,r,t,{authTagLength:re}),i=Buffer.concat([o.update(e,"utf8"),o.final()]),s=o.getAuthTag();return[t.toString("base64"),s.toString("base64"),i.toString("base64")].join(":")}function le(e,n){let[r,t,o]=e.split(":");if(!r||!t||!o)throw new Error("Invalid encrypted data format");let i=Buffer.from(n,"base64"),s=Buffer.from(r,"base64"),a=Buffer.from(t,"base64"),d=Buffer.from(o,"base64"),p=Re(te,i,s,{authTagLength:re});return p.setAuthTag(a),Buffer.concat([p.update(d),p.final()]).toString("utf8")}function H(e,n){let r={};for(let[t,o]of Object.entries(e))r[t]=ue(o,n);return r}function L(e,n){let r={};for(let[t,o]of Object.entries(e))r[t]=le(o,n);return r}function Y(e,n,r){let t=L(e,n);return H(t,r)}function oe(e,n){let r=[];e||r.push("database"),n||r.push("kek");let t={};return new Proxy(t,{get(o,i){let s=r.length>1;throw new Error(`corsair.keys.${String(i)}: Cannot access keys because ${r.join(" and ")} ${s?"are":"is"} not configured. Provide both 'database' and 'kek' in createCorsair() to enable key management.
|
|
2
|
+
|
|
3
|
+
To generate a KEK, run: openssl rand -base64 ${V}`)}})}var Q={oauth_2:{integration:["client_id","client_secret","redirect_url"],account:["access_token","refresh_token","expires_at","scope","webhook_signature"]},api_key:{integration:[],account:["api_key","webhook_signature"]},bot_token:{integration:[],account:["bot_token","webhook_signature"]}};function ve(e,n,r){let t={};for(let o of r)t[`get_${o}`]=async()=>(await e())[o]??null,t[`set_${o}`]=async i=>{let s=[null,void 0,""].includes(i)?null:i;await n({[o]:s})};return t}var pe=e=>{if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e};function q(e){let{authType:n,integrationName:r,kek:t,database:o,extraIntegrationFields:i=[]}=e,s=[...Q[n].integration,...i],a=null,d={kek:t,integrationName:r,getIntegration:async()=>{if(a)return a;let u=await o.db.selectFrom("corsair_integrations").selectAll().where("name","=",r).executeTakeFirst();if(!u)throw new Error(`Integration "${r}" not found. Make sure to create the integration first.`);return a={id:u.id,config:pe(u.config),dek:u.dek??null},a},updateIntegration:async u=>{let h=await d.getIntegration();await o.db.updateTable("corsair_integrations").set({...u.config!==void 0?{config:u.config}:{},...u.dek!==void 0?{dek:u.dek}:{},updated_at:new Date}).where("id","=",h.id).execute(),a=null}},p=null,c=async()=>{if(p)return p;let u=await d.getIntegration();if(!u.dek)throw new Error(`No DEK found for integration "${r}". Initialize the integration first.`);return p=await M(u.dek,t),p},l=async()=>{let u=await d.getIntegration(),h=await c(),b=u.config;return!b||Object.keys(b).length===0?{}:L(b,h)};return{get_dek:c,issue_new_dek:async()=>{let u=await d.getIntegration(),h=B(),b={};if(u.dek){let w=await M(u.dek,t),A=u.config;A&&Object.keys(A).length>0&&(b=Y(A,w,h))}let k=await j(h,t);return await d.updateIntegration({config:b,dek:k}),p=h,h},...ve(l,async u=>{let h=await c(),b;try{b=await l()}catch(A){console.error(`[corsair] Failed to decrypt config for integration "${r}", starting fresh:`,A),b={}}let k={...b};for(let[A,y]of Object.entries(u))y===null?delete k[A]:k[A]=y;let w=H(k,h);await d.updateIntegration({config:w})},s)}}function ie(e){let{authType:n,integrationName:r,tenantId:t,kek:o,database:i,extraAccountFields:s=[]}=e,a=[...Q[n].account,...s],d=null,p=null,c=async()=>{if(p)return p;let y=await i.db.selectFrom("corsair_integrations").selectAll().where("name","=",r).executeTakeFirst();if(!y)throw new Error(`Integration "${r}" not found. Make sure to create the integration first.`);return p={id:y.id,config:pe(y.config),dek:y.dek??null},p},l={kek:o,integrationName:r,tenantId:t,getIntegration:c,getAccount:async()=>{if(d)return d;let y=await c(),m=await i.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t).where("integration_id","=",y.id).executeTakeFirst();if(!m)throw new Error(`Account not found for tenant "${t}" and integration "${r}". Make sure to create the account first.`);return d={id:m.id,config:pe(m.config),dek:m.dek??null},d},updateAccount:async y=>{let m=await l.getAccount();await i.db.updateTable("corsair_accounts").set({...y.config!==void 0?{config:y.config}:{},...y.dek!==void 0?{dek:y.dek}:{},updated_at:new Date}).where("id","=",m.id).execute(),d=null}},f=null,g=null,u=async()=>{if(f)return f;let y=await l.getAccount();if(!y.dek)throw new Error(`No DEK found for account (tenant: "${t}", integration: "${r}"). Initialize the account first.`);return f=await M(y.dek,o),f},h=async()=>{if(g)return g;let y=await l.getIntegration();if(!y.dek)throw new Error(`No DEK found for integration "${r}". Initialize the integration first.`);return g=await M(y.dek,o),g},b=async()=>{let y=await l.getAccount(),m=await u(),T=y.config;return!T||Object.keys(T).length===0?{}:L(T,m)},k=async()=>{let y=await l.getIntegration(),m=await h(),T=y.config;return!T||Object.keys(T).length===0?{}:L(T,m)},A={get_dek:u,issue_new_dek:async()=>{let y=await l.getAccount(),m=B(),T={};if(y.dek){let I=await M(y.dek,o),C=y.config;C&&Object.keys(C).length>0&&(T=Y(C,I,m))}let P=await j(m,o);return await l.updateAccount({config:T,dek:P}),f=m,m},...ve(b,async y=>{let m=await u(),T;try{T=await b()}catch(C){console.error(`[corsair] Failed to decrypt config for account (tenant: "${t}", integration: "${r}"), starting fresh:`,C),T={}}let P={...T};for(let[C,O]of Object.entries(y))O===null?delete P[C]:P[C]=O;let I=H(P,m);await l.updateAccount({config:I})},a)};return n==="oauth_2"&&(A.get_integration_credentials=async()=>{let y=await k();return{client_id:y.client_id||null,client_secret:y.client_secret||null,redirect_url:y.redirect_url??null}}),A}async function _e(e,n,r){let t=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!t)throw new Error(`Integration "${n}" not found.`);let o=B(),i=await j(o,r);return await e.db.updateTable("corsair_integrations").set({dek:i,updated_at:new Date}).where("id","=",t.id).execute(),o}async function Se(e,n,r,t){let o=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!o)throw new Error(`Integration "${n}" not found.`);let i=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",r).where("integration_id","=",o.id).executeTakeFirst();if(!i)throw new Error(`Account not found for tenant "${r}" and integration "${n}".`);let s=B(),a=await j(s,t);return await e.db.updateTable("corsair_accounts").set({dek:a,updated_at:new Date}).where("id","=",i.id).execute(),s}import*as X from"crypto";function Oe(e,n){return Buffer.from(JSON.stringify({plugin:e,tenantId:n,iat:Date.now()})).toString("base64url")}function cn(e,{maxAgeMs:n}={}){try{let r=e.includes(".")?e.split(".")[0]:e,t=JSON.parse(Buffer.from(r,"base64url").toString("utf-8"));if(t!==null&&typeof t=="object"&&"plugin"in t&&"tenantId"in t&&typeof t.plugin=="string"&&typeof t.tenantId=="string"){let o=t;return n!==void 0&&typeof o.iat=="number"&&Date.now()-o.iat>n?null:o}return null}catch{return null}}function Fe(e,n){let r=X.createHmac("sha256",n).update(e).digest("base64url");return`${e}.${r}`}var dn=600*1e3;function $e(e,n){let r=e.lastIndexOf(".");if(r===-1)return null;let t=e.slice(0,r),o=e.slice(r+1),i=X.createHmac("sha256",n).update(t).digest("base64url"),s=Buffer.from(o,"base64url"),a=Buffer.from(i,"base64url");return s.length!==a.length||!X.timingSafeEqual(s,a)?null:cn(t,{maxAgeMs:dn})}var un=async(e,n)=>(console.error(`[corsair:${n.pluginId}:${n.operation}]`,{error:e.message,input:n.input}),{maxRetries:0});async function Me(e,n,r,t,o){let i={pluginId:n,operation:r,input:t,originalError:e},s=Object.keys(o).find(p=>o[p]?.match(e,i));return await(o[s||"DEFAULT"]?.handler||un)(e,i)}import{randomBytes as ln}from"crypto";import{v4 as pn}from"uuid";var gn={open:{read:"allow",write:"allow",destructive:"allow"},cautious:{read:"allow",write:"allow",destructive:"require_approval"},strict:{read:"allow",write:"require_approval",destructive:"deny"},readonly:{read:"allow",write:"deny",destructive:"deny"}};function fn(e,n,r){return r!==void 0?r:gn[n][e]}function Ke(e){let n=/(\d+)(d|h|m|s)/g,r=0,t;for(;(t=n.exec(e))!==null;){let o=parseInt(t[1],10);switch(t[2]){case"d":r+=o*864e5;break;case"h":r+=o*36e5;break;case"m":r+=o*6e4;break;case"s":r+=o*1e3;break}}return r>0?r:600*1e3}function Ne(e){return{async find_by_permission_id(n){if(e)return e.db.selectFrom("corsair_permissions").selectAll().where("id","=",n).executeTakeFirst()},async find_by_token(n){if(e)return e.db.selectFrom("corsair_permissions").selectAll().where("token","=",n).executeTakeFirst()},async set_executing(n){e&&await e.db.updateTable("corsair_permissions").set({status:"executing",updated_at:new Date}).where("id","=",n).execute()},async set_completed(n){e&&await e.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",n).execute()}}}async function Ze(e,n,r){let t=Date.now()+r;for(;Date.now()<t;){let o=await e.db.selectFrom("corsair_permissions").select(["id","status"]).where("id","=",n).executeTakeFirst();if(!o)return{result:"blocked",reason:"pending"};if(o.status==="approved")return{result:"allow",onComplete:async()=>{await e.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",n).execute()}};if(o.status==="denied")return{result:"blocked",reason:"denied"};if(o.status==="expired"||o.status==="failed")return{result:"blocked",reason:"timeout"};await new Promise(i=>setTimeout(i,500))}return{result:"blocked",reason:"timeout"}}async function Be(e){let n=fn(e.riskLevel,e.mode,e.override);if(n==="allow")return{result:"allow"};let r=e.meta?.irreversible?" (irreversible)":"",t=e.meta?.description?`${e.meta.description}${r}`:`${e.pluginId}.${e.endpointPath}${r}`;if(n==="deny"||!e.db)return console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 denied by permission mode '${e.mode}'.`,`
|
|
4
|
+
Action: ${t}`,`
|
|
5
|
+
To allow this, update the permission mode or add an override in your corsair config.`),{result:"blocked",reason:"policy"};let o=JSON.stringify(e.args),i=new Date().toISOString(),s=e.tenantId??"default",a=await e.db.db.selectFrom("corsair_permissions").selectAll().where("plugin","=",e.pluginId).where("endpoint","=",e.endpointPath).where("args","=",o).where("tenant_id","=",s).where("expires_at",">",i).where("status","in",["pending","approved","executing"]).orderBy("created_at","desc").limit(1).executeTakeFirst();if(a){if(a.status==="approved"){let u=e.db,h=a.id;return{result:"allow",onComplete:async()=>{await u.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",h).execute()}}}return a.status==="executing"?{result:"allow"}:(console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval already pending.`,`
|
|
6
|
+
Action: ${t}`,`
|
|
7
|
+
Permission ID: ${a.id}`,`
|
|
8
|
+
Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?Ze(e.db,a.id,e.timeoutMs??600*1e3):{result:"blocked",reason:"pending",id:a.id,token:a.token})}let d=pn(),p=ln(32).toString("hex"),c=e.timeoutMs??600*1e3,l=new Date(Date.now()+c).toISOString();return await e.db.db.insertInto("corsair_permissions").values({id:d,created_at:new Date,updated_at:new Date,token:p,plugin:e.pluginId,endpoint:e.endpointPath,args:o,tenant_id:s,status:"pending",expires_at:l}).execute(),console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval required.`,`
|
|
9
|
+
Action: ${t}`,`
|
|
10
|
+
Permission ID: ${d}`,`
|
|
11
|
+
Permission token: ${p}`,`
|
|
12
|
+
Expires at: ${l}`,`
|
|
13
|
+
Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?Ze(e.db,d,c):{result:"blocked",reason:"pending",id:d,token:p}}function yn(e){return typeof e=="function"}function je(e,n,r){let t=Fe(Oe(e,n.tenantId??r??"default"),n.kek),o=new URL(n.baseUrl);o.searchParams.set("state",t);let i=o.toString(),s=n.onAuthMissing?n.onAuthMissing({plugin:e,connectUrl:i,state:t}):`[auth-missing:${e}] Authentication required. Direct the user to connect their account: ${i}`;return new Error(s)}function ge({endpoints:e,hooks:n,ctx:r,tree:t,pluginId:o,errorHandlers:i,currentPath:s=[],keyBuilder:a,permissionsConfig:d,endpointMeta:p,database:c,approvalConfig:l,tenantId:f,connectConfig:g}){for(let[u,h]of Object.entries(e)){let b=n?.[u];if(yn(h)){let k=b,w=[...s,u].join("."),A=async(y={})=>{let m;if(d){let E=p?.[w],{result:U,reason:S,onComplete:J,token:F,id:K}=await Be({pluginId:o,endpointPath:w,args:y,mode:d.mode,override:d.overrides?.[w],riskLevel:E?.riskLevel??"write",meta:E,db:c,timeoutMs:l?Ke(l.timeout):void 0,tenantId:f,approvalMode:l?.mode});if(U==="blocked"){let x;throw S==="denied"?x=`Action '${w}' was denied by the user. Await further instructions before proceeding.`:S==="policy"?x=`Action '${w}' is blocked by the permission policy. Update the corsair config to allow it.`:S==="timeout"?x=`Action '${w}' timed out waiting for approval.`:l?.formatAsyncMessage&&F&&K?x=l.formatAsyncMessage({token:F,id:K,plugin:o,endpoint:w,args:y}):x=`Action '${w}' requires user approval before it can run.`,new Error(x)}m=J}let T=async(E,U,S)=>{try{return await h(U,S)}catch(J){if(J instanceof Error){let F=await Me(J,o,w,typeof S=="object"&&S!==null?S:{args:S},i);if(E<(F.maxRetries||0)){let K=E+1;console.log(`Retrying (${K} / ${F.maxRetries})...`);let x;if(F.headersRetryAfterMs)x=F.headersRetryAfterMs;else switch(F.retryStrategy){case"exponential_backoff":x=Math.pow(2,K-1)*1e3;break;case"exponential_backoff_jitter":let ce=Math.pow(2,K-1)*1e3,rn=(Math.random()-.5)*1e3;x=Math.max(0,ce+rn);break;case"linear_1s":x=1e3;break;case"linear_2s":x=2e3;break;case"linear_3s":x=3e3;break;case"linear_4s":x=4e3;break;default:x=1e3;break}await new Promise(ce=>setTimeout(ce,x)),await T(K,U,S),console.log(`[corsair:${o}:${w}] Retry strategy:`,F)}}throw J}},P;try{P=a?await a(r,"endpoint"):void 0}catch(E){throw g?.oauthConfig&&g.kek&&E instanceof N?je(o,g,f):E}if(!P&&a&&g?.oauthConfig&&g.kek)throw je(o,g,f);if(!k?.before&&!k?.after){let E=await T(0,{...r,key:P},y);return await m?.(),E}let I={...r,key:P},C=k.before?await k.before(I,y):{ctx:I,args:y,continue:!0,passToAfter:void 0};if(C.continue===!1)return;let O=await T(0,C.ctx,C.args);return await k.after?.(C.ctx,O,C.passToAfter),await m?.(),O};t[u]=A}else if(h&&typeof h=="object"){let k={};ge({endpoints:h,hooks:b,ctx:r,tree:k,pluginId:o,errorHandlers:i,currentPath:[...s,u],keyBuilder:a,permissionsConfig:d,endpointMeta:p,database:c,approvalConfig:l,tenantId:f,connectConfig:g}),t[u]=k}}}function hn(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function fe({webhooks:e,hooks:n,ctx:r,webhooksTree:t,keyBuilder:o}){for(let[i,s]of Object.entries(e)){let a=n?.[i];if(hn(s)){let d=a,p=async c=>{let l=(g,u)=>s.handler(g,u),f=o?await o(r,"webhook"):void 0;return!d?.before&&!d?.after?l({...r,key:f},c):(async()=>{let g={...r,key:f},u=d.before?await d.before(g,c):{ctx:g,args:c,continue:!0,passToAfter:void 0};if(u.continue===!1)return;let h=await l(u.ctx,u.args);return h?.success===!0&&await d.after?.(u.ctx,h,u.passToAfter),h})()};t[i]={match:s.match,handler:p}}else if(s&&typeof s=="object"){let d={};fe({webhooks:s,hooks:a,ctx:r,webhooksTree:d,keyBuilder:o}),t[i]=d}}}function mn(e,n,r){let t=null;return async()=>{if(t)return t;if(!e)throw new Error("Database not configured");let o=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!o)throw new Error(`Integration "${n}" not found. Make sure to create the integration first.`);let i=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",r).where("integration_id","=",o.id).executeTakeFirst();if(!i)throw new Error(`Account not found for tenant "${r}" and integration "${n}". Make sure to create the account first.`);return t=i.id,t}}function kn(e,n,r,t,o){return e?de(e.db,n,r,t,o):{findByEntityId:async()=>null,findById:async()=>null,findManyByEntityIds:async()=>[],list:async()=>[],search:async()=>[],upsertByEntityId:async()=>{throw new Error("Database not configured")},deleteById:async()=>!1,deleteByEntityId:async()=>!1,count:async()=>0}}function ye(e,n){let{database:r,tenantId:t,kek:o,rootErrorHandlers:i,approvalConfig:s,connectConfig:a}=n,d={},p={};for(let c of e)d[c.id]={},p[c.id]={};for(let c of e){let l=c.schema,f=t??"default",g=mn(r,c.id,f);if(l?.entities){let C={};for(let[O,E]of Object.entries(l.entities)){let U=r?de(r.db,g,O,l.version,E):kn(void 0,g,O,l.version,E);C[O]=U}p[c.id].db=C,d[c.id].db=C}let u=c.options,h=c.authConfig,b;if(r&&o&&u?.authType){let C=h?.[u.authType]?.account??[];b=ie({authType:u.authType,integrationName:c.id,tenantId:f,kek:o,database:r,extraAccountFields:C}),d[c.id].keys=b}let k={database:r,db:p[c.id]?.db??{},$getAccountId:g,...c.options?{options:c.options}:{},...b?{keys:b,authType:u?.authType}:{},...t?{tenantId:t}:{}},w=c.endpoints??{},A=c.hooks,y={...i,...c.errorHandlers},m={},T=c.options?.permissions;ge({endpoints:w,hooks:A,ctx:k,tree:m,pluginId:c.id,errorHandlers:y,currentPath:[],keyBuilder:c.keyBuilder,permissionsConfig:T,endpointMeta:c.endpointMeta,database:r,approvalConfig:s,tenantId:t,connectConfig:a?{...a,oauthConfig:c.oauthConfig,kek:o,tenantId:f}:void 0}),Object.keys(m).length>0&&(d[c.id].api=m),k.endpoints=m;let P=c.webhooks??{},I=c.webhookHooks;if(Object.keys(P).length>0){let C={};fe({webhooks:P,hooks:I,ctx:k,webhooksTree:C,keyBuilder:c.keyBuilder}),d[c.id].webhooks=C,c.pluginWebhookMatcher&&(d[c.id].pluginWebhookMatcher=c.pluginWebhookMatcher)}}return d}function Le(e,n,r){let t={};for(let o of e){let i=o.options,s=o.authConfig;if(i?.authType){let a=s?.[i.authType]?.integration??[],d=q({authType:i.authType,integrationName:o.id,kek:r,database:n,extraIntegrationFields:a});t[o.id]=d}}return t}async function We(e,n,r,t,o="pending"){if(!e)return null;try{let i=Pe(),s=new Date;return await e.db.insertInto("corsair_events").values({id:i,created_at:s,updated_at:s,account_id:n,event_type:r,payload:t,status:o}).execute(),i}catch(i){return console.warn("Failed to log event:",i),null}}async function bn(e,n,r,t="pending"){try{let o=await e.$getAccountId();return We(e.database,o,n,r,t)}catch(o){return console.warn("Failed to log event:",o),null}}import*as Ue from"https";import*as He from"querystring";function qe(e,n,r,t,o){let i=new URL(t.tokenUrl),s=t.tokenAuthMethod==="basic";return new Promise((a,d)=>{let p={code:e.trim(),redirect_uri:o,grant_type:"authorization_code"};s||(p.client_id=n,p.client_secret=r);let c=He.stringify(p),l={"Content-Type":"application/x-www-form-urlencoded","Content-Length":Buffer.byteLength(c).toString()};s&&(l.Authorization=`Basic ${Buffer.from(`${n}:${r}`).toString("base64")}`);let f=Ue.request({hostname:i.hostname,...i.port?{port:Number(i.port)}:{},path:i.pathname+i.search,method:"POST",headers:l},g=>{let u="";g.on("data",h=>{u+=h}),g.on("end",()=>{if(g.statusCode!==200){d(new Error(`Token exchange failed (${g.statusCode}): ${u}`));return}try{a(JSON.parse(u))}catch{d(new Error(`Token endpoint returned non-JSON response: ${u}`))}})});f.on("error",g=>d(new Error(`Request failed: ${g.message}`))),f.write(c),f.end()})}import*as ze from"querystring";function wn(e){let n=e[ee];if(!n)throw new Error("Invalid corsair instance");return n}function Cn(e,n){let r=e.plugins.find(t=>t.id===n);if(!r)throw new Error(`Plugin '${n}' not found`);return r}function Tn(e){let n=e.oauthConfig;if(!n)throw new Error(`Plugin '${e.id}' has no oauthConfig`);return n}async function An(e,n){let r=wn(e);if(!r.database)throw new Error("No database configured on corsair instance");let t=r.connect?.redirectUri;if(!t)throw new Error("No redirectUri configured. Set connect.redirectUri in createCorsair().");let o=$e(n,r.kek);if(!o)throw new Error("Invalid or tampered state parameter");let{plugin:i,tenantId:s}=o,a=Cn(r,i),d=Tn(a),c=await q({authType:"oauth_2",integrationName:i,kek:r.kek,database:r.database}).get_client_id();if(!c)throw new Error(`client_id not configured for '${i}'`);let l={...d.authParams,client_id:c,redirect_uri:t,response_type:"code",scope:d.scopes.join(" "),state:n},f=`${d.authUrl}?${ze.stringify(l)}`;return{plugin:i,tenantId:s,providerName:d.providerName,oauthUrl:f,state:n}}var Ge=["airtable","amplitude","asana","bitwarden","bluesky","box","cal","calendly","cloudflare","cursor","discord","dodopayments","dropbox","exa","figma","firecrawl","fireflies","github","gitlab","gmail","googlecalendar","googledrive","googlesheets","grafana","hackernews","hubspot","intercom","jira","linear","monday","notion","onedrive","openweathermap","oura","outlook","pagerduty","posthog","razorpay","reddit","resend","sentry","sharepoint","slack","spotify","strava","stripe","tally","tavily","teams","telegram","todoist","trello","twitter","twitterapiio","typeform","vapi","xquik","youtube","zendesk","zoom"];var Je=" ";function v(e){let n=e;return n._def??n.def??{}}function _(e){let n=e.typeName;if(n)return n;let r=e.type;if(r)return`Zod${r.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}`}function D(e){return e.innerType??e.schema??e.out??e.in}function Ye(e,n){switch(n){case"ZodPipe":return e.in??e.innerType;case"ZodEffects":return e.schema??e.innerType;case"ZodTransform":return e.schema??e.innerType??e.in;default:return D(e)}}function Qe(e){let n=e.type;return e.element??(typeof n=="string"?void 0:n)}function ae(e,n){let r=n.shape??e.shape;return typeof r=="function"?r():r}function z(e){return Array.isArray(e.options)?e.options:Array.isArray(e.values)?e.values:e.entries!==null&&typeof e.entries=="object"&&!Array.isArray(e.entries)?Object.values(e.entries):[]}function Xe(e,n){return e.description??n.description}function xn(e){let n=e;for(;n;){let r=v(n),t=Xe(n,r);if(t)return t;let o=_(r);if(we(o)||o==="ZodPipe"||o==="ZodEffects"||o==="ZodTransform"){n=Ye(r,o);continue}break}}function we(e){return e==="ZodOptional"||e==="ZodNullable"||e==="ZodDefault"||e==="ZodCatch"}function R(e){let n=v(e),r=_(n);switch(r){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodDate":return"Date";case"ZodNull":return"null";case"ZodUnknown":case"ZodAny":return"any";case"ZodLiteral":return String(n.value??z(n)[0]??"unknown");case"ZodEnum":return z(n).map(t=>String(t)).join(" | ");case"ZodOptional":{let t=D(n);return t?R(t):"unknown"}case"ZodNullable":{let t=D(n);return`${t?R(t):"unknown"} | null`}case"ZodDefault":case"ZodCatch":{let t=D(n);return t?R(t):"unknown"}case"ZodArray":{let t=Qe(n);if(!t)return"unknown[]";let o=v(t),i=_(o)==="ZodUnion",s=R(t);return`${i?`(${s})`:s}[]`}case"ZodRecord":return"{}";case"ZodObject":{let t=ae(e,n),o=Object.entries(t);return o.length===0?"{}":`{ ${o.map(([s,a])=>{let d=_(v(a));return`${d==="ZodOptional"||d==="ZodNullable"?s+"?":s}: ${R(a)}`}).join(", ")} }`}case"ZodUnion":return z(n).map(t=>R(t)).join(" | ");case"ZodIntersection":return`${R(n.left)} & ${R(n.right)}`;case"ZodPipe":case"ZodTransform":case"ZodEffects":{let t=Ye(n,r);return t?R(t):"unknown"}default:return(r??"unknown").replace("Zod","").toLowerCase()}}function $(e){let n=v(e),r=_(n),t=Xe(e,n);switch(r){case"ZodString":return{kind:"string",optional:!1,description:t};case"ZodNumber":return{kind:"number",optional:!1,description:t};case"ZodBoolean":return{kind:"boolean",optional:!1,description:t};case"ZodLiteral":{let o=n.value??z(n)[0],i=typeof o=="string"||typeof o=="number"||typeof o=="boolean"?o:String(o??"");return{kind:"literal",optional:!1,description:t,value:i}}case"ZodEnum":{let o=z(n).map(i=>String(i));return{kind:"string",optional:!1,description:t,enum:o}}case"ZodOptional":{let o=D(n),i=o?$(o):{kind:"unknown",optional:!1};return{...i,optional:!0,description:t??i.description}}case"ZodNullable":{let o=D(n),i=o?$(o):{kind:"unknown",optional:!1};return{...i,optional:!0,description:t??i.description}}case"ZodDefault":case"ZodCatch":{let o=D(n);return o?{...$(o),description:t}:{kind:"unknown",optional:!1,description:t}}case"ZodArray":{let o=Qe(n);return{kind:"array",optional:!1,description:t,items:o?$(o):{kind:"unknown",optional:!1}}}case"ZodObject":{let o=ae(e,n),i={};for(let[s,a]of Object.entries(o))i[s]=$(a);return{kind:"object",optional:!1,description:t,fields:i}}case"ZodRecord":return{kind:"unknown",optional:!1,description:t};case"ZodUnion":{let o=z(n);for(let i of o){let s=v(i);if(_(s)==="ZodObject")return{...$(i),description:t}}return{kind:"unknown",optional:!1,description:t}}case"ZodIntersection":case"ZodPipe":case"ZodTransform":case"ZodEffects":{let o=D(n);return o?{...$(o),description:t}:{kind:"unknown",optional:!1,description:t}}default:return{kind:"unknown",optional:!1,description:t}}}function wt(e,n){let r=n.toLowerCase(),t=r.indexOf(".");if(t===-1)return null;let o=r.slice(0,t),i=r.slice(t+1),s=e.find(c=>c.id===o);if(!s)return null;let a=i;a.startsWith("api.")&&(a=a.slice(4));let d=Z(s.endpointMeta,a),p=Z(s.endpointSchemas,a);return!d&&!p?null:{input:p?.input?$(p.input):null,output:p?.output?$(p.output):null,description:d?.description}}var Ce=["equals","contains","startsWith","endsWith","in"],Pn=["equals","gt","gte","lt","lte","in"],En=["equals"],Rn=["equals","before","after","between"];function en(e){let n=v(e);switch(_(n)){case"ZodOptional":case"ZodNullable":case"ZodDefault":case"ZodCatch":{let t=D(n);return t?en(t):null}case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodDate":return"date";default:return null}}function Te(e){let n=v(e),r=_(n);if(we(r)){let i=D(n);return i?Te(i):{}}if(r!=="ZodObject")return{};let t=ae(e,n),o={};for(let[i,s]of Object.entries(t)){let a=en(s);a==="string"?o[i]={type:"string",operators:Ce}:a==="number"?o[i]={type:"number",operators:Pn}:a==="boolean"?o[i]={type:"boolean",operators:En}:a==="date"&&(o[i]={type:"date",operators:Rn})}return o}function nn(e,n){for(let[r,t]of Object.entries(e))if(r.toLowerCase()===n)return[r,t]}function me(e,n,r){for(let[t,o]of Object.entries(e)){let i=[...n,t];typeof o=="function"?r.push(i.join(".")):o!==null&&typeof o=="object"&&me(o,i,r)}}function ke(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function be(e,n,r){for(let[t,o]of Object.entries(e)){let i=[...n,t];ke(o)?r.push(i.join(".")):o!==null&&typeof o=="object"&&be(o,i,r)}}function Ae(e,n){if(n.length===0)return null;let[r,...t]=n,o=Object.entries(e).find(([a])=>a.toLowerCase()===r);if(!o)return null;let[i,s]=o;if(t.length===0)return ke(s)?[i]:null;if(s!==null&&typeof s=="object"&&!ke(s)){let a=Ae(s,t);if(a!==null)return[i,...a]}return null}function tn(e,n){let r=[];r.push(`${e}({`),r.push(" webhookHooks: {");for(let i=0;i<n.length;i++){let s=" ".repeat(i+2);r.push(`${s}${n[i]}: {`)}let t=" ".repeat(n.length+2),o=t+" ";r.push(`${t}before(ctx, args) {`),r.push(`${o}return { ctx, args };`),r.push(`${t}},`),r.push(`${t}after(ctx, response) {`),r.push(`${t}},`);for(let i=n.length-1;i>=0;i--){let s=" ".repeat(i+2);r.push(`${s}},`)}return r.push(" },"),r.push("})"),r.join(`
|
|
14
|
+
`)}var In=new Set(Ge);function W(e,n){let r=n?.type??"api",t=n?.plugin;if(t!==void 0){let i=e.find(a=>a.id===t);if(!i)return In.has(t)?`This plugin (${t}) is not configured. Please add it to the Corsair instance to see its associated methods.`:W(e);if(r==="webhooks"){if(!i.webhooks)return[];let a=[];return be(i.webhooks,[],a),a.map(d=>`${i.id}.webhooks.${d}`)}if(r==="db"){let a=i.schema?.entities;return a?Object.keys(a).map(d=>`${i.id}.db.${d}.search`):[]}if(!i.endpoints)return[];let s=[];return me(i.endpoints,[],s),s.map(a=>`${i.id}.api.${a}`)}let o={};if(r==="webhooks")for(let i of e){if(!i.webhooks)continue;let s=[];be(i.webhooks,[],s),o[i.id]=s.map(a=>`${i.id}.webhooks.${a}`)}else if(r==="db")for(let i of e){let s=i.schema?.entities;s&&(o[i.id]=Object.keys(s).map(a=>`${i.id}.db.${a}.search`))}else for(let i of e){if(!i.endpoints)continue;let s=[];me(i.endpoints,[],s),o[i.id]=s.map(a=>`${i.id}.api.${a}`)}return o}function Z(e,n){if(e){for(let[r,t]of Object.entries(e))if(r.toLowerCase()===n)return t}}function Dn(e,n){let r=e.toLowerCase(),t=n.toLowerCase();if(!r.startsWith(`${t}.`)){let i=r.slice(n.length+1),s=i.startsWith(".")?i.slice(1):i;return s.startsWith("api.")&&(s=s.slice(4)),{shortPath:s,lookupKey:s}}let o=e.slice(n.length+1);return o.toLowerCase().startsWith("api.")&&(o=o.slice(4)),{shortPath:o,lookupKey:o.toLowerCase()}}function he(e,n){return typeof e=="string"?e:Array.isArray(e)?`${n}:
|
|
15
|
+
${e.join(", ")}`:`${n}:
|
|
16
|
+
`+Object.entries(e).map(([r,t])=>` ${r}: ${t.join(", ")}`).join(`
|
|
17
|
+
`)}function Ct(e,n){let r=n.toLowerCase(),t=r.indexOf(".");if(t!==-1){let o=r.slice(0,t),i=r.slice(t+1),s=e.find(a=>a.id===o);if(s){if(i.startsWith("db.")){let c=i.slice(3),l=c.lastIndexOf(".");if(l!==-1){let f=c.slice(0,l),g=c.slice(l+1),u=s.schema?.entities;if(g==="search"&&u){let h=nn(u,f);if(h){let[b,k]=h,w=Te(k),A=[`Search ${o} ${b} stored in the local database.`,"Pass limit and offset as numbers for pagination.","","filters {",` entity_id: string [${Ce.join(", ")}]`];for(let[y,m]of Object.entries(w))A.push(` ${y}?: ${m.type} [${m.operators.join(", ")}]`);return A.push("}"),A.join(`
|
|
18
|
+
`)}}}return he(W(e,{type:"db"}),"Path not found. Available db operations")}if(i.startsWith("webhooks.")){let c=i.slice(9);if(s.webhooks){let l=Ae(s.webhooks,c.split("."));if(l!==null){let f=l.join("."),g=Z(s.webhookSchemas,f.toLowerCase()),u=g?.response?R(g.response):null,h=[];return g?.description&&h.push(g.description),g?.payload&&h.push(`payload ${se(G(g.payload))}`),u&&h.push(`response: ${u}`),h.push(`usage:
|
|
19
|
+
${tn(o,l)}`),h.join(`
|
|
20
|
+
|
|
21
|
+
`)}}return he(W(e,{type:"webhooks"}),"Path not found. Available webhooks")}let a=i;a.startsWith("api.")&&(a=a.slice(4));let d=Z(s.endpointMeta,a),p=Z(s.endpointSchemas,a);if(d||p){let c=[],l=[d?.riskLevel?`[${d.riskLevel}]`:"",d?.irreversible?"[irreversible]":""].filter(Boolean).join(" "),f=[d?.description,l].filter(Boolean).join(" ");return f&&c.push(f),p?.input&&c.push(`input ${se(G(p.input))}`),p?.output&&c.push(`output ${se(G(p.output))}`),c.join(`
|
|
22
|
+
|
|
23
|
+
`)}}}return he(W(e),"Path not found. Available operations")}function Ve(e){let n=e;for(;;){let r=v(n),t=_(r);if(we(t)){let o=D(r);if(!o)return n;n=o;continue}return n}}function G(e){if(e===void 0)return{kind:"inline",type:"unknown"};let n=Ve(e),r=v(n);if(_(r)==="ZodObject"){let o=ae(n,r),i=[];for(let[s,a]of Object.entries(o)){let d=v(a),p=_(d),c=p==="ZodOptional"||p==="ZodNullable",l=Ve(a),f=xn(a);i.push({key:s,optional:c,type:R(l),...f!==void 0?{description:f}:{}})}return{kind:"object",fields:i}}return{kind:"inline",type:R(n)}}function se(e,n=0){if(e===void 0)return"{}";if(e.kind==="inline")return e.type;if(e.kind==="object"){if(e.fields.length===0)return"{}";let r=Je.repeat(n+1),t=Je.repeat(n);return`{
|
|
24
|
+
${e.fields.map(i=>{let s=i.optional?`${i.key}?`:i.key,a=i.description?` // ${i.description}`:"";return`${r}${s}: ${i.type}${a}`}).join(`
|
|
25
|
+
`)}
|
|
26
|
+
${t}}`}return"unknown"}function vn(e,n){let r=W(e,{plugin:n,type:"api"});if(typeof r=="string")return{ok:!1,error:r};if(!Array.isArray(r))return{ok:!1,error:"list_operations did not return a path array \u2014 pass a configured plugin id."};let t=e.find(c=>c.id===n);if(!t)return{ok:!1,error:`Plugin "${n}" is not configured on this instance.`};let o=[];for(let c of r){let{shortPath:l,lookupKey:f}=Dn(c,n),g=Z(t.endpointMeta,f),u=Z(t.endpointSchemas,f);!g&&!u||o.push({path:c,shortPath:l,description:g?.description,riskLevel:g?.riskLevel,irreversible:g?.irreversible,input:G(u?.input),output:G(u?.output)})}o.sort((c,l)=>c.path.localeCompare(l.path));let i=[],s=W(e,{plugin:n,type:"webhooks"});if(Array.isArray(s)&&t.webhooks)for(let c of s){let f=c.toLowerCase().slice(n.length+1),g=f.startsWith(".")?f.slice(1):f;if(!g.startsWith("webhooks."))continue;let u=g.slice(9),h=Ae(t.webhooks,u.split("."));if(h===null)continue;let b=h.join("."),k=Z(t.webhookSchemas,b.toLowerCase()),w=k?.response?R(k.response):void 0;i.push({path:c,description:k?.description,payload:G(k?.payload),responseType:w,usageExample:tn(n,h)})}i.sort((c,l)=>c.path.localeCompare(l.path));let a=[],d=W(e,{plugin:n,type:"db"}),p=t.schema?.entities;if(Array.isArray(d)&&p)for(let c of d){let f=c.toLowerCase().slice(n.length+1),g=f.startsWith(".")?f.slice(1):f;if(!g.startsWith("db."))continue;let u=g.slice(3),h=u.lastIndexOf(".");if(h===-1)continue;let b=u.slice(0,h);if(u.slice(h+1)!=="search")continue;let w=nn(p,b);if(!w)continue;let[A,y]=w,m=Te(y),T=Object.entries(m).map(([P,I])=>({field:P,type:I.type,operators:I.operators}));a.push({path:c,entityName:A,filters:[{field:"entity_id",type:"string",operators:Ce},...T]})}return a.sort((c,l)=>c.path.localeCompare(l.path)),{ok:!0,data:{pluginId:n,api:o,webhooks:i,db:a}}}var ee=Symbol.for("corsair:internal");function Rt(e){let n=e.database?xe(e.database):void 0,r=n&&e.kek?Le(e.plugins,n,e.kek):oe(!!n,!!e.kek),t={plugins:e.plugins,database:n,kek:e.kek,multiTenancy:!!e.multiTenancy,approval:e.approval,connect:e.connect},o=Ne(n);if(e.multiTenancy)return Object.assign({withTenant:s=>{if(!s)throw new Error("corsair.withTenant(tenantId): tenantId must be a non-empty string");let a=ye(e.plugins,{database:n,tenantId:s,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval,connectConfig:e.connect});return Object.assign(a,{[ee]:t})},keys:r,permissions:o},{[ee]:t});let i=ye(e.plugins,{database:n,tenantId:void 0,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval,connectConfig:e.connect});return Object.assign({},i,{keys:r,permissions:o,[ee]:t})}export{N as a,B as b,j as c,M as d,ue as e,le as f,H as g,L as h,Y as i,Q as j,q as k,ie as l,_e as m,Se as n,Oe as o,cn as p,Fe as q,$e as r,We as s,bn as t,qe as u,An as v,Ge as w,wt as x,W as y,Ct as z,se as A,vn as B,ee as C,Rt as D};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{C as A,D as T,j as w,k as C,l as S}from"./chunk-6Q5ZX65O.js";import{a as _}from"./chunk-UBM25HVI.js";import{Kysely as I}from"kysely";import{ZodBoolean as M,ZodDate as R,ZodEnum as j,ZodNullable as D,ZodNumber as F,ZodObject as O,ZodOptional as x,ZodRecord as E,ZodString as K,ZodType as B}from"zod";var h={slack:{channels:{list:{}},users:{list:{}}},linear:{projects:{list:{}},issues:{list:{}},users:{list:{}}},github:{issues:{list:{}},repositories:{list:{}}},discord:{guilds:{list:{}},channels:{list:{}}},hubspot:{contacts:{getMany:{}},companies:{getMany:{}},deals:{getMany:{}}},gmail:{messages:{list:{}},labels:{list:{}},drafts:{list:{}},threads:{list:{}}},googlecalendar:{events:{getMany:{}}},googledrive:{files:{list:{}},folders:{list:{}},sharedDrives:{list:{}}},notion:{databases:{getManyDatabases:{}},databasePages:{getManyDatabasePages:{}},users:{getManyUsers:{}}},airtable:{bases:{getMany:{}}},todoist:{projects:{getMany:{}},tasks:{getMany:{}}},cal:{bookings:{list:{}}}};async function ie(e,t){let a=[],i=s=>{a.push(s),console.log(s)},o=s=>{a.push(s),console.warn(s)},f=t?.caller??"script",d=t?.tenantId;if(!d){if(e?.withTenant)throw new Error("setupCorsair: tenantId must be a non-empty string");d="default"}let n=v(e);if(!n)throw new Error("setupCorsair: invalid corsair instance");if(!n.database)throw new Error("setupCorsair: a database must be configured on the corsair instance");let u={...n,database:n.database},c=u.database.db;await Y(c,o);let p=await H(c,u,d,i),y=await z(p,d,i,f);if(t?.backfill){i("[corsair:setup] Starting backfill...");let s=T({plugins:n.plugins,database:c,kek:n.kek,multiTenancy:!0}).withTenant(d);await Q(s,n.plugins,y,i,o),i("[corsair:setup] Backfill complete.")}return a.join(`
|
|
2
2
|
`)}function b(e){return typeof e=="object"&&e!==null}function Z(e){return!b(e)||!Array.isArray(e.plugins)||typeof e.kek!="string"||typeof e.multiTenancy!="boolean"?!1:e.database===void 0?!0:b(e.database)?e.database.db instanceof I:!1}function v(e){let t=Object.getOwnPropertyDescriptor(e,A);if(t)return Z(t.value)?t.value:void 0}function N(e){return e==="oauth_2"||e==="api_key"||e==="bot_token"}function L(e){let t=e.options?.authType;return N(t)?t:void 0}function m(e,t){if(!b(e))return;let a=e[t];return typeof a=="function"?(...i)=>Reflect.apply(a,e,i):void 0}function $(e,t){return b(e)?t===0?!0:Object.values(e).every(a=>$(a,t-1)):!1}function U(e){return $(e,4)}var W={..._};function k(e){if(e instanceof O){let t={};for(let[a,i]of Object.entries(e.shape))t[a]=i instanceof B?k(i):"unknown";return t}return e instanceof D?`${k(e.unwrap())} | null`:e instanceof x?`${k(e.unwrap())} | undefined`:e instanceof j?e.options.join(" | "):e instanceof K?"string":e instanceof F?"number":e instanceof M?"boolean":e instanceof R?"date":e instanceof E?"jsonb":"unknown"}async function Y(e,t){let a=await e.introspection.getTables(),i=new Set(a.map(o=>o.name));for(let[o,f]of Object.entries(W))i.has(o)||t(`[corsair:setup] Table "${o}" does not exist. Run your database migrations before calling setupCorsair.
|
|
3
3
|
Schema: ${JSON.stringify(k(f),null,2)}`)}async function H(e,t,a,i){let o=new Date,f=new Map;for(let d of t.plugins){let n=d.id,u=L(d),c=await e.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!c){let l=crypto.randomUUID();await e.insertInto("corsair_integrations").values({id:l,name:n,config:{},created_at:o,updated_at:o}).execute(),c=await e.selectFrom("corsair_integrations").selectAll().where("id","=",l).executeTakeFirst(),i(`[corsair:setup] Created integration: ${n}`)}let p=u?d.authConfig?.[u]?.integration??[]:[],y=u?d.authConfig?.[u]?.account??[]:[],s=u&&c?C({authType:u,integrationName:n,kek:t.kek,database:t.database,extraIntegrationFields:p}):void 0;if(c&&!c.dek&&s&&(await s.issue_new_dek(),i(`[corsair:setup] Issued integration DEK: ${n}`)),!c)continue;let r=await e.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",a).where("integration_id","=",c.id).executeTakeFirst();if(!r){let l=crypto.randomUUID();await e.insertInto("corsair_accounts").values({id:l,tenant_id:a,integration_id:c.id,config:{},created_at:o,updated_at:o}).execute(),r=await e.selectFrom("corsair_accounts").selectAll().where("id","=",l).executeTakeFirst(),i(`[corsair:setup] Created account: ${n}`)}let g=u&&r?S({authType:u,integrationName:n,tenantId:a,kek:t.kek,database:t.database,extraAccountFields:y}):void 0;r&&!r.dek&&g&&(await g.issue_new_dek(),i(`[corsair:setup] Issued account DEK: ${n}`)),u&&s&&g&&f.set(n,{pluginId:n,authType:u,integration:s,account:g,integrationFields:[...w[u].integration,...p],accountFields:[...w[u].account,...y]})}return f}var P=new Set(["webhook_signature","expires_at","scope","redirect_url"]);async function J(e,t,a,i,o,f,d,n,u){let c=[],p=[];for(let s of o){if(P.has(s))continue;let r=m(a,`get_${s}`);if(!r)continue;let g=null;try{let l=await r();g=typeof l=="string"?l:null}catch{}g||c.push(s)}for(let s of f){if(P.has(s))continue;let r=m(i,`get_${s}`);if(!r)continue;let g=null;try{let l=await r();g=typeof l=="string"?l:null}catch{}g||p.push(s)}let y=c.length===0&&p.length===0;if(y)n(`[corsair:setup] '${e}' (${t}) is configured \u2713`);else{let s=[...c,...p];if(u==="cli"){let r=s.map(g=>`${g}=VALUE`).join(" ");n(`[corsair:setup] '${e}' (${t}) needs credentials. Run:
|
|
4
4
|
corsair setup --${e} ${r}`)}else{let r=[`[corsair:setup] '${e}' (${t}) needs credentials. Call:`];for(let g of c)r.push(` await corsair.keys.${e}.set_${g}(value)`);for(let g of p){let l=d==="default"?`corsair.${e}`:`corsair.withTenant(${JSON.stringify(d)}).${e}`;r.push(` await ${l}.keys.set_${g}(value)`)}n(r.join(`
|
package/dist/core.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { C as CORSAIR_INTERNAL, a as CorsairInternalConfig, D as DocSchemaFieldRow, b as DocSchemaShape, d as DocsApiEndpoint, e as DocsDbEntity,
|
|
1
|
+
export { A as AuthMissingError, C as CORSAIR_INTERNAL, a as CorsairInternalConfig, D as DocSchemaFieldRow, b as DocSchemaShape, d as DocsApiEndpoint, e as DocsDbEntity, g as DocsDbFilterField, h as DocsWebhook, E as EndpointSchemaResult, I as IntrospectPluginForDocsResult, L as ListOperationsOptions, P as PluginDocsIntrospection, R as ResolveConnectLinkResult, c as createCorsair, f as formatDocSchemaShape, i as introspectPluginForDocs, r as resolveConnectLink } from './index-Cadh5O_D.js';
|
|
2
2
|
import { CorsairDatabase } from './db.js';
|
|
3
|
-
import { O as OAuthConfig, A as AuthTypes,
|
|
4
|
-
export {
|
|
3
|
+
import { O as OAuthConfig, A as AuthTypes, f as AccountKeyManagerFor, I as IntegrationKeyManagerFor } from './index-CN2IlLdT.js';
|
|
4
|
+
export { g as AccountFieldNames, m as AllProviders, l as BASE_AUTH_FIELDS, h as BaseAuthFieldConfig, i as BaseKeyManager, e as BaseProviders, H as BeforeHookResult, o as BindEndpoints, a3 as BindWebhooks, a1 as Bivariant, p as BoundEndpointFn, q as BoundEndpointTree, a4 as BoundWebhook, B as BoundWebhookTree, c as CorsairClient, r as CorsairContext, s as CorsairEndpoint, u as CorsairErrorHandler, J as CorsairIntegration, K as CorsairKeyBuilder, L as CorsairKeyBuilderBase, d as CorsairPermissionsNamespace, a as CorsairPlugin, M as CorsairPluginContext, C as CorsairSingleTenantClient, b as CorsairTenantWrapper, a5 as CorsairWebhook, a6 as CorsairWebhookHandler, a7 as CorsairWebhookMatcher, N as EndpointHooks, Q as EndpointMetaEntry, E as EndpointPathsOf, S as EndpointRiskLevel, t as EndpointTree, F as EnforcePermissionOptions, G as EnforcePermissionResult, v as ErrorContext, w as ErrorHandler, x as ErrorHandlerAndMatchFunction, y as ErrorMatcher, j as IntegrationFieldNames, T as KeyBuilderContext, k as OAuth2IntegrationCredentials, U as PermissionMode, V as PermissionPolicy, n as PickAuth, P as PluginAuthConfig, X as PluginEndpointMeta, Y as PluginPermissionsConfig, R as RawWebhookRequest, Z as RequiredPluginEndpointMeta, _ as RequiredPluginEndpointSchemas, $ as RequiredPluginWebhookSchemas, z as RetryStrategies, D as RetryStrategy, a2 as UnionToIntersection, a0 as WebhookHooks, a8 as WebhookPathsOf, a9 as WebhookRequest, W as WebhookResponse, aa as WebhookTree } from './index-CN2IlLdT.js';
|
|
5
5
|
import 'kysely';
|
|
6
6
|
import 'zod';
|
|
7
7
|
import 'pg';
|
package/dist/core.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,
|
|
1
|
+
import{A as s,B as t,C as u,D as v,a,b,c,d,e,f,g,h,i,j,k,l,m,n,s as o,t as p,u as q,v as r}from"./chunk-6Q5ZX65O.js";import"./chunk-OZHME3EO.js";import"./chunk-ZGVIF3UY.js";import"./chunk-QAIKSQAD.js";export{a as AuthMissingError,j as BASE_AUTH_FIELDS,u as CORSAIR_INTERNAL,l as createAccountKeyManager,v as createCorsair,k as createIntegrationKeyManager,h as decryptConfig,d as decryptDEK,f as decryptWithDEK,g as encryptConfig,c as encryptDEK,e as encryptWithDEK,q as exchangeCodeForTokens,s as formatDocSchemaShape,b as generateDEK,n as initializeAccountDEK,m as initializeIntegrationDEK,t as introspectPluginForDocs,o as logEvent,p as logEventFromContext,i as reEncryptConfig,r as resolveConnectLink};
|
|
@@ -3,8 +3,8 @@ import { CorsairPluginSchema, PluginEntityClients } from './orm.js';
|
|
|
3
3
|
import { CorsairDatabase, CorsairDatabaseInput, CorsairPermission } from './db.js';
|
|
4
4
|
|
|
5
5
|
type AllErrors = 'RATE_LIMIT_ERROR' | 'AUTH_ERROR' | 'PERMISSION_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'SERVER_ERROR' | 'VALIDATION_ERROR' | 'NOT_FOUND_ERROR' | 'BAD_REQUEST_ERROR' | 'PARSING_ERROR' | 'DEFAULT' | (string & {});
|
|
6
|
-
declare const BaseProviders: readonly ["
|
|
7
|
-
type AllProviders = '
|
|
6
|
+
declare const BaseProviders: readonly ["airtable", "amplitude", "asana", "bitwarden", "bluesky", "box", "cal", "calendly", "cloudflare", "cursor", "discord", "dodopayments", "dropbox", "exa", "figma", "firecrawl", "fireflies", "github", "gitlab", "gmail", "googlecalendar", "googledrive", "googlesheets", "grafana", "hackernews", "hubspot", "intercom", "jira", "linear", "monday", "notion", "onedrive", "openweathermap", "oura", "outlook", "pagerduty", "posthog", "razorpay", "reddit", "resend", "sentry", "sharepoint", "slack", "spotify", "strava", "stripe", "tally", "tavily", "teams", "telegram", "todoist", "trello", "twitter", "twitterapiio", "typeform", "vapi", "xquik", "youtube", "zendesk", "zoom"];
|
|
7
|
+
type AllProviders = 'airtable' | 'amplitude' | 'asana' | 'bitwarden' | 'bluesky' | 'box' | 'cal' | 'calendly' | 'cloudflare' | 'cursor' | 'discord' | 'dodopayments' | 'dropbox' | 'exa' | 'figma' | 'firecrawl' | 'fireflies' | 'github' | 'gitlab' | 'gmail' | 'googlecalendar' | 'googledrive' | 'googlesheets' | 'grafana' | 'hackernews' | 'hubspot' | 'intercom' | 'jira' | 'linear' | 'monday' | 'notion' | 'onedrive' | 'openweathermap' | 'oura' | 'outlook' | 'pagerduty' | 'posthog' | 'razorpay' | 'reddit' | 'resend' | 'sentry' | 'sharepoint' | 'slack' | 'spotify' | 'strava' | 'stripe' | 'tally' | 'tavily' | 'teams' | 'telegram' | 'todoist' | 'trello' | 'twitter' | 'twitterapiio' | 'typeform' | 'vapi' | 'xquik' | 'youtube' | 'zendesk' | 'zoom' | (string & {});
|
|
8
8
|
type AuthTypes = 'oauth_2' | 'api_key' | 'bot_token';
|
|
9
9
|
type PickAuth<T extends AuthTypes> = T;
|
|
10
10
|
|
|
@@ -939,6 +939,21 @@ type CorsairIntegration<Plugins extends readonly CorsairPlugin[]> = {
|
|
|
939
939
|
args: unknown;
|
|
940
940
|
}) => string;
|
|
941
941
|
};
|
|
942
|
+
/**
|
|
943
|
+
* Connect link configuration for non-authenticated users.
|
|
944
|
+
* When a plugin endpoint is called but the user hasn't authenticated,
|
|
945
|
+
* Corsair generates a connect link the agent can present to the user.
|
|
946
|
+
* Only applies to plugins with an `oauthConfig`.
|
|
947
|
+
*/
|
|
948
|
+
connect?: {
|
|
949
|
+
baseUrl: string;
|
|
950
|
+
redirectUri: string;
|
|
951
|
+
onAuthMissing?: (opts: {
|
|
952
|
+
plugin: string;
|
|
953
|
+
connectUrl: string;
|
|
954
|
+
state: string;
|
|
955
|
+
}) => string;
|
|
956
|
+
};
|
|
942
957
|
};
|
|
943
958
|
|
|
944
959
|
/**
|
|
@@ -1125,4 +1140,4 @@ type CorsairSingleTenantClient<Plugins extends readonly CorsairPlugin[]> = Corsa
|
|
|
1125
1140
|
permissions: CorsairPermissionsNamespace;
|
|
1126
1141
|
};
|
|
1127
1142
|
|
|
1128
|
-
export { type RequiredPluginWebhookSchemas as $, type AuthTypes as A, type BoundWebhookTree as B, type
|
|
1143
|
+
export { type RequiredPluginWebhookSchemas as $, type AuthTypes as A, type BoundWebhookTree as B, type CorsairSingleTenantClient as C, type RetryStrategy as D, type EndpointPathsOf as E, type EnforcePermissionOptions as F, type EnforcePermissionResult as G, type BeforeHookResult as H, type IntegrationKeyManagerFor as I, type CorsairIntegration as J, type CorsairKeyBuilder as K, type CorsairKeyBuilderBase as L, type CorsairPluginContext as M, type EndpointHooks as N, type OAuthConfig as O, type PluginAuthConfig as P, type EndpointMetaEntry as Q, type RawWebhookRequest as R, type EndpointRiskLevel as S, type KeyBuilderContext as T, type PermissionMode as U, type PermissionPolicy as V, type WebhookResponse as W, type PluginEndpointMeta as X, type PluginPermissionsConfig as Y, type RequiredPluginEndpointMeta as Z, type RequiredPluginEndpointSchemas as _, type CorsairPlugin as a, type WebhookHooks as a0, type Bivariant$2 as a1, type UnionToIntersection$1 as a2, type BindWebhooks as a3, type BoundWebhook as a4, type CorsairWebhook as a5, type CorsairWebhookHandler as a6, type CorsairWebhookMatcher as a7, type WebhookPathsOf as a8, type WebhookRequest as a9, type WebhookTree as aa, type CorsairTenantWrapper as b, type CorsairClient as c, type CorsairPermissionsNamespace as d, BaseProviders as e, type AccountKeyManagerFor as f, type AccountFieldNames as g, type BaseAuthFieldConfig as h, type BaseKeyManager as i, type IntegrationFieldNames as j, type OAuth2IntegrationCredentials as k, BASE_AUTH_FIELDS as l, type AllProviders as m, type PickAuth as n, type BindEndpoints as o, type BoundEndpointFn as p, type BoundEndpointTree as q, type CorsairContext as r, type CorsairEndpoint as s, type EndpointTree as t, type CorsairErrorHandler as u, type ErrorContext as v, type ErrorHandler as w, type ErrorHandlerAndMatchFunction as x, type ErrorMatcher as y, type RetryStrategies as z };
|
|
@@ -1,6 +1,85 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { S as EndpointRiskLevel, a as CorsairPlugin, J as CorsairIntegration, b as CorsairTenantWrapper, C as CorsairSingleTenantClient } from './index-CN2IlLdT.js';
|
|
2
2
|
import { CorsairDatabase } from './db.js';
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* Error thrown when a plugin endpoint is called but the user has not authenticated
|
|
6
|
+
* with the required OAuth provider. Corsair intercepts this error and returns a
|
|
7
|
+
* connect link the agent can present to the user.
|
|
8
|
+
*/
|
|
9
|
+
declare class AuthMissingError extends Error {
|
|
10
|
+
pluginId: string;
|
|
11
|
+
constructor(pluginId: string, message?: string);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
type ResolveConnectLinkResult = {
|
|
15
|
+
/** Plugin ID extracted from the signed state. */
|
|
16
|
+
plugin: string;
|
|
17
|
+
/** Tenant ID extracted from the signed state. */
|
|
18
|
+
tenantId: string;
|
|
19
|
+
/** Human-readable provider name from the plugin's oauthConfig. */
|
|
20
|
+
providerName: string;
|
|
21
|
+
/** The full OAuth authorization URL. Redirect the user here to start the OAuth flow. */
|
|
22
|
+
oauthUrl: string;
|
|
23
|
+
/** The signed state parameter (pass to processOAuthCallback after redirect). */
|
|
24
|
+
state: string;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Resolves a connect link request on the consumer's `/connect` page.
|
|
28
|
+
*
|
|
29
|
+
* Call this when your connect page receives a `state` query parameter.
|
|
30
|
+
* It verifies the HMAC-signed state, looks up the plugin's OAuth config,
|
|
31
|
+
* and returns the full OAuth authorization URL so you just have to render
|
|
32
|
+
* a "Connect" button linking to `result.oauthUrl`.
|
|
33
|
+
*
|
|
34
|
+
* Uses the `redirectUri` from `createCorsair({ connect: { redirectUri } })`.
|
|
35
|
+
*
|
|
36
|
+
* @param corsair - The corsair instance
|
|
37
|
+
* @param state - The `state` query parameter from the connect URL
|
|
38
|
+
* @returns Plugin info and the full OAuth authorization URL
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* // On your /connect page handler:
|
|
43
|
+
* const { providerName, oauthUrl } = await resolveConnectLink(corsair, stateQueryParam)
|
|
44
|
+
* // Render a "Connect {providerName}" button linking to oauthUrl
|
|
45
|
+
* // After OAuth redirect, call processOAuthCallback(corsair, { code, state, redirectUri })
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
declare function resolveConnectLink(corsair: unknown, state: string): Promise<ResolveConnectLinkResult>;
|
|
49
|
+
|
|
50
|
+
type FormFieldSchema = {
|
|
51
|
+
kind: 'string';
|
|
52
|
+
optional: boolean;
|
|
53
|
+
description?: string;
|
|
54
|
+
enum?: string[];
|
|
55
|
+
} | {
|
|
56
|
+
kind: 'number';
|
|
57
|
+
optional: boolean;
|
|
58
|
+
description?: string;
|
|
59
|
+
} | {
|
|
60
|
+
kind: 'boolean';
|
|
61
|
+
optional: boolean;
|
|
62
|
+
description?: string;
|
|
63
|
+
} | {
|
|
64
|
+
kind: 'literal';
|
|
65
|
+
optional: boolean;
|
|
66
|
+
description?: string;
|
|
67
|
+
value: string | number | boolean;
|
|
68
|
+
} | {
|
|
69
|
+
kind: 'object';
|
|
70
|
+
optional: boolean;
|
|
71
|
+
description?: string;
|
|
72
|
+
fields: Record<string, FormFieldSchema>;
|
|
73
|
+
} | {
|
|
74
|
+
kind: 'array';
|
|
75
|
+
optional: boolean;
|
|
76
|
+
description?: string;
|
|
77
|
+
items: FormFieldSchema;
|
|
78
|
+
} | {
|
|
79
|
+
kind: 'unknown';
|
|
80
|
+
optional: boolean;
|
|
81
|
+
description?: string;
|
|
82
|
+
};
|
|
4
83
|
/** @deprecated get_schema now returns a plain string. This type is kept for backwards compatibility. */
|
|
5
84
|
type EndpointSchemaResult = {
|
|
6
85
|
description?: string;
|
|
@@ -89,6 +168,11 @@ type IntrospectPluginForDocsResult = {
|
|
|
89
168
|
ok: false;
|
|
90
169
|
error: string;
|
|
91
170
|
};
|
|
171
|
+
/**
|
|
172
|
+
* Renders a {@link DocSchemaShape} as a TypeScript-like block with `// description`
|
|
173
|
+
* comments on each field row. Used by `getSchema`, catalog builders, and hosted MCP.
|
|
174
|
+
*/
|
|
175
|
+
declare function formatDocSchemaShape(shape: DocSchemaShape | undefined, depth?: number): string;
|
|
92
176
|
/**
|
|
93
177
|
* Returns structured API, webhook, and DB operation metadata for a single plugin.
|
|
94
178
|
* Intended for **documentation generators** inside the Corsair repo (or tooling that depends
|
|
@@ -119,6 +203,15 @@ type CorsairInternalConfig = {
|
|
|
119
203
|
args: unknown;
|
|
120
204
|
}) => string;
|
|
121
205
|
};
|
|
206
|
+
connect?: {
|
|
207
|
+
baseUrl: string;
|
|
208
|
+
redirectUri: string;
|
|
209
|
+
onAuthMissing?: (opts: {
|
|
210
|
+
plugin: string;
|
|
211
|
+
connectUrl: string;
|
|
212
|
+
state: string;
|
|
213
|
+
}) => string;
|
|
214
|
+
};
|
|
122
215
|
};
|
|
123
216
|
/**
|
|
124
217
|
* Creates a Corsair integration with multi-tenancy enabled.
|
|
@@ -140,4 +233,4 @@ declare function createCorsair<const Plugins extends readonly CorsairPlugin[]>(c
|
|
|
140
233
|
multiTenancy?: false | undefined;
|
|
141
234
|
}): CorsairSingleTenantClient<Plugins>;
|
|
142
235
|
|
|
143
|
-
export { CORSAIR_INTERNAL as C, type DocSchemaFieldRow as D, type EndpointSchemaResult as E, type IntrospectPluginForDocsResult as I, type ListOperationsOptions as L, type PluginDocsIntrospection as P, type CorsairInternalConfig as a, type DocSchemaShape as b, createCorsair as c, type DocsApiEndpoint as d, type DocsDbEntity as e, type DocsDbFilterField as
|
|
236
|
+
export { AuthMissingError as A, CORSAIR_INTERNAL as C, type DocSchemaFieldRow as D, type EndpointSchemaResult as E, type FormFieldSchema as F, type IntrospectPluginForDocsResult as I, type ListOperationsOptions as L, type PluginDocsIntrospection as P, type ResolveConnectLinkResult as R, type CorsairInternalConfig as a, type DocSchemaShape as b, createCorsair as c, type DocsApiEndpoint as d, type DocsDbEntity as e, formatDocSchemaShape as f, type DocsDbFilterField as g, type DocsWebhook as h, introspectPluginForDocs as i, resolveConnectLink as r };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { L as ListOperationsOptions } from './index-
|
|
2
|
-
export { c as createCorsair } from './index-
|
|
3
|
-
import {
|
|
1
|
+
import { F as FormFieldSchema, L as ListOperationsOptions } from './index-Cadh5O_D.js';
|
|
2
|
+
export { A as AuthMissingError, R as ResolveConnectLinkResult, c as createCorsair, f as formatDocSchemaShape, r as resolveConnectLink } from './index-Cadh5O_D.js';
|
|
3
|
+
import { C as CorsairSingleTenantClient, a as CorsairPlugin, b as CorsairTenantWrapper, c as CorsairClient, d as CorsairPermissionsNamespace, B as BoundWebhookTree, R as RawWebhookRequest, e as BaseProviders, W as WebhookResponse } from './index-CN2IlLdT.js';
|
|
4
4
|
export { SetupCorsairOptions, setupCorsair } from './setup.js';
|
|
5
5
|
import './db.js';
|
|
6
6
|
import 'kysely';
|
|
@@ -51,6 +51,18 @@ declare function listOperations(corsair: AnyCorsairInstance, options?: ListOpera
|
|
|
51
51
|
* // "Path not found. Available operations:\n slack: slack.api.channels.list, ..."
|
|
52
52
|
*/
|
|
53
53
|
declare function getSchema(corsair: AnyCorsairInstance, path: string): string;
|
|
54
|
+
/**
|
|
55
|
+
* Returns a machine-readable, JSON-serializable form schema for a given operation path.
|
|
56
|
+
* Unlike {@link getSchema} (which returns a TypeScript-style string), this returns
|
|
57
|
+
* structured field definitions suitable for driving dynamic form UIs.
|
|
58
|
+
*
|
|
59
|
+
* Returns `null` if the path does not resolve to a known endpoint.
|
|
60
|
+
*/
|
|
61
|
+
declare function getStructuredSchema(corsair: AnyCorsairInstance, path: string): {
|
|
62
|
+
input: FormFieldSchema | null;
|
|
63
|
+
output: FormFieldSchema | null;
|
|
64
|
+
description?: string;
|
|
65
|
+
} | null;
|
|
54
66
|
|
|
55
67
|
/**
|
|
56
68
|
* The corsair instance type for permission execution.
|
|
@@ -157,4 +169,4 @@ declare function processWebhook(corsair: CorsairInstance, headers: WebhookHeader
|
|
|
157
169
|
[x: string]: string | string[] | undefined;
|
|
158
170
|
}): Promise<WebhookFilterResult>;
|
|
159
171
|
|
|
160
|
-
export { type AnyCorsairInstance, ListOperationsOptions, type PermissionExecuteResult, executePermission, getSchema, listOperations, processWebhook };
|
|
172
|
+
export { type AnyCorsairInstance, FormFieldSchema, ListOperationsOptions, type PermissionExecuteResult, executePermission, getSchema, getStructuredSchema, listOperations, processWebhook };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as A}from"./chunk-RCM2FWFL.js";import{A as x,C,D as T,a as I,v as O,w as k,x as y,y as b,z as w}from"./chunk-6Q5ZX65O.js";import"./chunk-UBM25HVI.js";import"./chunk-OZHME3EO.js";import"./chunk-3USHGH6P.js";import"./chunk-ZGVIF3UY.js";import"./chunk-QAIKSQAD.js";function h(n){let r=n[C];if(!r)throw new Error("listOperations / getSchema: invalid corsair instance. Pass the value returned by createCorsair() or corsair.withTenant().");return r.plugins}function B(n,r){let o=b(h(n),r);return typeof o=="string"?o:Array.isArray(o)?o.join(`
|
|
2
2
|
`):Object.values(o).flat().join(`
|
|
3
|
-
`)}function
|
|
3
|
+
`)}function E(n,r){return w(h(n),r)}function F(n,r){return y(h(n),r)}var $=Symbol.for("corsair:internal");function j(n,r){let o=n;for(let e of r){if(!o||typeof o!="object")return null;o=o[e]}return typeof o=="function"?o:null}function S(n){return n[$]?.database}async function _(n,r){let o=new Date().toISOString(),e=await n.permissions.find_by_token(r);if(!e)return console.error("executePermission: no permission found for token."),{error:"executePermission: no permission found for token."};if(e.status!=="approved")return console.error(`executePermission: permission '${e.id}' is '${e.status}', expected 'approved'.`),{endpoint:e.endpoint,plugin:e.plugin,result:null,error:`executePermission: permission '${e.id}' is '${e.status}', expected 'approved'.`};if(e.expires_at<o){let i=S(n);return i&&await i.db.updateTable("corsair_permissions").set({status:"expired",updated_at:new Date}).where("id","=",e.id).execute(),console.error(`executePermission: permission '${e.id}' has expired.`),{error:`executePermission: permission '${e.id}' has expired.`,endpoint:e.endpoint,plugin:e.plugin,result:null}}let t=e.tenant_id??"default",g=(n.withTenant?n.withTenant(t):n)[e.plugin];if(!g?.api)return console.error(`executePermission: plugin '${e.plugin}' not found or has no API on this corsair instance.`),{error:`executePermission: plugin '${e.plugin}' not found or has no API on this corsair instance.`,plugin:e.plugin,endpoint:e.endpoint,result:null};let c=j(g.api,e.endpoint.split("."));if(!c)return console.error(`executePermission: endpoint '${e.endpoint}' not found in plugin '${e.plugin}'.`),{endpoint:e.endpoint,plugin:e.plugin,result:null,error:`executePermission: endpoint '${e.endpoint}' not found in plugin '${e.plugin}'.`};await n.permissions.set_executing(e.id);try{let i=typeof e.args=="string"?JSON.parse(e.args):e.args,u=await c(i);return await n.permissions.set_completed(e.id),{plugin:e.plugin,endpoint:e.endpoint,result:u}}catch(i){let u=i instanceof Error?i.message:String(i),d=S(n);return d&&await d.db.updateTable("corsair_permissions").set({status:"failed",error:u,updated_at:new Date}).where("id","=",e.id).execute(),{plugin:e.plugin,endpoint:e.endpoint,result:null,error:u}}}function v(n){return n!==null&&typeof n=="object"&&"match"in n&&"handler"in n&&typeof n.match=="function"&&typeof n.handler=="function"}function R(n,r,o=[]){for(let[e,t]of Object.entries(n))if(v(t)){if(t.match(r))return{webhook:t,path:[...o,e]}}else if(t&&typeof t=="object"){let s=R(t,r,[...o,e]);if(s)return s}return null}function N(n){let r={};for(let[o,e]of Object.entries(n))r[o.toLowerCase()]=Array.isArray(e)?e[0]:e;return r}function L(n){let r=n["x-goog-resource-uri"],o=n["x-goog-channel-id"];if(!r||!o)return null;let e={resourceId:n["x-goog-resource-id"]||"",resourceState:n["x-goog-resource-state"]||"",resourceUri:r,channelId:o,channelExpiration:n["x-goog-channel-expiration"]||""};return r.includes("/drive/")&&(e.kind="drive#change"),{message:{data:Buffer.from(JSON.stringify(e)).toString("base64"),messageId:n["x-goog-message-number"]||""}}}async function D(n,r,o,e){let t=N(r),s=typeof o=="string"?JSON.parse(o):o;(!s||typeof s=="object"&&Object.keys(s).length===0)&&t["x-goog-resource-uri"]&&(s=L(t)||s);let c={headers:t,body:s},i=e?.tenantId||"default",u=n.withTenant?n.withTenant(i):n,d=k;for(let l of d){let p=u[l];if(!p||!p.webhooks||p.pluginWebhookMatcher&&!p.pluginWebhookMatcher(c))continue;let f=R(p.webhooks,c);if(!f)continue;let m=f.path.join("."),P={payload:s,headers:t,rawBody:typeof o=="string"?o:JSON.stringify(o)};try{let a=await f.webhook.handler(P),W=!!Object.keys(a.returnToSender||{})?.length;return{plugin:l,action:m,body:s,response:W?{...a?.returnToSender,success:!0}:{success:!0},...a.responseHeaders&&{responseHeaders:a.responseHeaders}}}catch(a){return console.error(`Error executing webhook handler for ${l}.${m}:`,a),{plugin:l,action:m,body:s,response:{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}}return{plugin:null,action:null,body:null}}export{I as AuthMissingError,T as createCorsair,_ as executePermission,x as formatDocSchemaShape,E as getSchema,F as getStructuredSchema,B as listOperations,D as processWebhook,O as resolveConnectLink,A as setupCorsair};
|
package/dist/oauth.d.ts
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
type OAuthState = {
|
|
2
2
|
plugin: string;
|
|
3
3
|
tenantId: string;
|
|
4
|
+
iat: number;
|
|
4
5
|
};
|
|
5
6
|
declare function encodeOAuthState(plugin: string, tenantId: string): string;
|
|
6
|
-
declare function decodeOAuthState(state: string
|
|
7
|
+
declare function decodeOAuthState(state: string, { maxAgeMs }?: {
|
|
8
|
+
maxAgeMs?: number;
|
|
9
|
+
}): OAuthState | null;
|
|
10
|
+
|
|
7
11
|
type GenerateOAuthUrlOptions = {
|
|
8
12
|
tenantId: string;
|
|
9
13
|
redirectUri: string;
|
package/dist/oauth.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{C as x,b as C,c as O,k as p,l as m,o as f,p as _,q as A,r as y,u as b}from"./chunk-6Q5ZX65O.js";import{b as P}from"./chunk-UBM25HVI.js";import"./chunk-OZHME3EO.js";import"./chunk-3USHGH6P.js";import"./chunk-ZGVIF3UY.js";import"./chunk-QAIKSQAD.js";import*as E from"querystring";function I(n){let e=n[x];if(!e)throw new Error("Invalid corsair instance");return e}function U(n,e){let o=n.plugins.find(a=>a.id===e);if(!o)throw new Error(`Plugin '${e}' not found`);return o}function N(n){let e=n.oauthConfig;if(!e)throw new Error(`Plugin '${n.id}' has no oauthConfig`);return e}async function R(n,e,o,a){let i=P(n),t=await i.integrations.findByName(e);if(!t)throw new Error(`Integration '${e}' not found. Run setupCorsair first.`);if(await i.accounts.findOne({tenant_id:o,integration_id:t.id}))return;let r=C(),s=await O(r,a);await i.accounts.create({tenant_id:o,integration_id:t.id,config:{},dek:s})}async function S(n,e,o){let{tenantId:a,redirectUri:i}=o,t=I(n);if(!t.database)throw new Error("No database configured on corsair instance");let u=U(t,e),r=N(u),d=await p({authType:"oauth_2",integrationName:e,kek:t.kek,database:t.database}).get_client_id();if(!d)throw new Error(`client_id not configured for '${e}'`);let g=A(f(e,a),t.kek),l={...r.authParams,client_id:d,redirect_uri:i,response_type:"code",scope:r.scopes.join(" "),state:g};return{url:`${r.authUrl}?${E.stringify(l)}`,state:g}}async function K(n,e){let{code:o,state:a,redirectUri:i}=e,t=I(n),u=y(a,t.kek);if(!u)throw new Error("Invalid or tampered state parameter");let{plugin:r,tenantId:s}=u;if(!t.database)throw new Error("No database configured on corsair instance");let d=U(t,r),g=N(d),l=p({authType:"oauth_2",integrationName:r,kek:t.kek,database:t.database}),k=await l.get_client_id(),w=await l.get_client_secret();if(!k||!w)throw new Error(`Credentials not configured for '${r}'`);await R(t.database,r,s,t.kek);let c=await b(o,k,w,g,i);if(!c.access_token)throw new Error(`No access_token returned from ${g.providerName}`);let h=m({authType:"oauth_2",integrationName:r,tenantId:s,kek:t.kek,database:t.database});return await h.set_access_token(c.access_token),c.refresh_token&&await h.set_refresh_token(c.refresh_token),c.expires_in&&await h.set_expires_at(String(Math.floor(Date.now()/1e3)+c.expires_in)),{plugin:r,tenantId:s}}export{_ as decodeOAuthState,f as encodeOAuthState,S as generateOAuthUrl,K as processOAuthCallback};
|
package/dist/setup.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as CorsairPlugin, C as CorsairSingleTenantClient, b as CorsairTenantWrapper } from './index-CN2IlLdT.js';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import './orm.js';
|
|
4
4
|
import './db.js';
|
package/dist/setup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o}from"./chunk-
|
|
1
|
+
import{a as o}from"./chunk-RCM2FWFL.js";import"./chunk-6Q5ZX65O.js";import"./chunk-UBM25HVI.js";import"./chunk-OZHME3EO.js";import"./chunk-3USHGH6P.js";import"./chunk-ZGVIF3UY.js";import"./chunk-QAIKSQAD.js";export{o as setupCorsair};
|
package/package.json
CHANGED
package/dist/chunk-XYRVJ76B.js
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import{a as be,b as te}from"./chunk-OZHME3EO.js";import{a as ke}from"./chunk-ZGVIF3UY.js";import{createCipheriv as we,createDecipheriv as Te,randomBytes as G,scrypt as He}from"crypto";import{promisify as Ue}from"util";var Ce=Ue(He),J="aes-256-gcm",Pe=12,V=16,qe=16,H=32;function K(){return G(H).toString("base64")}async function M(e,t){let n=G(qe),r=await Ce(t,n,H),o=G(Pe),i=we(J,r,o,{authTagLength:V}),s=Buffer.concat([i.update(e,"utf8"),i.final()]),a=i.getAuthTag();return[n.toString("base64"),o.toString("base64"),a.toString("base64"),s.toString("base64")].join(":")}async function O(e,t){let[n,r,o,i]=e.split(":");if(!n||!r||!o||!i)throw new Error("Invalid encrypted DEK format");let s=Buffer.from(n,"base64"),a=Buffer.from(r,"base64"),d=Buffer.from(o,"base64"),c=Buffer.from(i,"base64"),l=await Ce(t,s,H),p=Te(J,l,a,{authTagLength:V});return p.setAuthTag(d),Buffer.concat([p.update(c),p.final()]).toString("utf8")}function oe(e,t){let n=Buffer.from(t,"base64"),r=G(Pe),o=we(J,n,r,{authTagLength:V}),i=Buffer.concat([o.update(e,"utf8"),o.final()]),s=o.getAuthTag();return[r.toString("base64"),s.toString("base64"),i.toString("base64")].join(":")}function re(e,t){let[n,r,o]=e.split(":");if(!n||!r||!o)throw new Error("Invalid encrypted data format");let i=Buffer.from(t,"base64"),s=Buffer.from(n,"base64"),a=Buffer.from(r,"base64"),d=Buffer.from(o,"base64"),c=Te(J,i,s,{authTagLength:V});return c.setAuthTag(a),Buffer.concat([c.update(d),c.final()]).toString("utf8")}function Z(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=oe(o,t);return n}function S(e,t){let n={};for(let[r,o]of Object.entries(e))n[r]=re(o,t);return n}function U(e,t,n){let r=S(e,t);return Z(r,n)}function Y(e,t){let n=[];e||n.push("database"),t||n.push("kek");let r={};return new Proxy(r,{get(o,i){let s=n.length>1;throw new Error(`corsair.keys.${String(i)}: Cannot access keys because ${n.join(" and ")} ${s?"are":"is"} not configured. Provide both 'database' and 'kek' in createCorsair() to enable key management.
|
|
2
|
-
|
|
3
|
-
To generate a KEK, run: openssl rand -base64 ${H}`)}})}var q={oauth_2:{integration:["client_id","client_secret","redirect_url"],account:["access_token","refresh_token","expires_at","scope","webhook_signature"]},api_key:{integration:[],account:["api_key","webhook_signature"]},bot_token:{integration:[],account:["bot_token","webhook_signature"]}};function xe(e,t,n){let r={};for(let o of n)r[`get_${o}`]=async()=>(await e())[o]??null,r[`set_${o}`]=async i=>{let s=[null,void 0,""].includes(i)?null:i;await t({[o]:s})};return r}var ie=e=>{if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e};function Q(e){let{authType:t,integrationName:n,kek:r,database:o,extraIntegrationFields:i=[]}=e,s=[...q[t].integration,...i],a=null,d={kek:r,integrationName:n,getIntegration:async()=>{if(a)return a;let u=await o.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!u)throw new Error(`Integration "${n}" not found. Make sure to create the integration first.`);return a={id:u.id,config:ie(u.config),dek:u.dek??null},a},updateIntegration:async u=>{let f=await d.getIntegration();await o.db.updateTable("corsair_integrations").set({...u.config!==void 0?{config:u.config}:{},...u.dek!==void 0?{dek:u.dek}:{},updated_at:new Date}).where("id","=",f.id).execute(),a=null}},c=null,l=async()=>{if(c)return c;let u=await d.getIntegration();if(!u.dek)throw new Error(`No DEK found for integration "${n}". Initialize the integration first.`);return c=await O(u.dek,r),c},p=async()=>{let u=await d.getIntegration(),f=await l(),m=u.config;return!m||Object.keys(m).length===0?{}:S(m,f)};return{get_dek:l,issue_new_dek:async()=>{let u=await d.getIntegration(),f=K(),m={};if(u.dek){let P=await O(u.dek,r),b=u.config;b&&Object.keys(b).length>0&&(m=U(b,P,f))}let k=await M(f,r);return await d.updateIntegration({config:m,dek:k}),c=f,f},...xe(p,async u=>{let f=await l(),m;try{m=await p()}catch(b){console.error(`[corsair] Failed to decrypt config for integration "${n}", starting fresh:`,b),m={}}let k={...m};for(let[b,y]of Object.entries(u))y===null?delete k[b]:k[b]=y;let P=Z(k,f);await d.updateIntegration({config:P})},s)}}function X(e){let{authType:t,integrationName:n,tenantId:r,kek:o,database:i,extraAccountFields:s=[]}=e,a=[...q[t].account,...s],d=null,c=null,l=async()=>{if(c)return c;let y=await i.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!y)throw new Error(`Integration "${n}" not found. Make sure to create the integration first.`);return c={id:y.id,config:ie(y.config),dek:y.dek??null},c},p={kek:o,integrationName:n,tenantId:r,getIntegration:l,getAccount:async()=>{if(d)return d;let y=await l(),w=await i.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",r).where("integration_id","=",y.id).executeTakeFirst();if(!w)throw new Error(`Account not found for tenant "${r}" and integration "${n}". Make sure to create the account first.`);return d={id:w.id,config:ie(w.config),dek:w.dek??null},d},updateAccount:async y=>{let w=await p.getAccount();await i.db.updateTable("corsair_accounts").set({...y.config!==void 0?{config:y.config}:{},...y.dek!==void 0?{dek:y.dek}:{},updated_at:new Date}).where("id","=",w.id).execute(),d=null}},h=null,g=null,u=async()=>{if(h)return h;let y=await p.getAccount();if(!y.dek)throw new Error(`No DEK found for account (tenant: "${r}", integration: "${n}"). Initialize the account first.`);return h=await O(y.dek,o),h},f=async()=>{if(g)return g;let y=await p.getIntegration();if(!y.dek)throw new Error(`No DEK found for integration "${n}". Initialize the integration first.`);return g=await O(y.dek,o),g},m=async()=>{let y=await p.getAccount(),w=await u(),T=y.config;return!T||Object.keys(T).length===0?{}:S(T,w)},k=async()=>{let y=await p.getIntegration(),w=await f(),T=y.config;return!T||Object.keys(T).length===0?{}:S(T,w)},b={get_dek:u,issue_new_dek:async()=>{let y=await p.getAccount(),w=K(),T={};if(y.dek){let C=await O(y.dek,o),A=y.config;A&&Object.keys(A).length>0&&(T=U(A,C,w))}let I=await M(w,o);return await p.updateAccount({config:T,dek:I}),h=w,w},...xe(m,async y=>{let w=await u(),T;try{T=await m()}catch(A){console.error(`[corsair] Failed to decrypt config for account (tenant: "${r}", integration: "${n}"), starting fresh:`,A),T={}}let I={...T};for(let[A,E]of Object.entries(y))E===null?delete I[A]:I[A]=E;let C=Z(I,w);await p.updateAccount({config:C})},a)};return t==="oauth_2"&&(b.get_integration_credentials=async()=>{let y=await k();return{client_id:y.client_id||null,client_secret:y.client_secret||null,redirect_url:y.redirect_url??null}}),b}async function Ae(e,t,n){let r=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!r)throw new Error(`Integration "${t}" not found.`);let o=K(),i=await M(o,n);return await e.db.updateTable("corsair_integrations").set({dek:i,updated_at:new Date}).where("id","=",r.id).execute(),o}async function Ee(e,t,n,r){let o=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!o)throw new Error(`Integration "${t}" not found.`);let i=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",n).where("integration_id","=",o.id).executeTakeFirst();if(!i)throw new Error(`Account not found for tenant "${n}" and integration "${t}".`);let s=K(),a=await M(s,r);return await e.db.updateTable("corsair_accounts").set({dek:a,updated_at:new Date}).where("id","=",i.id).execute(),s}var ze=async(e,t)=>(console.error(`[corsair:${t.pluginId}:${t.operation}]`,{error:e.message,input:t.input}),{maxRetries:0});async function Re(e,t,n,r,o){let i={pluginId:t,operation:n,input:r,originalError:e},s=Object.keys(o).find(c=>o[c]?.match(e,i));return await(o[s||"DEFAULT"]?.handler||ze)(e,i)}import{randomBytes as Ge}from"crypto";import{v4 as Je}from"uuid";var Ve={open:{read:"allow",write:"allow",destructive:"allow"},cautious:{read:"allow",write:"allow",destructive:"require_approval"},strict:{read:"allow",write:"require_approval",destructive:"deny"},readonly:{read:"allow",write:"deny",destructive:"deny"}};function Ye(e,t,n){return n!==void 0?n:Ve[t][e]}function De(e){let t=/(\d+)(d|h|m|s)/g,n=0,r;for(;(r=t.exec(e))!==null;){let o=parseInt(r[1],10);switch(r[2]){case"d":n+=o*864e5;break;case"h":n+=o*36e5;break;case"m":n+=o*6e4;break;case"s":n+=o*1e3;break}}return n>0?n:600*1e3}function _e(e){return{async find_by_permission_id(t){if(e)return e.db.selectFrom("corsair_permissions").selectAll().where("id","=",t).executeTakeFirst()},async find_by_token(t){if(e)return e.db.selectFrom("corsair_permissions").selectAll().where("token","=",t).executeTakeFirst()},async set_executing(t){e&&await e.db.updateTable("corsair_permissions").set({status:"executing",updated_at:new Date}).where("id","=",t).execute()},async set_completed(t){e&&await e.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",t).execute()}}}async function Ie(e,t,n){let r=Date.now()+n;for(;Date.now()<r;){let o=await e.db.selectFrom("corsair_permissions").select(["id","status"]).where("id","=",t).executeTakeFirst();if(!o)return{result:"blocked",reason:"pending"};if(o.status==="approved")return{result:"allow",onComplete:async()=>{await e.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",t).execute()}};if(o.status==="denied")return{result:"blocked",reason:"denied"};if(o.status==="expired"||o.status==="failed")return{result:"blocked",reason:"timeout"};await new Promise(i=>setTimeout(i,500))}return{result:"blocked",reason:"timeout"}}async function ve(e){let t=Ye(e.riskLevel,e.mode,e.override);if(t==="allow")return{result:"allow"};let n=e.meta?.irreversible?" (irreversible)":"",r=e.meta?.description?`${e.meta.description}${n}`:`${e.pluginId}.${e.endpointPath}${n}`;if(t==="deny"||!e.db)return console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 denied by permission mode '${e.mode}'.`,`
|
|
4
|
-
Action: ${r}`,`
|
|
5
|
-
To allow this, update the permission mode or add an override in your corsair config.`),{result:"blocked",reason:"policy"};let o=JSON.stringify(e.args),i=new Date().toISOString(),s=e.tenantId??"default",a=await e.db.db.selectFrom("corsair_permissions").selectAll().where("plugin","=",e.pluginId).where("endpoint","=",e.endpointPath).where("args","=",o).where("tenant_id","=",s).where("expires_at",">",i).where("status","in",["pending","approved","executing"]).orderBy("created_at","desc").limit(1).executeTakeFirst();if(a){if(a.status==="approved"){let u=e.db,f=a.id;return{result:"allow",onComplete:async()=>{await u.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",f).execute()}}}return a.status==="executing"?{result:"allow"}:(console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval already pending.`,`
|
|
6
|
-
Action: ${r}`,`
|
|
7
|
-
Permission ID: ${a.id}`,`
|
|
8
|
-
Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?Ie(e.db,a.id,e.timeoutMs??600*1e3):{result:"blocked",reason:"pending",id:a.id,token:a.token})}let d=Je(),c=Ge(32).toString("hex"),l=e.timeoutMs??600*1e3,p=new Date(Date.now()+l).toISOString();return await e.db.db.insertInto("corsair_permissions").values({id:d,created_at:new Date,updated_at:new Date,token:c,plugin:e.pluginId,endpoint:e.endpointPath,args:o,tenant_id:s,status:"pending",expires_at:p}).execute(),console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval required.`,`
|
|
9
|
-
Action: ${r}`,`
|
|
10
|
-
Permission ID: ${d}`,`
|
|
11
|
-
Permission token: ${c}`,`
|
|
12
|
-
Expires at: ${p}`,`
|
|
13
|
-
Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?Ie(e.db,d,l):{result:"blocked",reason:"pending",id:d,token:c}}function Qe(e){return typeof e=="function"}function se({endpoints:e,hooks:t,ctx:n,tree:r,pluginId:o,errorHandlers:i,currentPath:s=[],keyBuilder:a,permissionsConfig:d,endpointMeta:c,database:l,approvalConfig:p,tenantId:h}){for(let[g,u]of Object.entries(e)){let f=t?.[g];if(Qe(u)){let m=f,k=[...s,g].join("."),P=async(b={})=>{let y;if(d){let E=c?.[k],{result:B,reason:v,onComplete:W,token:F,id:$}=await ve({pluginId:o,endpointPath:k,args:b,mode:d.mode,override:d.overrides?.[k],riskLevel:E?.riskLevel??"write",meta:E,db:l,timeoutMs:p?De(p.timeout):void 0,tenantId:h,approvalMode:p?.mode});if(B==="blocked"){let x;throw v==="denied"?x=`Action '${k}' was denied by the user. Await further instructions before proceeding.`:v==="policy"?x=`Action '${k}' is blocked by the permission policy. Update the corsair config to allow it.`:v==="timeout"?x=`Action '${k}' timed out waiting for approval.`:p?.formatAsyncMessage&&F&&$?x=p.formatAsyncMessage({token:F,id:$,plugin:o,endpoint:k,args:b}):x=`Action '${k}' requires user approval before it can run.`,new Error(x)}y=W}let w=async(E,B,v)=>{try{return await u(B,v)}catch(W){if(W instanceof Error){let F=await Re(W,o,k,typeof v=="object"&&v!==null?v:{args:v},i);if(E<(F.maxRetries||0)){let $=E+1;console.log(`Retrying (${$} / ${F.maxRetries})...`);let x;if(F.headersRetryAfterMs)x=F.headersRetryAfterMs;else switch(F.retryStrategy){case"exponential_backoff":x=Math.pow(2,$-1)*1e3;break;case"exponential_backoff_jitter":let ne=Math.pow(2,$-1)*1e3,We=(Math.random()-.5)*1e3;x=Math.max(0,ne+We);break;case"linear_1s":x=1e3;break;case"linear_2s":x=2e3;break;case"linear_3s":x=3e3;break;case"linear_4s":x=4e3;break;default:x=1e3;break}await new Promise(ne=>setTimeout(ne,x)),await w($,B,v),console.log(`[corsair:${o}:${k}] Retry strategy:`,F)}}throw W}},T=a?await a(n,"endpoint"):void 0;if(!m?.before&&!m?.after){let E=await w(0,{...n,key:T},b);return await y?.(),E}let I={...n,key:T},C=m.before?await m.before(I,b):{ctx:I,args:b,continue:!0,passToAfter:void 0};if(C.continue===!1)return;let A=await w(0,C.ctx,C.args);return await m.after?.(C.ctx,A,C.passToAfter),await y?.(),A};r[g]=P}else if(u&&typeof u=="object"){let m={};se({endpoints:u,hooks:f,ctx:n,tree:m,pluginId:o,errorHandlers:i,currentPath:[...s,g],keyBuilder:a,permissionsConfig:d,endpointMeta:c,database:l,approvalConfig:p,tenantId:h}),r[g]=m}}}function Xe(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function ae({webhooks:e,hooks:t,ctx:n,webhooksTree:r,keyBuilder:o}){for(let[i,s]of Object.entries(e)){let a=t?.[i];if(Xe(s)){let d=a,c=async l=>{let p=(g,u)=>s.handler(g,u),h=o?await o(n,"webhook"):void 0;return!d?.before&&!d?.after?p({...n,key:h},l):(async()=>{let g={...n,key:h},u=d.before?await d.before(g,l):{ctx:g,args:l,continue:!0,passToAfter:void 0};if(u.continue===!1)return;let f=await p(u.ctx,u.args);return f?.success===!0&&await d.after?.(u.ctx,f,u.passToAfter),f})()};r[i]={match:s.match,handler:c}}else if(s&&typeof s=="object"){let d={};ae({webhooks:s,hooks:a,ctx:n,webhooksTree:d,keyBuilder:o}),r[i]=d}}}function en(e,t,n){let r=null;return async()=>{if(r)return r;if(!e)throw new Error("Database not configured");let o=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!o)throw new Error(`Integration "${t}" not found. Make sure to create the integration first.`);let i=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",n).where("integration_id","=",o.id).executeTakeFirst();if(!i)throw new Error(`Account not found for tenant "${n}" and integration "${t}". Make sure to create the account first.`);return r=i.id,r}}function nn(e,t,n,r,o){return e?te(e.db,t,n,r,o):{findByEntityId:async()=>null,findById:async()=>null,findManyByEntityIds:async()=>[],list:async()=>[],search:async()=>[],upsertByEntityId:async()=>{throw new Error("Database not configured")},deleteById:async()=>!1,deleteByEntityId:async()=>!1,count:async()=>0}}function ce(e,t){let{database:n,tenantId:r,kek:o,rootErrorHandlers:i,approvalConfig:s}=t,a={},d={};for(let c of e)a[c.id]={},d[c.id]={};for(let c of e){let l=c.schema,p=r??"default",h=en(n,c.id,p);if(l?.entities){let C={};for(let[A,E]of Object.entries(l.entities)){let B=n?te(n.db,h,A,l.version,E):nn(void 0,h,A,l.version,E);C[A]=B}d[c.id].db=C,a[c.id].db=C}let g=c.options,u=c.authConfig,f;if(n&&o&&g?.authType){let C=u?.[g.authType]?.account??[];f=X({authType:g.authType,integrationName:c.id,tenantId:p,kek:o,database:n,extraAccountFields:C}),a[c.id].keys=f}let m={database:n,db:d[c.id]?.db??{},$getAccountId:h,...c.options?{options:c.options}:{},...f?{keys:f,authType:g?.authType}:{},...r?{tenantId:r}:{}},k=c.endpoints??{},P=c.hooks,b={...i,...c.errorHandlers},y={},w=c.options?.permissions;se({endpoints:k,hooks:P,ctx:m,tree:y,pluginId:c.id,errorHandlers:b,currentPath:[],keyBuilder:c.keyBuilder,permissionsConfig:w,endpointMeta:c.endpointMeta,database:n,approvalConfig:s,tenantId:r}),Object.keys(y).length>0&&(a[c.id].api=y),m.endpoints=y;let T=c.webhooks??{},I=c.webhookHooks;if(Object.keys(T).length>0){let C={};ae({webhooks:T,hooks:I,ctx:m,webhooksTree:C,keyBuilder:c.keyBuilder}),a[c.id].webhooks=C,c.pluginWebhookMatcher&&(a[c.id].pluginWebhookMatcher=c.pluginWebhookMatcher)}}return a}function Fe(e,t,n){let r={};for(let o of e){let i=o.options,s=o.authConfig;if(i?.authType){let a=s?.[i.authType]?.integration??[],d=Q({authType:i.authType,integrationName:o.id,kek:n,database:t,extraIntegrationFields:a});r[o.id]=d}}return r}async function Oe(e,t,n,r,o="pending"){if(!e)return null;try{let i=be(),s=new Date;return await e.db.insertInto("corsair_events").values({id:i,created_at:s,updated_at:s,account_id:t,event_type:n,payload:r,status:o}).execute(),i}catch(i){return console.warn("Failed to log event:",i),null}}async function tn(e,t,n,r="pending"){try{let o=await e.$getAccountId();return Oe(e.database,o,t,n,r)}catch(o){return console.warn("Failed to log event:",o),null}}import*as $e from"https";import*as Ke from"querystring";function Me(e,t,n,r,o){let i=new URL(r.tokenUrl),s=r.tokenAuthMethod==="basic";return new Promise((a,d)=>{let c={code:e.trim(),redirect_uri:o,grant_type:"authorization_code"};s||(c.client_id=t,c.client_secret=n);let l=Ke.stringify(c),p={"Content-Type":"application/x-www-form-urlencoded","Content-Length":Buffer.byteLength(l).toString()};s&&(p.Authorization=`Basic ${Buffer.from(`${t}:${n}`).toString("base64")}`);let h=$e.request({hostname:i.hostname,...i.port?{port:Number(i.port)}:{},path:i.pathname+i.search,method:"POST",headers:p},g=>{let u="";g.on("data",f=>{u+=f}),g.on("end",()=>{if(g.statusCode!==200){d(new Error(`Token exchange failed (${g.statusCode}): ${u}`));return}try{a(JSON.parse(u))}catch{d(new Error(`Token endpoint returned non-JSON response: ${u}`))}})});h.on("error",g=>d(new Error(`Request failed: ${g.message}`))),h.write(l),h.end()})}var Se=["ably","airtable","amplitude","asana","box","cal","calendly","cloudflare","cursor","discord","dodopayments","dropbox","exa","figma","firecrawl","fireflies","github","gitlab","gmail","googlecalendar","googledrive","googlesheets","hackernews","hubspot","intercom","jira","linear","monday","notion","onedrive","openweathermap","oura","outlook","pagerduty","posthog","razorpay","reddit","resend","sentry","sharepoint","slack","spotify","strava","stripe","tavily","teams","telegram","todoist","trello","twitter","twitterapiio","typeform","vapi","youtube","zoom"];var Ne=" ";function D(e){return e._def}function _(e){let t=e.typeName;if(t)return t;let n=e.type;if(n)return`Zod${n.charAt(0).toUpperCase()}${n.slice(1)}`}function L(e){return e.innerType}function on(e){return e.element??e.type}function ee(e,t){let n=t.shape??e.shape;return typeof n=="function"?n():n}function R(e){let t=D(e),n=_(t);switch(n){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodNull":return"null";case"ZodUnknown":case"ZodAny":return"any";case"ZodLiteral":return String(t.value);case"ZodEnum":return t.values.map(r=>String(r)).join(" | ");case"ZodOptional":return R(L(t));case"ZodNullable":return`${R(L(t))} | null`;case"ZodArray":{let r=on(t),o=D(r),i=_(o)==="ZodUnion",s=R(r);return`${i?`(${s})`:s}[]`}case"ZodRecord":return"{}";case"ZodObject":{let r=ee(e,t),o=Object.entries(r);return o.length===0?"{}":`{ ${o.map(([s,a])=>{let d=_(D(a));return`${d==="ZodOptional"||d==="ZodNullable"?s+"?":s}: ${R(a)}`}).join(", ")} }`}case"ZodUnion":return t.options.map(R).join(" | ");case"ZodIntersection":return`${R(t.left)} & ${R(t.right)}`;default:return(n??"unknown").replace("Zod","").toLowerCase()}}function z(e,t){let n=D(e),r=_(n);if(r==="ZodOptional")return z(L(n),t);if(r!=="ZodObject")return R(e);let o=ee(e,n),i=Object.entries(o);if(i.length===0)return"{}";let s=Ne.repeat(t+1),a=Ne.repeat(t),d=[];for(let[c,l]of i){let p=D(l),h=_(p),u=h==="ZodOptional"||h==="ZodNullable"?`${c}?`:c,f=h==="ZodOptional"||h==="ZodNullable"?p.innerType:l,m=D(f),k=_(m),P=m?.description,b=P?` // ${P}`:"";k==="ZodObject"?d.push(`${s}${u}: ${z(f,t+1)}${b}`):d.push(`${s}${u}: ${R(l)}${b}`)}return`{
|
|
14
|
-
${d.join(`
|
|
15
|
-
`)}
|
|
16
|
-
${a}}`}var fe=["equals","contains","startsWith","endsWith","in"],rn=["equals","gt","gte","lt","lte","in"],sn=["equals"],an=["equals","before","after","between"];function Ze(e){let t=D(e);switch(_(t)){case"ZodOptional":case"ZodNullable":case"ZodDefault":return Ze(L(t));case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodDate":return"date";default:return null}}function ye(e){let t=D(e),n=_(t);if(n==="ZodOptional"||n==="ZodNullable"||n==="ZodDefault")return ye(L(t));if(n!=="ZodObject")return{};let r=ee(e,t),o={};for(let[i,s]of Object.entries(r)){let a=Ze(s);a==="string"?o[i]={type:"string",operators:fe}:a==="number"?o[i]={type:"number",operators:rn}:a==="boolean"?o[i]={type:"boolean",operators:sn}:a==="date"&&(o[i]={type:"date",operators:an})}return o}function je(e,t){for(let[n,r]of Object.entries(e))if(n.toLowerCase()===t)return[n,r]}function le(e,t,n){for(let[r,o]of Object.entries(e)){let i=[...t,r];typeof o=="function"?n.push(i.join(".")):o!==null&&typeof o=="object"&&le(o,i,n)}}function pe(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function ge(e,t,n){for(let[r,o]of Object.entries(e)){let i=[...t,r];pe(o)?n.push(i.join(".")):o!==null&&typeof o=="object"&&ge(o,i,n)}}function he(e,t){if(t.length===0)return null;let[n,...r]=t,o=Object.entries(e).find(([a])=>a.toLowerCase()===n);if(!o)return null;let[i,s]=o;if(r.length===0)return pe(s)?[i]:null;if(s!==null&&typeof s=="object"&&!pe(s)){let a=he(s,r);if(a!==null)return[i,...a]}return null}function Le(e,t){let n=[];n.push(`${e}({`),n.push(" webhookHooks: {");for(let i=0;i<t.length;i++){let s=" ".repeat(i+2);n.push(`${s}${t[i]}: {`)}let r=" ".repeat(t.length+2),o=r+" ";n.push(`${r}before(ctx, args) {`),n.push(`${o}return { ctx, args };`),n.push(`${r}},`),n.push(`${r}after(ctx, response) {`),n.push(`${r}},`);for(let i=t.length-1;i>=0;i--){let s=" ".repeat(i+2);n.push(`${s}},`)}return n.push(" },"),n.push("})"),n.join(`
|
|
17
|
-
`)}var cn=new Set(Se);function N(e,t){let n=t?.type??"api",r=t?.plugin;if(r!==void 0){let i=e.find(a=>a.id===r);if(!i)return cn.has(r)?`This plugin (${r}) is not configured. Please add it to the Corsair instance to see its associated methods.`:N(e);if(n==="webhooks"){if(!i.webhooks)return[];let a=[];return ge(i.webhooks,[],a),a.map(d=>`${i.id}.webhooks.${d}`)}if(n==="db"){let a=i.schema?.entities;return a?Object.keys(a).map(d=>`${i.id}.db.${d}.search`):[]}if(!i.endpoints)return[];let s=[];return le(i.endpoints,[],s),s.map(a=>`${i.id}.api.${a}`)}let o={};if(n==="webhooks")for(let i of e){if(!i.webhooks)continue;let s=[];ge(i.webhooks,[],s),o[i.id]=s.map(a=>`${i.id}.webhooks.${a}`)}else if(n==="db")for(let i of e){let s=i.schema?.entities;s&&(o[i.id]=Object.keys(s).map(a=>`${i.id}.db.${a}.search`))}else for(let i of e){if(!i.endpoints)continue;let s=[];le(i.endpoints,[],s),o[i.id]=s.map(a=>`${i.id}.api.${a}`)}return o}function j(e,t){if(e){for(let[n,r]of Object.entries(e))if(n.toLowerCase()===t)return r}}function dn(e,t){let n=e.toLowerCase(),r=t.toLowerCase();if(!n.startsWith(`${r}.`)){let i=n.slice(t.length+1),s=i.startsWith(".")?i.slice(1):i;return s.startsWith("api.")&&(s=s.slice(4)),{shortPath:s,lookupKey:s}}let o=e.slice(t.length+1);return o.toLowerCase().startsWith("api.")&&(o=o.slice(4)),{shortPath:o,lookupKey:o.toLowerCase()}}function de(e,t){return typeof e=="string"?e:Array.isArray(e)?`${t}:
|
|
18
|
-
${e.join(", ")}`:`${t}:
|
|
19
|
-
`+Object.entries(e).map(([n,r])=>` ${n}: ${r.join(", ")}`).join(`
|
|
20
|
-
`)}function qn(e,t){let n=t.toLowerCase(),r=n.indexOf(".");if(r!==-1){let o=n.slice(0,r),i=n.slice(r+1),s=e.find(a=>a.id===o);if(s){if(i.startsWith("db.")){let l=i.slice(3),p=l.lastIndexOf(".");if(p!==-1){let h=l.slice(0,p),g=l.slice(p+1),u=s.schema?.entities;if(g==="search"&&u){let f=je(u,h);if(f){let[m,k]=f,P=ye(k),b=[`Search ${o} ${m} stored in the local database.`,"Pass limit and offset as numbers for pagination.","","filters {",` entity_id: string [${fe.join(", ")}]`];for(let[y,w]of Object.entries(P))b.push(` ${y}?: ${w.type} [${w.operators.join(", ")}]`);return b.push("}"),b.join(`
|
|
21
|
-
`)}}}return de(N(e,{type:"db"}),"Path not found. Available db operations")}if(i.startsWith("webhooks.")){let l=i.slice(9);if(s.webhooks){let p=he(s.webhooks,l.split("."));if(p!==null){let h=p.join("."),g=j(s.webhookSchemas,h.toLowerCase()),u=g?.response?R(g.response):null,f=[];return g?.description&&f.push(g.description),g?.payload&&f.push(`payload ${z(g.payload,0)}`),u&&f.push(`response: ${u}`),f.push(`usage:
|
|
22
|
-
${Le(o,p)}`),f.join(`
|
|
23
|
-
|
|
24
|
-
`)}}return de(N(e,{type:"webhooks"}),"Path not found. Available webhooks")}let a=i;a.startsWith("api.")&&(a=a.slice(4));let d=j(s.endpointMeta,a),c=j(s.endpointSchemas,a);if(d||c){let l=[],p=[d?.riskLevel?`[${d.riskLevel}]`:"",d?.irreversible?"[irreversible]":""].filter(Boolean).join(" "),h=[d?.description,p].filter(Boolean).join(" ");return h&&l.push(h),c?.input&&l.push(`input ${z(c.input,0)}`),c?.output&&l.push(`output ${z(c.output,0)}`),l.join(`
|
|
25
|
-
|
|
26
|
-
`)}}}return de(N(e),"Path not found. Available operations")}function Be(e){let t=e;for(;;){let n=D(t),r=_(n);if(r==="ZodOptional"||r==="ZodNullable"||r==="ZodDefault"){t=L(n);continue}return t}}function ue(e){if(e===void 0)return{kind:"inline",type:"unknown"};let t=Be(e),n=D(t);if(_(n)==="ZodObject"){let o=ee(t,n),i=[];for(let[s,a]of Object.entries(o)){let d=D(a),c=_(d),l=c==="ZodOptional"||c==="ZodNullable",p=Be(a),g=D(p)?.description;i.push({key:s,optional:l,type:R(p),description:g})}return{kind:"object",fields:i}}return{kind:"inline",type:R(t)}}function un(e,t){let n=N(e,{plugin:t,type:"api"});if(typeof n=="string")return{ok:!1,error:n};if(!Array.isArray(n))return{ok:!1,error:"list_operations did not return a path array \u2014 pass a configured plugin id."};let r=e.find(l=>l.id===t);if(!r)return{ok:!1,error:`Plugin "${t}" is not configured on this instance.`};let o=[];for(let l of n){let{shortPath:p,lookupKey:h}=dn(l,t),g=j(r.endpointMeta,h),u=j(r.endpointSchemas,h);!g&&!u||o.push({path:l,shortPath:p,description:g?.description,riskLevel:g?.riskLevel,irreversible:g?.irreversible,input:ue(u?.input),output:ue(u?.output)})}o.sort((l,p)=>l.path.localeCompare(p.path));let i=[],s=N(e,{plugin:t,type:"webhooks"});if(Array.isArray(s)&&r.webhooks)for(let l of s){let h=l.toLowerCase().slice(t.length+1),g=h.startsWith(".")?h.slice(1):h;if(!g.startsWith("webhooks."))continue;let u=g.slice(9),f=he(r.webhooks,u.split("."));if(f===null)continue;let m=f.join("."),k=j(r.webhookSchemas,m.toLowerCase()),P=k?.response?R(k.response):void 0;i.push({path:l,description:k?.description,payload:ue(k?.payload),responseType:P,usageExample:Le(t,f)})}i.sort((l,p)=>l.path.localeCompare(p.path));let a=[],d=N(e,{plugin:t,type:"db"}),c=r.schema?.entities;if(Array.isArray(d)&&c)for(let l of d){let h=l.toLowerCase().slice(t.length+1),g=h.startsWith(".")?h.slice(1):h;if(!g.startsWith("db."))continue;let u=g.slice(3),f=u.lastIndexOf(".");if(f===-1)continue;let m=u.slice(0,f);if(u.slice(f+1)!=="search")continue;let P=je(c,m);if(!P)continue;let[b,y]=P,w=ye(y),T=Object.entries(w).map(([I,C])=>({field:I,type:C.type,operators:C.operators}));a.push({path:l,entityName:b,filters:[{field:"entity_id",type:"string",operators:fe},...T]})}return a.sort((l,p)=>l.path.localeCompare(p.path)),{ok:!0,data:{pluginId:t,api:o,webhooks:i,db:a}}}var me=Symbol.for("corsair:internal");function Qn(e){let t=e.database?ke(e.database):void 0,n=t&&e.kek?Fe(e.plugins,t,e.kek):Y(!!t,!!e.kek),r={plugins:e.plugins,database:t,kek:e.kek,multiTenancy:!!e.multiTenancy,approval:e.approval},o=_e(t);if(e.multiTenancy)return Object.assign({withTenant:s=>{if(!s)throw new Error("corsair.withTenant(tenantId): tenantId must be a non-empty string");let a=ce(e.plugins,{database:t,tenantId:s,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval});return Object.assign(a,{[me]:r})},keys:n,permissions:o},{[me]:r});let i=ce(e.plugins,{database:t,tenantId:void 0,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval});return Object.assign({},i,{keys:n,permissions:o,[me]:r})}export{K as a,M as b,O as c,oe as d,re as e,Z as f,S as g,U as h,q as i,Q as j,X as k,Ae as l,Ee as m,Oe as n,tn as o,Me as p,Se as q,N as r,qn as s,un as t,me as u,Qn as v};
|