corsair 0.1.212 → 0.2.0

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.
@@ -0,0 +1 @@
1
+ import{d as ae,e as se,f as ce,g as ue}from"./chunk-XPXWKPFZ.js";var Ze=Symbol.for("corsair:internal"),K=class extends Error{constructor(t="Invalid corsair instance"){super(t),this.name="InvalidCorsairInstanceError"}};function z(e){return typeof e=="object"&&e!==null}function de(e){if(!z(e)||!Array.isArray(e.plugins)||typeof e.kek!="string"||typeof e.multiTenancy!="boolean")return!1;if(e.database===void 0)return!0;if(!z(e.database))return!1;let t=e.database.db;return typeof t=="object"&&t!==null&&typeof t.selectFrom=="function"}function le(e){if(!e||typeof e!="object")return;let n=Object.getOwnPropertyDescriptor(e,Ze)?.value;return de(n)?n:void 0}function Je(e,t){let n=le(e);if(!n)throw t?.()??new K;return n}function ye(e,t){return e.plugins.find(n=>n.id===t)}function Qe(e,t,n){let r=ye(e,t);if(!r)throw n(`Plugin '${t}' not found`);return r}function ze(e){return"withTenant"in e&&typeof e.withTenant=="function"}function He(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="function"?(...r)=>Reflect.apply(n,e,r):void 0}var H={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"]},managed:{integration:[],account:["access_token","refresh_token","expires_at","scope","webhook_signature"]},managed_pricing:{integration:[],account:[]}};function fe(e){return e==="oauth_2"||e==="api_key"||e==="bot_token"||e==="managed"||e==="managed_pricing"}function Ge(e){let t=e.options?.authType;return fe(t)?t:void 0}function Ot(e){return e==="managed_pricing"}function qe(e,t){let n=e.authConfig,r=H[t].account,i=n?.[t]?.account??[];return[...r,...i]}function vt(e,t){let n=e.authConfig,r=H[t].integration,i=n?.[t]?.integration??[];return[...r,...i]}import{createCipheriv as ge,createDecipheriv as pe,randomBytes as O,scrypt as Ye}from"crypto";import{promisify as Xe}from"util";var me=Xe(Ye),v="aes-256-gcm",we=12,$=16,Ve=16,G=32;function q(){return O(G).toString("base64")}async function Y(e,t){let n=O(Ve),r=await me(t,n,G),i=O(we),o=ge(v,r,i,{authTagLength:$}),a=Buffer.concat([o.update(e,"utf8"),o.final()]),d=o.getAuthTag();return[n.toString("base64"),i.toString("base64"),d.toString("base64"),a.toString("base64")].join(":")}async function F(e,t){let[n,r,i,o]=e.split(":");if(!n||!r||!i||!o)throw new Error("Invalid encrypted DEK format");let a=Buffer.from(n,"base64"),d=Buffer.from(r,"base64"),p=Buffer.from(i,"base64"),w=Buffer.from(o,"base64"),l=await me(t,a,G),s=pe(v,l,d,{authTagLength:$});return s.setAuthTag(p),Buffer.concat([s.update(w),s.final()]).toString("utf8")}function X(e,t){let n=Buffer.from(t,"base64"),r=O(we),i=ge(v,n,r,{authTagLength:$}),o=Buffer.concat([i.update(e,"utf8"),i.final()]),a=i.getAuthTag();return[r.toString("base64"),a.toString("base64"),o.toString("base64")].join(":")}function V(e,t){let[n,r,i]=e.split(":");if(!n||!r||!i)throw new Error("Invalid encrypted data format");let o=Buffer.from(t,"base64"),a=Buffer.from(n,"base64"),d=Buffer.from(r,"base64"),p=Buffer.from(i,"base64"),w=pe(v,o,a,{authTagLength:$});return w.setAuthTag(d),Buffer.concat([w.update(p),w.final()]).toString("utf8")}function ee(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=X(i,t);return n}function j(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=V(i,t);return n}function Lt(e,t,n){let r=j(e,t);return ee(r,n)}import{v7 as et}from"uuid";function P(){return et()}function M(e,t){return e.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t.tenantId).where("integration_id","=",t.integrationId).orderBy("created_at","asc").orderBy("id","asc")}async function B(e,t){return M(e,t).executeTakeFirst()}async function tt(e){let t=!1;for(;;){let n=await e.database.db.selectFrom("corsair_integrations").selectAll().where("name","=",e.integrationName).executeTakeFirst();if(!n){if(!t&&e.ensureProvisioned){t=!0,await e.ensureProvisioned();continue}throw new Error(`Integration "${e.integrationName}" not found. Make sure to create the integration first.`)}let r={tenantId:e.tenantId,integrationId:n.id},i=e.account?await ot({db:e.database.db,kek:e.account.kek,...r,ref:e.account.ref}):await B(e.database.db,r);if(!i){if(!t&&e.ensureProvisioned){t=!0,await e.ensureProvisioned();continue}throw new Error(`Account not found for tenant "${e.tenantId}" and integration "${e.integrationName}". Make sure to create the account first.`)}return{integrationId:n.id,accountId:i.id,integration:{id:n.id,config:n.config,dek:n.dek??null},account:{id:i.id,config:i.config,dek:i.dek??null}}}}async function rn(e){let{integrationId:t,accountId:n}=await tt(e);return{integrationId:t,accountId:n}}var S=class extends Error{code;accounts;constructor(t,n,r=[]){super(n),this.name="AccountSelectionError",this.code=t,this.accounts=r}};function Ce(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e??{}}var te=e=>({id:e.id,config:e.config,dek:e.dek??null});async function L(e,t){let n=Ce(e.config);if(!e.dek||!n?.account_ref)return{};try{let r=j(n,await F(e.dek,t));return{ref:r.account_ref,label:r.account_label}}catch{return{}}}async function on(e,t,n){if(e.id===t)return!0;let{ref:r,label:i}=await L(e,n);return r===t||i?.toLowerCase()===t.toLowerCase()}async function an(e,t,n){let r=n?await e.selectFrom("corsair_accounts").select(["config","dek"]).where("id","=",t).executeTakeFirst():void 0;return{id:t,...r&&n?await L(r,n):{}}}function nt(e){let t=new Set(e),n=1;for(;t.has(`Account ${n}`);)n++;return`Account ${n}`}var ke=(e,t)=>Promise.all(e.map(async n=>({...te(n),...await L(n,t)})));async function Te(e){return ke(await M(e.db,e).execute(),e.kek)}var rt=e=>e.label??e.ref??e.id,W=({id:e,ref:t,label:n})=>({id:e,ref:t,label:n});async function sn(e){let t=await e.db.selectFrom("corsair_integrations").select("id").where("name","=",e.integrationName).executeTakeFirst();if(!t)return[];let n=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",e.tenantId).where("integration_id","=",t.id).execute();return n.length<2?n:(await Te({db:e.db,kek:e.kek,integrationId:t.id,tenantId:e.tenantId})).map(i=>({id:i.id,label:i.label??i.ref}))}async function cn(e){let t=await e.db.selectFrom("corsair_integrations").select("id").where("name","=",e.integrationName).executeTakeFirst();return t?(await Te({db:e.db,kek:e.kek,integrationId:t.id,tenantId:e.tenantId})).map(W):[]}async function it(e,t){return(await e.selectFrom("corsair_integrations").select("name").where("id","=",t).executeTakeFirst())?.name??t}async function ot(e){let t=await M(e.db,e).execute();if(t.length===0)return;if(!e.ref&&t.length===1)return te(t[0]);let n=e.ref?t.find(l=>l.id===e.ref):void 0;if(n)return te(n);let r=await ke(t,e.kek),i=e.ref?.toLowerCase(),o=e.ref?r.find(l=>l.ref===e.ref):void 0;if(o)return o;let a=e.ref?r.filter(l=>l.label?.toLowerCase()===i):[];if(a.length===1)return a[0];let d=await it(e.db,e.integrationId);if(a.length>1)throw new S("account_required",`Label "${e.ref}" matches ${a.length} accounts for "${d}" (tenant "${e.tenantId}"): ${a.map(l=>l.ref??l.id).join(", ")}. Name one by its id.`,a.map(W));let p=r.map(rt).join(", "),w=r.map(W);throw e.ref?new S("account_not_found",`No account "${e.ref}" for "${d}" (tenant "${e.tenantId}"). Accounts: ${p}.`,w):new S("account_required",`Plugin "${d}" has ${r.length} accounts for tenant "${e.tenantId}": ${p}. Name one with withTenant(tenantId, { accounts: { ${d}: "<account>" } }).`,w)}var at=5;async function un(e){let{database:t,kek:n,tenantId:r}=e;return t.db.transaction().execute(async i=>{let o=i.selectFrom("corsair_integrations").select(["id"]).where("name","=",e.integrationName);t.isPg===!0&&(o=o.forUpdate());let a=await o.executeTakeFirst();if(!a)throw new Error(`Integration '${e.integrationName}' not found. Run setupCorsair first.`);let d=await M(i,{tenantId:r,integrationId:a.id}).execute();if(!e.identity)return d[0]?{accountId:d[0].id,created:!1}:he(i,a.id,r,n);let p=await Promise.all(d.map(async u=>({row:u,...await L(u,n)}))),w=e.identity.label===void 0&&e.nameNew?{...e.identity,label:nt(p.map(u=>u.label))}:e.identity;if(e.rowId){let u=p.find(m=>m.row.id===e.rowId);if(!u)throw new S("account_not_found",`Account "${e.rowId}" is no longer connected for "${e.integrationName}" (tenant "${r}").`);return u.ref?{accountId:u.row.id,created:!1}:(await be(i,u.row,w,n),{accountId:u.row.id,created:!1})}let l=p.find(u=>u.ref===w.id),s=l??p.find(u=>!u.ref)??(e.allowMany?void 0:p[0]);if(s){if(!l||w.label&&s.label!==w.label){let u=!l&&s.ref!==void 0;await be(i,s.row,w,n,u)}return{accountId:s.row.id,created:!1}}if(d.length>=at)throw new S("account_limit",`Account limit reached: tenant "${r}" already has ${d.length} accounts for "${e.integrationName}".`,p.map(({row:u,ref:m,label:I})=>W({id:u.id,ref:m,label:I})));return he(i,a.id,r,n,w)})}async function Ae(e,t,n){let{account_label:r,...i}=t;return ee({...i,account_ref:n.id,...n.label?{account_label:n.label}:{}},e)}async function be(e,t,n,r,i=!1){let o=t.dek?await F(t.dek,r):q(),a=Ce(t.config),d=i?{}:t.dek?j(a,o):a;await e.updateTable("corsair_accounts").set({config:await Ae(o,d,n),dek:t.dek??await Y(o,r),updated_at:new Date}).where("id","=",t.id).execute()}async function he(e,t,n,r,i){let o=q(),a=new Date,d=P();return await e.insertInto("corsair_accounts").values({id:d,created_at:a,updated_at:a,tenant_id:n,integration_id:t,config:i?await Ae(o,{},i):{},dek:await Y(o,r)}).execute(),{accountId:d,created:!0}}import{SqliteAdapter as st,sql as Ke}from"kysely";import{z as T}from"zod";var ne="_corsair_enc";function Ie(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t[ne]=="string"&&Object.keys(t).length===1}function re(e,t){return{[ne]:X(JSON.stringify(e),t)}}function ie(e,t){let n=Ee(e);return Ie(n)?JSON.parse(V(n[ne],t)):n}async function fn(e,t,n){let r=await e.selectFrom("corsair_accounts").select("dek").where("id","=",t).executeTakeFirst();if(!r?.dek)throw new Error(`No DEK found for account "${t}". Initialize the account first.`);return F(r.dek,n)}async function gn(e,t,n,r){let i=await e.selectFrom("corsair_entities").select(["id","data"]).where("account_id","=",t).execute();for(let a of i){let d=xe(a.data,n,r);d&&await e.updateTable("corsair_entities").set({data:d,updated_at:new Date}).where("id","=",a.id).execute()}let o=await e.selectFrom("corsair_events").select(["id","payload"]).where("account_id","=",t).execute();for(let a of o){let d=xe(a.payload,n,r);d&&await e.updateTable("corsair_events").set({payload:d,updated_at:new Date}).where("id","=",a.id).execute()}}function xe(e,t,n){let r=Ee(e);if(Ie(r))return re(ie(r,t),n)}function Ee(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}import{sql as D}from"kysely";function U(e){return e.replace(/'/g,"''")}function _e(e){let t=U(e);return D`data->>'${D.raw(t)}'`}function De(e){let t=U(e);return D`(data->>'${D.raw(t)}')::numeric`}function Fe(e){let t=U(e);return D`(data->>'${D.raw(t)}')::boolean`}function Pe(e){let t=U(e);return D`(data->>'${D.raw(t)}')::timestamptz`}import{sql as Z}from"kysely";function Se(e){return e.replace(/'/g,"''").replace(/\\/g,"\\\\")}function Re(e){let t=Se(e);return Z`CAST(json_extract(data, '$.${Z.raw(t)}') AS REAL)`}function Be(e){let t=Se(e);return Z`json_extract(data, '$.${Z.raw(t)}')`}var ct={number:e=>De(e),booleanEquals:(e,t)=>Ke`${Fe(e)} = ${t}`,timestamp:e=>Pe(e)},ut={number:e=>Re(e),booleanEquals:(e,t)=>Ke`json_extract(data, ${`$.${e}`}) = ${t?1:0}`,timestamp:e=>Be(e)};function dt(e){return e.getExecutor().adapter instanceof st?ut:ct}function lt(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function Oe(e){let t=e;for(;t;){if(t instanceof T.ZodOptional||t instanceof T.ZodNullable){t=t._def.innerType;continue}if(t instanceof T.ZodDefault){t=t._def.innerType;continue}break}return t}function Ne(e){if(typeof e=="string")return"string";if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean"}function oe(e){let[t]=e;return t&&e.every(n=>n===t)?t:void 0}function ve(e){let t=Oe(e);if(t instanceof T.ZodString)return"string";if(t instanceof T.ZodNumber)return"number";if(t instanceof T.ZodBoolean)return"boolean";if(t instanceof T.ZodDate)return"date";if(t instanceof T.ZodEnum)return oe(t.options.map(Ne));if(t instanceof T.ZodLiteral)return oe([...t.values].map(Ne));if(t instanceof T.ZodUnion)return oe(t.options.filter(n=>!(n instanceof T.ZodNull)).map(n=>ve(n)))}function yt(e){let t=Oe(e);if(!(t instanceof T.ZodObject))return{};let n=t.shape,r={};for(let[i,o]of Object.entries(n)){let a=ve(o);a&&(r[i]=a)}return r}function ft(e,t,n){if(typeof n=="string")return e.where(t,"=",n);if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;"equals"in r&&typeof r.equals=="string"&&(e=e.where(t,"=",r.equals)),"contains"in r&&typeof r.contains=="string"&&(e=e.where(t,"like",`%${r.contains}%`)),"startsWith"in r&&typeof r.startsWith=="string"&&(e=e.where(t,"like",`${r.startsWith}%`)),"endsWith"in r&&typeof r.endsWith=="string"&&(e=e.where(t,"like",`%${r.endsWith}`)),"in"in r&&Array.isArray(r.in)&&(e=e.where(t,"in",r.in))}return e}function gt(e,t,n){if(typeof n=="number")return e.where(t,"=",n);if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;typeof r.equals=="number"&&(e=e.where(t,"=",r.equals)),typeof r.gt=="number"&&(e=e.where(t,">",r.gt)),typeof r.gte=="number"&&(e=e.where(t,">=",r.gte)),typeof r.lt=="number"&&(e=e.where(t,"<",r.lt)),typeof r.lte=="number"&&(e=e.where(t,"<=",r.lte)),Array.isArray(r.in)&&(e=e.where(t,"in",r.in))}return e}function pt(e,t,n){if(typeof n=="boolean")return e.where(t(n));if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;typeof r.equals=="boolean"&&(e=e.where(t(r.equals)))}return e}function mt(e,t,n){if(n instanceof Date)return e.where(t,"=",n);if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;if(r.equals instanceof Date&&(e=e.where(t,"=",r.equals)),r.before instanceof Date&&(e=e.where(t,"<",r.before)),r.after instanceof Date&&(e=e.where(t,">",r.after)),Array.isArray(r.between)&&r.between.length===2){let[i,o]=r.between;i instanceof Date&&(e=e.where(t,">=",i)),o instanceof Date&&(e=e.where(t,"<=",o))}}return e}function wt(e,t,n,r,i){return r==="number"?gt(e,t.number(n),i):r==="boolean"?pt(e,o=>t.booleanEquals(n,o),i):r==="date"?mt(e,t.timestamp(n),i):ft(e,_e(n),i)}function bt(e,t,n){if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;return"equals"in r&&(e=e.where(t,"=",r.equals)),"contains"in r&&typeof r.contains=="string"&&(e=e.where(t,"like",`%${r.contains}%`)),"startsWith"in r&&typeof r.startsWith=="string"&&(e=e.where(t,"like",`${r.startsWith}%`)),"endsWith"in r&&typeof r.endsWith=="string"&&(e=e.where(t,"like",`%${r.endsWith}`)),"in"in r&&Array.isArray(r.in)&&(e=e.where(t,"in",r.in)),e}return e.where(t,"=",n)}function ht(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function $e(e,t){return Array.isArray(t)?e("account_id","in",t):e("account_id","=",t)}function R(e,t,n){let r=e.selectFrom("corsair_entities").selectAll().where(i=>$e(i,t)).where("entity_type","=",n);return Array.isArray(t)?r.orderBy("created_at").orderBy("id"):r}function je(e,t,n,r,i,o,a){let d=yt(i),p=new Map,w=async c=>{if(!o?.kek)throw new Error("encryptDataAtRest requires kek");let y=await e.selectFrom("corsair_accounts").select("dek").where("id","=",c).executeTakeFirst();if(!y?.dek)throw new Error(`No DEK found for account "${c}". Initialize the account first.`);let f=p.get(c);if(f&&f.wrapped===y.dek)return f.dek;let g=await F(y.dek,o.kek);return p.set(c,{wrapped:y.dek,dek:g}),g};async function l(c,y){let f=lt(c.data);return o&&(f=ie(f,y??await w(c.account_id))),{...c,data:i.parse(f)}}async function s(){let c=a?await a():[];return c.length<2?{ids:await t()}:{ids:c.map(y=>y.id),labels:new Map(c.map(y=>[y.id,y.label??y.id]))}}async function u(c){let{ids:y,labels:f}=await s(),h=await R(e,y,n).where("entity_id","=",c).execute();return Array.isArray(y)?(h.sort((x,A)=>y.indexOf(x.account_id)-y.indexOf(A.account_id)),{row:h[0],labels:f}):{row:h[0],labels:f}}async function m(c,y){let f=new Map;return o&&await Promise.all([...new Set(c.map(g=>g.account_id))].map(async g=>f.set(g,await w(g)))),Promise.all(c.map(async g=>{let h=await l(g,f.get(g.account_id)),x=y?.get(g.account_id);return x?{...h,account:x}:h}))}async function I(c,y){return o?re(y,await w(c)):y}return{findByEntityId:async c=>{let{row:y,labels:f}=await u(c);return y?(await m([y],f))[0]:null},existsByEntityId:async c=>{let{ids:y}=await s();return await R(e,y,n).select("id").where("entity_id","=",c).executeTakeFirst()!==void 0},findIdByEntityId:async c=>{let{row:y}=await u(c);return y?.id??null},findById:async c=>{let{ids:y,labels:f}=await s(),g=await R(e,y,n).where("id","=",c).executeTakeFirst();return g?(await m([g],f))[0]:null},findManyByEntityIds:async c=>{if(c.length===0)return[];let{ids:y,labels:f}=await s(),g=await R(e,y,n).where("entity_id","in",c).execute();return m(g,f)},list:async c=>{let{ids:y,labels:f}=await s(),g=R(e,y,n);typeof c?.limit=="number"&&(g=g.limit(c.limit)),typeof c?.offset=="number"&&(g=g.offset(c.offset));let h=await g.execute();return m(h,f)},search:async c=>{if(o&&c.data&&typeof c.data=="object"&&Object.keys(c.data).length>0)throw new Error("Entity JSON field search cannot run while encryptDataAtRest is enabled. The stored document is ciphertext.");let{ids:y,labels:f}=await s(),g=R(e,y,n),h=new Set(["data","limit","offset"]);for(let[A,_]of Object.entries(c))h.has(A)||_===void 0||(g=bt(g,A,_));if(c.data&&typeof c.data=="object")for(let[A,_]of Object.entries(c.data)){if(_===void 0)continue;let Q=d[A]??"string";g=wt(g,dt(e),A,Q,_)}typeof c.limit=="number"&&(g=g.limit(c.limit)),typeof c.offset=="number"&&(g=g.offset(c.offset));let x=await g.execute();return m(x,f)},upsertByEntityId:async(c,y)=>{let f=await t(),g=i.parse(y),h=await I(f,g),x=new Date,A=await R(e,f,n).select("id").where("entity_id","=",c).executeTakeFirst();if(A?.id){await e.updateTable("corsair_entities").set({version:r,data:h,updated_at:x}).where("id","=",A.id).execute();let Ue=await e.selectFrom("corsair_entities").selectAll().where("id","=",A.id).executeTakeFirst();return l(Ue)}let _=P();await e.insertInto("corsair_entities").values({id:_,created_at:x,updated_at:x,account_id:f,entity_id:c,entity_type:n,version:r,data:h}).execute();let Q=await e.selectFrom("corsair_entities").selectAll().where("id","=",_).executeTakeFirst();return l(Q)},deleteById:async c=>{let y=await t(),f=await e.deleteFrom("corsair_entities").where("account_id","=",y).where("entity_type","=",n).where("id","=",c).executeTakeFirst();return Number(f.numDeletedRows)>0},deleteByEntityId:async c=>{let y=await t(),f=await e.deleteFrom("corsair_entities").where("account_id","=",y).where("entity_type","=",n).where("entity_id","=",c).executeTakeFirst();return Number(f.numDeletedRows)>0},count:async()=>{let{ids:c}=await s(),y=await e.selectFrom("corsair_entities").select(f=>f.fn.countAll().as("count")).where(f=>$e(f,c)).where("entity_type","=",n).executeTakeFirst();return ht(y?.count)}}}var Ct={corsair_integrations:ae,corsair_accounts:se,corsair_entities:ce,corsair_events:ue};function kt(e){return Ct[e]}function We(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function b(e){if(!e)throw new Error("Corsair database is not configured. Pass `database` to createCorsair(...) to enable ORM.")}function N(e){if(!e)return[];let t=[];for(let n in e){let r=n,i=e[r];if(i!==void 0)if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&!(i instanceof Date)){let o=i;"in"in o&&Array.isArray(o.in)?t.push({field:r,operator:"in",value:o.in}):"like"in o&&typeof o.like=="string"&&t.push({field:r,operator:"like",value:o.like})}else t.push({field:r,value:i})}return t}function E(e,t){if(!t?.length)return e;let n=e;for(let r of t){let i=r.operator??"=";n=n.where(r.field,i,r.value)}return n}function Tt(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function J(e,t){let n=kt(t),r=()=>(b(e),e),i=()=>r().db.selectFrom(t),o=()=>r().db.insertInto(t),a=()=>r().db.updateTable(t),d=()=>r().db.deleteFrom(t);function p(l){let s={};for(let[u,m]of Object.entries(l))s[u]=We(m);return n.parse(s)}function w(l){let s={};for(let[u,m]of Object.entries(l))s[u]=We(m);return n.parse(s)}return{findById:async l=>{b(e);let s=i().selectAll();s=E(s,[{field:"id",value:l}]);let u=await s.executeTakeFirst();return u?p(u):null},findOne:async l=>{b(e);let s=i().selectAll();s=E(s,N(l));let u=await s.executeTakeFirst();return u?p(u):null},findMany:async l=>{b(e);let s=i().selectAll();return s=E(s,N(l?.where)),typeof l?.limit=="number"&&(s=s.limit(l.limit)),typeof l?.offset=="number"&&(s=s.offset(l.offset)),(await s.execute()).map(m=>p(m))},create:async l=>{b(e);let s=new Date,u={id:l.id??P(),created_at:s,updated_at:s,...l},m=await o().values(u).returningAll().executeTakeFirst();return m?p(m):w(u)},update:async(l,s)=>{b(e);let u={...s,updated_at:new Date},m=a().set(u).returningAll();m=E(m,[{field:"id",value:l}]);let I=await m.executeTakeFirst();return I?p(I):null},updateMany:async(l,s)=>{b(e);let u={...s,updated_at:new Date},m=i().select("id");m=E(m,N(l));let I=await m.execute();for(let c of I){let y=a().set(u);y=E(y,[{field:"id",value:c.id}]),await y.execute()}return I.length},delete:async l=>{b(e);let s=d();s=E(s,[{field:"id",value:l}]);let u=await s.executeTakeFirst();return Number(u?.numDeletedRows??0)>0},deleteMany:async l=>{b(e);let s=d();s=E(s,N(l));let u=await s.executeTakeFirst();return Number(u?.numDeletedRows??0)},count:async l=>{b(e);let s=i().select(m=>m.fn.countAll().as("count"));s=E(s,N(l));let u=await s.executeTakeFirst();return Tt(u?.count)}}}function At(e){let t=J(e,"corsair_integrations");return{...t,findByName:n=>t.findOne({name:n}),upsertByName:async(n,r)=>{let i=await t.findOne({name:n});return i?await t.update(i.id,r):t.create({...r,name:n})}}}function xt(e){let t=J(e,"corsair_accounts");return{...t,findByTenantAndIntegration:async(n,r)=>{b(e);let i=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",r).executeTakeFirst();if(!i)return null;let o=await B(e.db,{tenantId:n,integrationId:i.id});return o?t.findOne({id:o.id,tenant_id:n,integration_id:i.id}):null},listByTenant:(n,r)=>t.findMany({where:{tenant_id:n},limit:r?.limit,offset:r?.offset}),upsertByTenantAndIntegration:async(n,r,i)=>{b(e);let o=await B(e.db,{tenantId:n,integrationId:r});return o?await t.update(o.id,i):t.create({...i,tenant_id:n,integration_id:r})}}}function It(e){let t=J(e,"corsair_entities");return{...t,findByEntityId:({accountId:n,entityType:r,entityId:i})=>t.findOne({account_id:n,entity_type:r,entity_id:i}),findManyByEntityIds:async({accountId:n,entityType:r,entityIds:i})=>i.length===0?[]:(b(e),await e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",n).where("entity_type","=",r).where("entity_id","in",i).execute()),listByScope:({accountId:n,entityType:r,limit:i,offset:o})=>t.findMany({where:{account_id:n,entity_type:r},limit:i,offset:o}),searchByEntityId:async({accountId:n,entityType:r,query:i,limit:o,offset:a})=>{b(e);let d=e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",n).where("entity_type","=",r).where("entity_id","like",`%${i}%`);return typeof o=="number"&&(d=d.limit(o)),typeof a=="number"&&(d=d.offset(a)),await d.execute()},upsertByEntityId:async({accountId:n,entityType:r,entityId:i,version:o,data:a})=>{let d=await t.findOne({account_id:n,entity_type:r,entity_id:i});return d?await t.update(d.id,{version:o,data:a}):t.create({account_id:n,entity_type:r,entity_id:i,version:o,data:a})},deleteByEntityId:async({accountId:n,entityType:r,entityId:i})=>{b(e);let o=await e.db.deleteFrom("corsair_entities").where("account_id","=",n).where("entity_type","=",r).where("entity_id","=",i).executeTakeFirst();return Number(o.numDeletedRows)>0}}}function Et(e){let t=J(e,"corsair_events");return{...t,listByAccount:(n,r)=>t.findMany({where:{account_id:n},limit:r?.limit,offset:r?.offset}),listByStatus:(n,r)=>{let i={status:n};return r?.accountId&&(i.account_id=r.accountId),t.findMany({where:i,limit:r?.limit,offset:r?.offset})},listPending:n=>{let r={status:"pending"};return n?.accountId&&(r.account_id=n.accountId),t.findMany({where:r,limit:n?.limit??100})},updateStatus:(n,r)=>t.update(n,{status:r})}}function Me(e){return{integrations:At(e),accounts:xt(e),entities:It(e),events:Et(e)}}function _t(e){if(e.encryptDataAtRest===!0)return{encryptDataAtRest:!0,kek:e.kek??""}}function Dt(e,t,n,r,i,o){let a=null;async function d(){if(a!==null)return a;b(e);let p=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t.integrationName).executeTakeFirst();if(!p)throw new Error(`Integration "${t.integrationName}" not found. Make sure to create the integration first.`);let w=await B(e.db,{tenantId:t.tenantId,integrationId:p.id});if(!w)throw new Error(`Account not found for tenant "${t.tenantId}" and integration "${t.integrationName}". Make sure to create the account first.`);return a=w.id,a}return b(e),je(e.db,d,n,r,i,o)}function Le(e){let{database:t,integrationName:n,schema:r,tenantId:i}=e,o=_t(e),a=Me(t),d={tenantId:i,integrationName:n},p=null;async function w(){if(p!==null)return p;b(t);let s=await t.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!s)throw new Error(`Integration "${n}" not found. Make sure to create the integration first.`);let u=await B(t.db,{tenantId:i,integrationId:s.id});if(!u)throw new Error(`Account not found for tenant "${i}" and integration "${n}". Make sure to create the account first.`);return p=u.id,p}let l={};for(let[s,u]of Object.entries(r.entities))l[s]=Dt(t,d,s,r.version,u,o);return{...l,$orm:a,$integrationName:n,$tenantId:i,$getAccountId:w}}function On(e,t){let n=Me(e);return{$tenantId:t,$orm:n,listAccounts:r=>n.accounts.listByTenant(t,r),findAccountByIntegration:r=>n.accounts.findByTenantAndIntegration(t,r),listEntities:async r=>{b(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",t).execute();if(i.length===0)return[];let o=i.map(d=>d.id),a=e.db.selectFrom("corsair_entities").selectAll().where("account_id","in",o);return r?.entityType&&(a=a.where("entity_type","=",r.entityType)),typeof r?.limit=="number"&&(a=a.limit(r.limit)),typeof r?.offset=="number"&&(a=a.offset(r.offset)),await a.execute()},listEvents:async r=>{b(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",t).execute();if(i.length===0)return[];let o=i.map(d=>d.id),a=e.db.selectFrom("corsair_events").selectAll().where("account_id","in",o);return r?.status&&(a=a.where("status","=",r.status)),typeof r?.limit=="number"&&(a=a.limit(r.limit)),typeof r?.offset=="number"&&(a=a.offset(r.offset)),await a.execute()},forIntegration:r=>Le({database:e,integrationName:r.integrationName,schema:r.schema,tenantId:t,encryptDataAtRest:r.encryptDataAtRest,kek:r.kek})}}function vn(e,t){return{forTenant:n=>Le({database:e,integrationName:t.integrationName,schema:t.schema,tenantId:n,encryptDataAtRest:t.encryptDataAtRest,kek:t.kek})}}export{K as a,z as b,le as c,Je as d,Qe as e,ze as f,He as g,H as h,Ge as i,Ot as j,qe as k,vt as l,G as m,q as n,Y as o,F as p,X as q,V as r,ee as s,j as t,Lt as u,Ie as v,re as w,ie as x,fn as y,gn as z,P as A,B,rn as C,S as D,L as E,on as F,an as G,sn as H,cn as I,ot as J,at as K,un as L,je as M,Ct as N,Me as O,Le as P,On as Q,vn as R};
@@ -30,6 +30,9 @@ type Tenant = {
30
30
  id: string;
31
31
  accounts: Array<{
32
32
  integrationName: string;
33
+ accountId: string;
34
+ ref?: string;
35
+ label?: string;
33
36
  hasCredentials: boolean;
34
37
  }>;
35
38
  connectedPlugins: string[];
@@ -0,0 +1 @@
1
+ import{$ as b,_ as a,aa as c}from"./chunk-JDPLOTGP.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-KOJBIKQZ.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{c as createHubConnectSession,b as createHubConnectSessionForPlugin,a as postHubConnectSession};
package/dist/core.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- export { C as CORSAIR_INTERNAL, a as CorsairInternalConfig, c as createCorsair, s as shouldStartTunnel, b as superviseTunnel } from './index-CBAM12HG.js';
2
- import { A as AuthTypes, f as AccountKeyManagerFor, I as IntegrationKeyManagerFor, H as HubConfig, E as EndpointRiskLevel, g as CorsairPluginSubscribeResult } from './index-DfwzI6WA.js';
3
- export { h as AccountFieldNames, i as AgentMessageRole, j as AgentReply, k as AllProviders, B as BASE_AUTH_FIELDS, l as BaseAuthFieldConfig, m as BaseKeyManager, n as BaseProviders, o as BeforeHookResult, p as BindEndpoints, q as BindWebhooks, r as Bivariant, s as BoundEndpointFn, t as BoundEndpointTree, u as BoundWebhook, v as BoundWebhookTree, w as ChatHandle, x as ChatMessage, y as ChatSummary, z as CorsairChatsNamespace, D as CorsairClient, F as CorsairContext, G as CorsairEndpoint, J as CorsairErrorHandler, c as CorsairIntegration, K as CorsairKeyBuilder, L as CorsairKeyBuilderBase, M as CorsairOAuthWebhookTenantLinkResolver, N as CorsairPermissionsNamespace, C as CorsairPlugin, P as CorsairPluginContext, Q as CorsairPluginSubscribe, R as CorsairRunsNamespace, e as CorsairSingleTenantClient, d as CorsairTenantWrapper, S as CorsairWebhook, T as CorsairWebhookHandler, U as CorsairWebhookMatcher, V as CorsairWebhookTenantMatcher, X as CorsairWorkflowsNamespace, Y as CreateChatResult, Z as EndpointHooks, _ as EndpointJob, $ as EndpointMetaEntry, a0 as EndpointPathsOf, a1 as EndpointTree, a2 as EnforcePermissionOptions, a3 as EnforcePermissionResult, a4 as ErrorContext, a5 as ErrorHandler, a6 as ErrorHandlerAndMatchFunction, a7 as ErrorMatcher, a8 as IntegrationFieldNames, a9 as KeyBuilderContext, aa as OAuth2IntegrationCredentials, O as OAuthConfig, ab as PermissionMode, ac as PermissionPolicy, ad as PickAuth, ae as PluginAuthConfig, af as PluginEndpointMeta, ag as PluginPermissionsConfig, ah as ProviderDisplayNames, ai as RawWebhookRequest, aj as ReadonlyForbiddenError, ak as RequiredPluginEndpointMeta, al as RequiredPluginEndpointSchemas, am as RequiredPluginWebhookSchemas, an as RetryStrategies, ao as RetryStrategy, ap as TokenResponse, aq as TriggerRunResult, ar as UnionToIntersection, as as WebhookHooks, at as WebhookPathsOf, au as WebhookRequest, av as WebhookResponse, W as WebhookTenantMatch, aw as WebhookTree, ax as WorkflowRun, ay as WorkflowRunStatus, az as WorkflowRunStep, aA as WorkflowStatus, aB as WorkflowSummary, aC as activeMode, aD as assertModeAllows, aE as assertReadonlyAllowed, aF as exchangeCodeForTokens, aG as formatProviderDisplayName, aH as isReadonlyScopeActive, aI as runReadonly, aJ as runWithMode } from './index-DfwzI6WA.js';
4
- export { A as AuthMissingError, a as AuthType, C as CloudAccess, b as CloudApiError, c as CloudCatalogIntegration, d as CloudConnectSession, e as CloudConnection, f as CloudDeleted, g as CloudDelivery, h as CloudEmbeddedList, i as CloudInstance, j as CloudInstanceApply, k as CloudInstancePlane, l as CloudInstanceRemoval, m as CloudIntegration, n as CloudIntegrationOperations, o as CloudKey, p as CloudKeyRotation, q as CloudLink, r as CloudLinkLine, s as CloudList, t as CloudMcpToken, u as CloudOauthApp, v as CloudOperation, w as CloudProject, x as CloudProjectPlane, y as CloudSigningSecret, z as CloudSigningSecretRotation, B as CloudTenant, D as CloudWebhook, E as CorsairCloudConfig, F as CorsairCloudInstance, G as CorsairCloudInstanceHandle, H as CorsairCloudManage, I as CorsairCloudRegistry, J as CorsairKekMissingError, K as CreateConnectSessionInput, L as CreateInstanceInput, M as CreateTenantInput, N as CreateWebhookInput, O as CredentialSource, P as DocSchemaFieldRow, Q as DocSchemaShape, R as DocsApiEndpoint, S as DocsDbEntity, T as DocsDbFilterField, U as DocsWebhook, V as EndpointSchemaResult, W as IntrospectPluginForDocsResult, X as LinkLine, Y as LinkPolicy, Z as ListOperationsOptions, _ as ListQuery, $ as ManagementApiError, a0 as MintLinkInput, a1 as MintTokenInput, a2 as Permission, a3 as PermissionDecision, a4 as PermissionRequiredError, a5 as PluginDocsIntrospection, a6 as PluginWebhookMatchers, a7 as ProjectStatus, a8 as PutIntegrationInput, a9 as PutOauthAppInput, aa as ReconnectRequiredError, ab as RequestOptions, ac as ResolveConnectLinkResult, ad as RotateWebhookSecretInput, ae as SetAccessInput, af as UpdateInstanceInput, ag as UpdateLinkInput, ah as UpdateTenantInput, ai as V1Transport, aj as WebhookPluginTenantMatch, ak as asRecord, al as buildInstancePlane, am as buildProjectPlane, an as collectPluginWebhookMatchers, ao as corsairCloud, ap as decodePubSubData, aq as extractMicrosoftGraphValidationToken, ar as firstString, as as formatDocSchemaShape, at as getHeader, au as introspectPluginForDocs, av as isMicrosoftGraphValidationHandshake, aw as mapV1Error, ax as matchWebhookPlugin, ay as matchWebhookPluginAndTenant, az as readBodyRecord, aA as readQueryParam, aB as resolveConnectLink, aC as toExternalId } from './tenant-match-utils-CyrwBjB5.js';
1
+ export { C as CORSAIR_INTERNAL, a as CorsairInternalConfig, c as createCorsair, s as shouldStartTunnel, b as superviseTunnel } from './index-B5PVm2FS.js';
2
+ import { A as AuthTypes, f as AccountKeyManagerFor, I as IntegrationKeyManagerFor, H as HubConfig, E as EndpointRiskLevel, g as CorsairPluginSubscribeResult } from './index-CVBmlS4w.js';
3
+ export { h as Account, i as AccountFieldNames, j as AccountModes, k as AccountSelectionError, l as AgentMessageRole, m as AgentReply, n as AllProviders, B as BASE_AUTH_FIELDS, o as BaseAuthFieldConfig, p as BaseKeyManager, q as BaseProviders, r as BeforeHookResult, s as BindEndpoints, t as BindWebhooks, u as Bivariant, v as BoundEndpointFn, w as BoundEndpointTree, x as BoundWebhook, y as BoundWebhookTree, z as ChatHandle, D as ChatMessage, F as ChatSummary, G as CorsairChatsNamespace, J as CorsairClient, K as CorsairContext, L as CorsairEndpoint, M as CorsairErrorHandler, c as CorsairIntegration, N as CorsairKeyBuilder, P as CorsairKeyBuilderBase, Q as CorsairOAuthWebhookTenantLinkResolver, R as CorsairPermissionsNamespace, C as CorsairPlugin, S as CorsairPluginContext, T as CorsairPluginSubscribe, U as CorsairRunsNamespace, e as CorsairSingleTenantClient, d as CorsairTenantWrapper, V as CorsairWebhook, X as CorsairWebhookHandler, Y as CorsairWebhookMatcher, Z as CorsairWebhookTenantMatcher, _ as CorsairWorkflowsNamespace, $ as CreateChatResult, a0 as EndpointHooks, a1 as EndpointJob, a2 as EndpointMetaEntry, a3 as EndpointPathsOf, a4 as EndpointTree, a5 as EnforcePermissionOptions, a6 as EnforcePermissionResult, a7 as ErrorContext, a8 as ErrorHandler, a9 as ErrorHandlerAndMatchFunction, aa as ErrorMatcher, ab as IntegrationFieldNames, ac as KeyBuilderContext, ad as ModeScope, ae as OAuth2IntegrationCredentials, O as OAuthConfig, af as PermissionMode, ag as PermissionPolicy, ah as PickAuth, ai as PluginAuthConfig, aj as PluginEndpointMeta, ak as PluginPermissionsConfig, al as ProviderDisplayNames, am as RawWebhookRequest, an as ReadonlyForbiddenError, ao as RequiredPluginEndpointMeta, ap as RequiredPluginEndpointSchemas, aq as RequiredPluginWebhookSchemas, ar as RetryStrategies, as as RetryStrategy, at as TokenResponse, au as TriggerRunResult, av as UnionToIntersection, aw as WebhookHooks, ax as WebhookPathsOf, ay as WebhookRequest, az as WebhookResponse, W as WebhookTenantMatch, aA as WebhookTree, aB as WorkflowRun, aC as WorkflowRunStatus, aD as WorkflowRunStep, aE as WorkflowStatus, aF as WorkflowSummary, aG as activeMode, aH as assertModeAllows, aI as assertReadonlyAllowed, aJ as exchangeCodeForTokens, aK as formatProviderDisplayName, aL as isReadonlyScopeActive, aM as runReadonly, aN as runWithMode } from './index-CVBmlS4w.js';
4
+ export { A as AuthMissingError, a as AuthType, C as CloudAccess, b as CloudApiError, c as CloudCatalogIntegration, d as CloudConnectSession, e as CloudConnection, f as CloudDeleted, g as CloudDelivery, h as CloudEmbeddedList, i as CloudInstance, j as CloudInstanceApply, k as CloudInstancePlane, l as CloudInstanceRemoval, m as CloudIntegration, n as CloudIntegrationOperations, o as CloudKey, p as CloudKeyRotation, q as CloudLink, r as CloudLinkLine, s as CloudList, t as CloudMcpToken, u as CloudOauthApp, v as CloudOperation, w as CloudProject, x as CloudProjectPlane, y as CloudSigningSecret, z as CloudSigningSecretRotation, B as CloudTenant, D as CloudWebhook, E as CorsairCloudConfig, F as CorsairCloudInstance, G as CorsairCloudInstanceHandle, H as CorsairCloudManage, I as CorsairCloudRegistry, J as CorsairKekMissingError, K as CreateConnectSessionInput, L as CreateInstanceInput, M as CreateTenantInput, N as CreateWebhookInput, O as CredentialSource, P as DocSchemaFieldRow, Q as DocSchemaShape, R as DocsApiEndpoint, S as DocsDbEntity, T as DocsDbFilterField, U as DocsWebhook, V as EndpointSchemaResult, W as IntrospectPluginForDocsResult, X as LinkLine, Y as LinkPolicy, Z as ListOperationsOptions, _ as ListQuery, $ as ManagementApiError, a0 as MintLinkInput, a1 as MintTokenInput, a2 as Permission, a3 as PermissionDecision, a4 as PermissionRequiredError, a5 as PluginDocsIntrospection, a6 as PluginWebhookMatchers, a7 as ProjectStatus, a8 as PutIntegrationInput, a9 as PutOauthAppInput, aa as ReconnectRequiredError, ab as RequestOptions, ac as ResolveConnectLinkResult, ad as RotateWebhookSecretInput, ae as SetAccessInput, af as UpdateInstanceInput, ag as UpdateLinkInput, ah as UpdateTenantInput, ai as V1Transport, aj as WebhookPluginTenantMatch, ak as asRecord, al as buildInstancePlane, am as buildProjectPlane, an as collectPluginWebhookMatchers, ao as corsairCloud, ap as decodePubSubData, aq as extractMicrosoftGraphValidationToken, ar as firstString, as as formatDocSchemaShape, at as getHeader, au as introspectPluginForDocs, av as isMicrosoftGraphValidationHandshake, aw as mapV1Error, ax as matchWebhookPlugin, ay as matchWebhookPluginAndTenant, az as readBodyRecord, aA as readQueryParam, aB as resolveConnectLink, aC as toExternalId } from './tenant-match-utils-BiOexLyr.js';
5
5
  import { CorsairDatabase } from './db.js';
6
6
  import 'zod';
7
7
  import './orm.js';
@@ -135,6 +135,10 @@ type AccountKeyManagerOptions<T extends AuthTypes> = {
135
135
  /** Extra account-level fields from plugin authConfig */
136
136
  extraAccountFields?: readonly string[];
137
137
  ensureProvisioned?: () => Promise<void>;
138
+ /** Scope to one named account. Absent = the default (oldest) account. */
139
+ account?: {
140
+ ref?: string;
141
+ };
138
142
  };
139
143
  /**
140
144
  * Creates an account-level key manager for the given auth type.
@@ -216,7 +220,7 @@ declare function callPluginDb(client: unknown, route: {
216
220
  plugin: string;
217
221
  entityType: string;
218
222
  method: string;
219
- }, args: unknown[]): Promise<unknown>;
223
+ }, args: unknown[], bound?: boolean): Promise<unknown>;
220
224
 
221
225
  /** Minimal shape we need from the account key manager (ctx.keys). */
222
226
  type SubscribeCtx$1 = {
package/dist/core.js CHANGED
@@ -1 +1 @@
1
- import{$b as O,Ab as D,Bb as E,Cb as F,D as m,Db as G,E as n,Eb as H,F as o,G as p,Sb as I,Tb as J,Ub as K,Vb as L,Wb as M,_b as N,a,ac as P,b,ba as q,bb as A,bc as Q,c,ca as r,cc as R,dc as S,ec as T,fa as s,fc as U,ga as t,gc as V,ha as u,hc as W,ia as v,ic as X,ja as w,jc as Y,ka as x,kc as Z,la as y,lc as _,ma as z,mc as $,nc as aa,oc as ba,pc as ca,qc as da,rc as ea,sc as fa,yb as B,zb as C}from"./chunk-Q4GSHKL5.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import{h as d,n as e,o as f,p as g,q as h,r as i,s as j,t as k,u as l}from"./chunk-XFXMLS67.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{A as AuthMissingError,d as BASE_AUTH_FIELDS,ca as CORSAIR_INTERNAL,G as CloudApiError,B as CorsairKekMissingError,C as DB_METHOD_RISK,Q as MS_GRAPH_API_BASE,z as ManagementApiError,L as OAuthRefreshError,r as PermissionRequiredError,a as ProviderDisplayNames,s as ReadonlyForbiddenError,c as ReconnectRequiredError,u as activeMode,X as asRecord,y as assertModeAllows,x as assertReadonlyAllowed,F as callPluginDb,U as collectPluginWebhookMatchers,H as corsairCloud,n as createAccountKeyManager,da as createCorsair,m as createIntegrationKeyManager,E as decodeDbArgs,ba as decodePubSubData,k as decryptConfig,g as decryptDEK,i as decryptWithDEK,D as encodeDbArgs,j as encryptConfig,f as encryptDEK,h as encryptWithDEK,K as exchangeCodeForTokens,_ as extractMicrosoftGraphValidationToken,aa as firstString,N as formatDocSchemaShape,b as formatProviderDisplayName,e as generateDEK,V as getHeader,M as getOAuthAccessToken,P as googleChannelSubscribe,p as initializeAccountDEK,o as initializeIntegrationDEK,O as introspectPluginForDocs,$ as isMicrosoftGraphValidationHandshake,w as isReadonlyScopeActive,I as logEvent,J as logEventFromContext,S as matchWebhookPlugin,T as matchWebhookPluginAndTenant,R as msGraphSubscribe,l as reEncryptConfig,Y as readBodyRecord,Z as readQueryParam,q as resolveConnectLink,v as runReadonly,t as runWithMode,ea as shouldStartTunnel,fa as superviseTunnel,W as toExternalId};
1
+ import{$b as P,Ab as E,Bb as F,Cb as G,D as n,Db as H,E as o,Eb as I,F as p,G as q,Sb as J,Tb as K,Ub as L,Vb as M,Wb as N,_b as O,a,ac as Q,b,ba as r,bb as B,bc as R,c,ca as s,cc as S,dc as T,ec as U,fa as t,fc as V,ga as u,gc as W,ha as v,hc as X,ia as w,ic as Y,ja as x,jc as Z,ka as y,kc as _,la as z,lc as $,ma as A,mc as aa,nc as ba,oc as ca,pc as da,qc as ea,rc as fa,sc as ga,yb as C,zb as D}from"./chunk-JDPLOTGP.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import{D as m,h as d,n as e,o as f,p as g,q as h,r as i,s as j,t as k,u as l}from"./chunk-KOJBIKQZ.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{m as AccountSelectionError,B as AuthMissingError,d as BASE_AUTH_FIELDS,da as CORSAIR_INTERNAL,H as CloudApiError,C as CorsairKekMissingError,D as DB_METHOD_RISK,R as MS_GRAPH_API_BASE,A as ManagementApiError,M as OAuthRefreshError,s as PermissionRequiredError,a as ProviderDisplayNames,t as ReadonlyForbiddenError,c as ReconnectRequiredError,v as activeMode,Y as asRecord,z as assertModeAllows,y as assertReadonlyAllowed,G as callPluginDb,V as collectPluginWebhookMatchers,I as corsairCloud,o as createAccountKeyManager,ea as createCorsair,n as createIntegrationKeyManager,F as decodeDbArgs,ca as decodePubSubData,k as decryptConfig,g as decryptDEK,i as decryptWithDEK,E as encodeDbArgs,j as encryptConfig,f as encryptDEK,h as encryptWithDEK,L as exchangeCodeForTokens,$ as extractMicrosoftGraphValidationToken,ba as firstString,O as formatDocSchemaShape,b as formatProviderDisplayName,e as generateDEK,W as getHeader,N as getOAuthAccessToken,Q as googleChannelSubscribe,q as initializeAccountDEK,p as initializeIntegrationDEK,P as introspectPluginForDocs,aa as isMicrosoftGraphValidationHandshake,x as isReadonlyScopeActive,J as logEvent,K as logEventFromContext,T as matchWebhookPlugin,U as matchWebhookPluginAndTenant,S as msGraphSubscribe,l as reEncryptConfig,Z as readBodyRecord,_ as readQueryParam,r as resolveConnectLink,w as runReadonly,u as runWithMode,fa as shouldStartTunnel,ga as superviseTunnel,X as toExternalId};
package/dist/hub.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { aZ as HubOAuthMode, A as AuthTypes, a_ as HubConnectSessionResult, a$ as HubPermissionSessionResult, H as HubConfig, b0 as HubConfigInput, b1 as HubConnectSessionInput, b2 as HubListProjectConnectionsInput, f as AccountKeyManagerFor, b3 as HubPermissionSessionInput } from './index-DfwzI6WA.js';
2
- export { b4 as DEFAULT_HUB_API_URL, b5 as HubEnvironmentSlug, aG as formatProviderDisplayName } from './index-DfwzI6WA.js';
3
- import { R as RunResultPayload, P as ProbeResultPayload, h as TunnelType, c as ProcessCorsairRequest, m as WebhookTenantLink } from './index-uHFiiaZb.js';
4
- export { n as BROWSER_DELIVERY_TTL_MS, o as BrowserDeliveryMode, B as BrowserDeliveryPayload, S as SIGNED_TUNNEL_REPLAY_WINDOW_MS, g as TunnelEnvelope } from './index-uHFiiaZb.js';
5
- export { b as buildBrowserDeliveryRedirectUrl, s as signBrowserDeliveryToken, v as verifyBrowserDeliveryToken } from './browser-delivery-_kIRM0EM.js';
1
+ import { b2 as HubOAuthMode, A as AuthTypes, b3 as HubConnectSessionResult, b4 as HubPermissionSessionResult, H as HubConfig, b5 as HubConfigInput, b6 as HubConnectSessionInput, b7 as HubListProjectConnectionsInput, f as AccountKeyManagerFor, k as AccountSelectionError, b8 as HubPermissionSessionInput } from './index-CVBmlS4w.js';
2
+ export { b9 as DEFAULT_HUB_API_URL, ba as HubEnvironmentSlug, aK as formatProviderDisplayName } from './index-CVBmlS4w.js';
3
+ import { R as RunResultPayload, P as ProbeResultPayload, h as TunnelType, c as ProcessCorsairRequest, m as WebhookTenantLink } from './index-Cnk2Dmi2.js';
4
+ export { n as BROWSER_DELIVERY_TTL_MS, o as BrowserDeliveryMode, B as BrowserDeliveryPayload, S as SIGNED_TUNNEL_REPLAY_WINDOW_MS, g as TunnelEnvelope } from './index-Cnk2Dmi2.js';
5
+ export { b as buildBrowserDeliveryRedirectUrl, s as signBrowserDeliveryToken, v as verifyBrowserDeliveryToken } from './browser-delivery-BAxysT_B.js';
6
6
  import 'zod';
7
7
  import './db.js';
8
8
  import 'kysely';
@@ -433,7 +433,7 @@ declare function getManagedAccessToken(ctx: ManagedAuthContext, options?: {
433
433
  }): Promise<ManagedAccessTokenResult>;
434
434
  declare function attachManagedRefreshAuth(ctx: Record<string, unknown>, managedContext: ManagedAuthContext): Promise<void>;
435
435
 
436
- type ManagedOAuthDeliveryErrorCode = 'invalid_corsair_instance' | 'no_database' | 'plugin_not_found' | 'no_access_token';
436
+ type ManagedOAuthDeliveryErrorCode = 'invalid_corsair_instance' | 'no_database' | 'plugin_not_found' | 'no_access_token' | AccountSelectionError['code'];
437
437
  declare class ManagedOAuthDeliveryError extends Error {
438
438
  readonly code: ManagedOAuthDeliveryErrorCode;
439
439
  constructor(code: ManagedOAuthDeliveryErrorCode, message: string);
@@ -447,6 +447,10 @@ type ProcessManagedOAuthDeliveryOptions = {
447
447
  scope?: string;
448
448
  authType?: 'managed' | 'oauth_2';
449
449
  providerData?: Record<string, unknown>;
450
+ account?: {
451
+ id: string;
452
+ label?: string;
453
+ };
450
454
  };
451
455
  type ProcessManagedOAuthDeliveryResult = {
452
456
  plugin: string;
package/dist/hub.js CHANGED
@@ -1 +1 @@
1
- import{$a as ca,A as z,Aa as T,B as A,Ba as U,C as B,Ca as V,Da as W,L as C,Qa as X,Ra as Y,Sa as Z,Xa as _,Ya as $,Za as aa,_a as ba,aa as D,ab as da,b as a,cb as ea,d as b,da as E,db as fa,e as c,ea as F,eb as ga,f as d,fb as ha,g as e,gb as ia,h as f,hb as ja,i as g,ib as ka,j as i,jb as la,k as j,kb as ma,l as k,lb as na,m as l,mb as oa,n as m,na as G,nb as pa,o as n,oa as H,ob as qa,p as o,pa as I,pb as ra,q as p,qa as J,qb as sa,r as q,ra as K,rb as ta,s as r,sa as L,sb as ua,t as s,ta as M,tb as va,u as t,ua as N,ub as wa,v as u,va as O,vb as xa,w as v,wa as P,wb as ya,x as w,xa as Q,xb as za,y as x,ya as R,z as y,za as S}from"./chunk-Q4GSHKL5.js";import{a as h,b as Aa,c as Ba,d as Ca,e as Da,f as Ea}from"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-XFXMLS67.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{m as BROWSER_DELIVERY_TTL_MS,Ba as CORSAIR_TUNNEL_PATH,Aa as CORSAIR_TUNNEL_ZONE,u as DEFAULT_HUB_API_URL,Ca as FRPC_VERSION,w as HubCredentialsMissingError,v as HubNotConfiguredError,V as ManagedOAuthDeliveryError,n as SIGNED_TUNNEL_REPLAY_WINDOW_MS,fa as attachManagedRefreshAuth,p as buildBrowserDeliveryRedirectUrl,s as buildClientBridgeBrowserDeliveryUrl,la as createConnectSessionJti,qa as createConnectTokenJti,D as createHubConnectSession,E as createHubPermissionSession,ka as createHubRouteHandlers,ia as createManagedPricingCredentialCache,wa as createPermissionSessionJti,o as createSignedTokenJti,pa as decodeConnectSessionTokenFromPath,va as decodeConnectTokenFromPath,za as decodePermissionTokenFromPath,Q as deliverConnectCreateLink,U as deliverSignedEnvelope,S as describeDeliveryNetworkError,ua as encodeConnectTokenForPath,O as extractConnectLinkFromDeliveryAck,H as extractProbeFromDeliveryAck,G as extractRunFromDeliveryAck,N as extractSyncFromDeliveryAck,F as formatHubApprovalMessage,a as formatProviderDisplayName,T as formatServerDeliveryError,Da as frpcPlatformKey,ma as getConnectSessionExpiryMs,X as getConnectStatusForTenant,ra as getConnectTokenExpiryMs,z as getHubConfig,ea as getManagedAccessToken,ha as getManagedPricingApiKey,_ as handleHubDeliveryGet,$ as handleHubDeliveryPost,ba as handleHubDeliveryRequest,aa as hubDeliveryToResponse,B as inferHubEnvironmentSlug,i as isLoopbackUrl,M as isServerDeliveryAckSuccessful,Y as listHubProjectConnections,x as normalizeHubConfig,P as parseConnectLinkFromDeliveryBody,b as parseConnectSessionResponse,f as parseConnectStatusResponse,g as parseHubApiErrorBody,Z as parseManagedPricingCredentialsResponse,e as parseOAuthRefreshResponse,d as parsePermissionSessionResponse,c as parseProjectConnectionsResponse,L as parseServerDeliveryAckBody,R as parseSyncFromDeliveryBody,t as prepareClientBridgeDeliveryTransport,W as processManagedOAuthDelivery,C as registerHubWebhookTenantLink,ga as requireHubForManagedPricing,j as resolveDeliveryTransport,Ea as resolveFrpcBinary,y as resolveHubConfigInput,h as resolveHubDeliveryUrl,A as resolveHubOAuthCallbackUrl,ja as resolveManagedPricingApiKey,ca as respondToHubDelivery,da as respondToHubDeliveryFromRequest,q as signBrowserDeliveryToken,na as signConnectSessionToken,sa as signConnectToken,I as signDeliveryEnvelope,xa as signPermissionToken,k as usesBrowserDelivery,l as validateProductionDeliveryUrl,r as verifyBrowserDeliveryToken,oa as verifyConnectSessionToken,ta as verifyConnectToken,J as verifyDeliveryEnvelope,ya as verifyPermissionToken,K as verifySignedTunnelDelivery};
1
+ import{$a as ca,A as z,Aa as T,B as A,Ba as U,C as B,Ca as V,Da as W,L as C,Qa as X,Ra as Y,Sa as Z,Xa as _,Ya as $,Za as aa,_a as ba,aa as D,ab as da,b as a,cb as ea,d as b,da as E,db as fa,e as c,ea as F,eb as ga,f as d,fb as ha,g as e,gb as ia,h as f,hb as ja,i as g,ib as ka,j as i,jb as la,k as j,kb as ma,l as k,lb as na,m as l,mb as oa,n as m,na as G,nb as pa,o as n,oa as H,ob as qa,p as o,pa as I,pb as ra,q as p,qa as J,qb as sa,r as q,ra as K,rb as ta,s as r,sa as L,sb as ua,t as s,ta as M,tb as va,u as t,ua as N,ub as wa,v as u,va as O,vb as xa,w as v,wa as P,wb as ya,x as w,xa as Q,xb as za,y as x,ya as R,z as y,za as S}from"./chunk-JDPLOTGP.js";import{a as h,b as Aa,c as Ba,d as Ca,e as Da,f as Ea}from"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-KOJBIKQZ.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{m as BROWSER_DELIVERY_TTL_MS,Ba as CORSAIR_TUNNEL_PATH,Aa as CORSAIR_TUNNEL_ZONE,u as DEFAULT_HUB_API_URL,Ca as FRPC_VERSION,w as HubCredentialsMissingError,v as HubNotConfiguredError,V as ManagedOAuthDeliveryError,n as SIGNED_TUNNEL_REPLAY_WINDOW_MS,fa as attachManagedRefreshAuth,p as buildBrowserDeliveryRedirectUrl,s as buildClientBridgeBrowserDeliveryUrl,la as createConnectSessionJti,qa as createConnectTokenJti,D as createHubConnectSession,E as createHubPermissionSession,ka as createHubRouteHandlers,ia as createManagedPricingCredentialCache,wa as createPermissionSessionJti,o as createSignedTokenJti,pa as decodeConnectSessionTokenFromPath,va as decodeConnectTokenFromPath,za as decodePermissionTokenFromPath,Q as deliverConnectCreateLink,U as deliverSignedEnvelope,S as describeDeliveryNetworkError,ua as encodeConnectTokenForPath,O as extractConnectLinkFromDeliveryAck,H as extractProbeFromDeliveryAck,G as extractRunFromDeliveryAck,N as extractSyncFromDeliveryAck,F as formatHubApprovalMessage,a as formatProviderDisplayName,T as formatServerDeliveryError,Da as frpcPlatformKey,ma as getConnectSessionExpiryMs,X as getConnectStatusForTenant,ra as getConnectTokenExpiryMs,z as getHubConfig,ea as getManagedAccessToken,ha as getManagedPricingApiKey,_ as handleHubDeliveryGet,$ as handleHubDeliveryPost,ba as handleHubDeliveryRequest,aa as hubDeliveryToResponse,B as inferHubEnvironmentSlug,i as isLoopbackUrl,M as isServerDeliveryAckSuccessful,Y as listHubProjectConnections,x as normalizeHubConfig,P as parseConnectLinkFromDeliveryBody,b as parseConnectSessionResponse,f as parseConnectStatusResponse,g as parseHubApiErrorBody,Z as parseManagedPricingCredentialsResponse,e as parseOAuthRefreshResponse,d as parsePermissionSessionResponse,c as parseProjectConnectionsResponse,L as parseServerDeliveryAckBody,R as parseSyncFromDeliveryBody,t as prepareClientBridgeDeliveryTransport,W as processManagedOAuthDelivery,C as registerHubWebhookTenantLink,ga as requireHubForManagedPricing,j as resolveDeliveryTransport,Ea as resolveFrpcBinary,y as resolveHubConfigInput,h as resolveHubDeliveryUrl,A as resolveHubOAuthCallbackUrl,ja as resolveManagedPricingApiKey,ca as respondToHubDelivery,da as respondToHubDeliveryFromRequest,q as signBrowserDeliveryToken,na as signConnectSessionToken,sa as signConnectToken,I as signDeliveryEnvelope,xa as signPermissionToken,k as usesBrowserDelivery,l as validateProductionDeliveryUrl,r as verifyBrowserDeliveryToken,oa as verifyConnectSessionToken,ta as verifyConnectToken,J as verifyDeliveryEnvelope,ya as verifyPermissionToken,K as verifySignedTunnelDelivery};
@@ -1,5 +1,5 @@
1
1
  import { CorsairDatabase } from './db.js';
2
- import { C as CorsairPlugin, a as CorsairPermissionsOptions, b as CorsairManualConfig, H as HubConfig, c as CorsairIntegration, d as CorsairTenantWrapper, e as CorsairSingleTenantClient } from './index-DfwzI6WA.js';
2
+ import { C as CorsairPlugin, a as CorsairPermissionsOptions, b as CorsairManualConfig, H as HubConfig, c as CorsairIntegration, d as CorsairTenantWrapper, e as CorsairSingleTenantClient } from './index-CVBmlS4w.js';
3
3
 
4
4
  declare const CORSAIR_INTERNAL: unique symbol;
5
5
  type CorsairInternalConfig = {
@@ -7,6 +7,7 @@ type CorsairInternalConfig = {
7
7
  database: CorsairDatabase | undefined;
8
8
  kek: string;
9
9
  multiTenancy: boolean;
10
+ multiAccount: boolean;
10
11
  permissions?: CorsairPermissionsOptions;
11
12
  manual?: CorsairManualConfig;
12
13
  hub?: HubConfig;
@@ -1,6 +1,7 @@
1
1
  import { ZodTypeAny } from 'zod';
2
- import { CorsairDatabase, CorsairPermission, CorsairDatabaseInput, CorsairDbTables } from './db.js';
2
+ import { CorsairKyselyDatabase, CorsairDatabase, CorsairPermission, CorsairDatabaseInput, CorsairDbTables } from './db.js';
3
3
  import { CorsairPluginSchema, PluginEntityClients } from './orm.js';
4
+ import { Selectable } from 'kysely';
4
5
 
5
6
  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
7
  declare const BaseProviders: readonly ["ably", "abstract", "abuseipdb", "abyssale", "accrediblecertificates", "activecampaign", "activetrail", "addresszen", "adyntel", "aeroleads", "affinda", "agencyzoom", "agentmail", "agentql", "agenty", "agiled", "agilitycms", "ahrefs", "aimlapi", "airtable", "aivoov", "akta", "alchemy", "algolia", "alibaba", "allimagesai", "alphavantage", "altoviz", "alttextai", "amara", "ambee", "ambientweather", "amcards", "amplitude", "anchorbrowser", "anonyflow", "anthropicadministrator", "anyapi", "apaleo", "api2pdf", "apibible", "apify", "apilabz", "apininjas", "apipie", "apisports", "apollo", "appointo", "aryn", "asana", "ascora", "ashby", "asindataapi", "asticaai", "asyncinterview", "attio", "autom", "ayrshare", "backendless", "bannerbear", "bart", "basecamp", "baselinker", "basin", "beaconstac", "beamer", "beeminder", "benchmarkemail", "benzinga", "bestbuy", "bettercontact", "betterproposals", "betterstack", "bigdatacloud", "bigmailer", "bigml", "bigpictureio", "bitbucket", "bitwarden", "blackbaud", "blazemeter", "blocknative", "bluesky", "boldsign", "boloforms", "boltiot", "bonsai", "bookingmood", "booqable", "borneo", "botbaba", "botpress", "botsonic", "bouncer", "box", "boxhero", "brandfetch", "breathehr", "brevo", "brex", "brightdata", "browseai", "browserless", "browsertool", "browseruse", "bubble", "bugsnag", "buildkite", "builtwith", "bunnycdn", "bytedance", "byteforms", "cal", "calendly", "callingly", "callpage", "campaigncleaner", "campayn", "canny", "canva", "canvas", "capsulecrm", "carbone", "castingwords", "cdrplatform", "celigo", "certifier", "certspotter", "chaser", "chatbotkit", "chatfai", "chatwork", "chmeetings", "cincopa", "circleci", "claidai", "classmarker", "clay", "clickhouse", "clickmeeting", "clicksend", "clickup", "clientary", "clockify", "cloro", "close", "cloudcart", "cloudconvert", "cloudflare", "cloudflareapikey", "cloudflarebrowserrendering", "cloudinary", "cloudlayer", "coassemble", "coda", "codacy", "codeinterpreter", "codereadr", "cody", "coinbase", "coinmarketcal", "coinmarketcap", "collegefootballdata", "commcare", "companyenrich", "composio", "confluence", "connecteam", "contactout", "contentfulgraphql", "contextdev", "contextsevenmcp", "conversiontools", "convex", "convoloai", "cosmic", "countdownapi", "craftmypdf", "crowterminal", "currencyscoop", "currentsapi", "cursor", "customerio", "customgpt", "customjs", "cuttly", "d2lbrightspace", "dadataru", "daffy", "databox", "databricks", "datadog", "dataforseo", "datarobot", "deepline", "deepseek", "demio", "deployhq", "desktime", "devinmcp", "dialpad", "diffbot", "digicert", "digitalocean", "discord", "dnsfilter", "dockerhub", "docmosis", "docsbotai", "docsumo", "documenso", "docupost", "docusign", "dodopayments", "doppler", "dopplermarketingautomation", "dovetail", "draftable", "dreamstudio", "dripcel", "dropbox", "dropboxsign", "dropcontact", "dynapictures", "e2b", "echtpost", "ecologi", "elevenlabs", "elorus", "emailoctopus", "emelia", "encodian", "endorsal", "enginemailer", "enigma", "epicgames", "esignatures", "erpnext", "esputnik", "etermin", "eventbrite", "eventee", "eventzilla", "everhour", "exa", "excel", "exist", "extractaai", "facebook", "fal", "faraday", "fathom", "felt", "fibery", "fidel", "figma", "filevine", "filloutforms", "finage", "findymail", "finerworks", "finmei", "fireberry", "firecrawl", "fireflies", "fixer", "flexisign", "flutterwave", "fluxguard", "fly", "folk", "followupboss", "fomo", "forcemanager", "formbricks", "formdesk", "foursquare", "freeagent", "freshdesk", "fundable", "gagelist", "gamma", "gatherup", "gemini", "genderapi", "genderapiio", "genderize", "geoapify", "geocodio", "geokeo", "getprospect", "giftup", "gigasheet", "giphy", "github", "gitlab", "givebutter", "gladia", "gleap", "globalping", "gmail", "gmicloud", "godial", "gong", "googleaddressvalidation", "googleanalytics", "googlebigquery", "googlecalendar", "googleclassroom", "googlecloudvision", "googledocs", "googledrive", "googlemaps", "googlemeet", "googlesheets", "googleslides", "googletasks", "gorgias", "gosquared", "grafana", "griptape", "grist", "groqcloud", "gumroad", "habitica", "hackernews", "handwrytten", "happyscribe", "harvest", "hashnode", "helpscout", "helpwise", "here", "hex", "heygen", "heyy", "higgsfield", "honeyhive", "hookdeck", "htmltoimage", "hubplanner", "hubspot", "huggingface", "humanitix", "hunterio", "hyperbrowser", "ignisign", "imagekit", "imagior", "imejisio", "imgbb", "imgix", "inboxkit", "insightoai", "instagram", "instantly", "intercom", "ip2proxy", "ip2whois", "jigsawstack", "jira", "jobnimbus", "jotform", "junglescout", "kadoa", "kaggle", "kalshi", "kanbanize", "keen", "keenable", "keyword", "kibana", "kickbox", "kit", "klaviyo", "klazify", "kling", "klipfolio", "knack", "kofi", "kommo", "kontentai", "krakenio", "labs64netlicensing", "launchdarkly", "leexi", "leiga", "lemonsqueezy", "lever", "linear", "linguapop", "linkedin", "litescrape", "livesession", "logodev", "loyverse", "magichour", "mailboxlayer", "mailcheck", "mailchimp", "mailsso", "mailtrap", "make", "mapbox", "marketstack", "melo", "mem0", "memberstack", "memberspot", "merriamwebsterdict", "minerstat", "minimax", "miro", "missive", "mistralai", "mixmax", "modelry", "monday", "mondaymcp", "moonclerk", "motion", "mrscraper", "nanonets", "neon", "netsuite", "neverbounce", "newsapi", "nextdns", "northflank", "notion", "nutshell", "ocrspace", "ocrwebservice", "octen", "ollama", "onedesk", "onedrive", "onepassword", "openai", "opengraph", "openrouter", "opensea", "openweathermap", "orbit", "oura", "outlook", "pagerduty", "parallel", "parma", "parsehub", "parseur", "pdfapi", "pdfco", "pdfless", "pdfmonkey", "pdl", "perplexityai", "phantombuster", "pinecone", "pipedrive", "placid", "plain", "platerecognizer", "ploid", "pointagram", "polygon", "polygonio", "postalytics", "postgrid", "postiz", "postmark", "prerender", "prismic", "proabono", "posthog", "postman", "prisma", "proofly", "pushbullet", "pushover", "qdrant", "quaderno", "radar", "ragic", "raisely", "ramp", "razorpay", "realphonevalidation", "reamaze", "recallai", "recruitee", "redcircle", "reddit", "reducto", "referralrock", "refiner", "remarkety", "remoet", "remoteretrieval", "removebg", "render", "renderform", "rentman", "repairshopr", "replicate", "replyio", "resend", "respondio", "retailed", "retellai", "retently", "revai", "revolt", "ritekit", "roam", "roboflow", "rocketlane", "rocketreach", "rollbar", "rootly", "rosette", "route4me", "rudderstacktransform", "runpod", "salesflare", "salesforce", "sanity", "saperly", "sapsuccessfactors", "satismeter", "scaleai", "scrapedo", "scrapegraphai", "scrapingant", "screenshotone", "search1api", "searchapi", "securitytrails", "semanticscholar", "sendbird", "sendgrid", "sensibo", "sentry", "serpapi", "serply", "servicem8", "servicenow", "sevdesk", "sharepoint", "shipengine", "shippo", "shopify", "shortcut", "shortio", "signpath", "signwell", "similarweb", "simlacom", "simpleanalytics", "simplekpi", "simplero", "simplesat", "slack", "slackbot", "smsalert", "snapchat", "snowflake", "sourcegraph", "splitwise", "spoki", "spotlightr", "spotify", "square", "stackai", "stackexchange", "starton", "strava", "streamtime", "stripe", "storyblok", "studiobyai21labs", "suitedash", "superchat", "supersaas", "supabase", "supadata", "supportbee", "surf", "surveymonkey", "swaggerhub", "suzanne", "svix", "sympla", "synthflowai", "taggun", "talenthr", "tapfiliate", "tally", "tave", "telnyx", "teltel", "thanksio", "tavily", "taxjar", "tavilymcp", "templated", "textcortex", "teamcamp", "teams", "teamwork", "telegram", "textit", "textrazor", "thinkific", "ticketmaster", "ticktick", "tikhub", "timecamp", "timelink", "timely", "tinyfish", "tinypng", "tinyurl", "tisane", "tldv", "todoist", "tomba", "tomtom", "toggl", "tokenmetrics", "toneden", "tpscheck", "trello", "triggercmd", "tripadvisor", "trustpilot", "truvera", "turbotpipes", "turso", "twelvedata", "twentyonerisk", "twilio", "twitter", "twitterapiio", "twocaptcha", "twochat", "typeform", "typesafe", "u301", "unione", "unipile", "unisender", "uniswapapi", "updownio", "uploadcare", "uptimerobot", "userflow", "userlist", "vapi", "vaquill", "vectorshift", "vercel", "veriphone", "vestaboard", "virustotal", "waboxapp", "wachete", "waiverfile", "wakatime", "wati", "webex", "webflow", "webscraperio", "webscrapingai", "webvizio", "whatsapp", "whautomate", "whoisfreaks", "winstonai", "witai", "wix", "wiza", "woodpeckerco", "workable", "workday", "workiom", "worksnaps", "worldnewsapi", "wrike", "writer", "xero", "xquik", "yandex", "ynab", "youcom", "youtube", "zendesk", "zenrows", "zenserp", "zohobigin", "zohodesk", "zohoinventory", "zohomail", "zoom", "zoominfo"];
@@ -756,6 +757,8 @@ type HubConfigInput = {
756
757
  * to Hub. Leave unset elsewhere.
757
758
  */
758
759
  runtimeProofKey?: string;
760
+ /** Set from `createCorsair({ multiAccount })`; gates the capability header. */
761
+ multiAccount?: boolean;
759
762
  };
760
763
  /**
761
764
  * Overrides for Corsair's self-hosted frp auto-tunnel. The frpc binary ships
@@ -784,6 +787,7 @@ type HubConfig = {
784
787
  * to Hub. Leave unset elsewhere.
785
788
  */
786
789
  runtimeProofKey?: string;
790
+ multiAccount?: boolean;
787
791
  };
788
792
  type HubConnectSessionInput = {
789
793
  /** When omitted, the connect link covers all configured plugins. */
@@ -978,7 +982,14 @@ type IntegrationKeyManagerFor<T extends AuthTypes, Config extends PluginAuthConf
978
982
  * @template T - The auth type
979
983
  * @template Config - Optional plugin auth config for extension fields
980
984
  */
981
- type AccountKeyManagerFor<T extends AuthTypes, Config extends PluginAuthConfig | undefined = undefined> = BaseKeyManager & AllFieldAccessors<AccountFieldNames<T, Config>> & (T extends 'oauth_2' ? {
985
+ type AccountKeyManagerFor<T extends AuthTypes, Config extends PluginAuthConfig | undefined = undefined> = BaseKeyManager & {
986
+ /**
987
+ * Runs `run` once for concurrent callers with the same name on this account,
988
+ * however each caller reached it. Optional: key managers built outside the
989
+ * SDK need not have it.
990
+ */
991
+ single_flight?: <R>(name: string, run: () => Promise<R>) => Promise<R>;
992
+ } & AllFieldAccessors<AccountFieldNames<T, Config>> & (T extends 'oauth_2' ? {
982
993
  /**
983
994
  * Get the integration-level OAuth2 credentials (client_id, client_secret, redirect_url).
984
995
  * Useful for token refresh flows that need access to both account and integration secrets.
@@ -986,6 +997,25 @@ type AccountKeyManagerFor<T extends AuthTypes, Config extends PluginAuthConfig |
986
997
  get_integration_credentials: () => Promise<OAuth2IntegrationCredentials>;
987
998
  } : {});
988
999
 
1000
+ type AccountConfig = Selectable<CorsairKyselyDatabase['corsair_accounts']>['config'];
1001
+ type Account = {
1002
+ id: string;
1003
+ ref?: string;
1004
+ label?: string;
1005
+ config: AccountConfig;
1006
+ dek: string | null;
1007
+ };
1008
+ type AccountSummary = {
1009
+ id: string;
1010
+ ref?: string;
1011
+ label?: string;
1012
+ };
1013
+ declare class AccountSelectionError extends Error {
1014
+ code: 'account_required' | 'account_not_found' | 'account_limit';
1015
+ accounts: AccountSummary[];
1016
+ constructor(code: AccountSelectionError['code'], message: string, accounts?: AccountSelectionError['accounts']);
1017
+ }
1018
+
989
1019
  /** Handle for one chat: `corsair.withTenant(t).chats.get(id).message(...)`. */
990
1020
  interface ChatHandle {
991
1021
  /** Send a message to this chat; the agent may create/edit the workflow. */
@@ -1141,6 +1171,9 @@ type Tenant = {
1141
1171
  id: string;
1142
1172
  accounts: Array<{
1143
1173
  integrationName: string;
1174
+ accountId: string;
1175
+ ref?: string;
1176
+ label?: string;
1144
1177
  hasCredentials: boolean;
1145
1178
  }>;
1146
1179
  connectedPlugins: string[];
@@ -1225,6 +1258,8 @@ type DisconnectInput = {
1225
1258
  /** Plugin whose connection to remove for the tenant. */
1226
1259
  plugin: string;
1227
1260
  tenantId?: string;
1261
+ /** Remove only this account (row id, provider id or label); omit for all. */
1262
+ account?: string;
1228
1263
  };
1229
1264
  type DisconnectResult = {
1230
1265
  ok: true;
@@ -1260,6 +1295,19 @@ type CorsairManageNamespace = {
1260
1295
  disconnect: (input: DisconnectInput) => Promise<DisconnectResult>;
1261
1296
  };
1262
1297
 
1298
+ /** Per-account modes: plugin id → account (its id, ref or label) → mode. */
1299
+ type AccountModes = Record<string, Record<string, PermissionMode>>;
1300
+ /** A caller's mode: one for every call, or a default with modes per account. */
1301
+ type ModeScope = PermissionMode | {
1302
+ mode?: PermissionMode;
1303
+ accounts?: AccountModes;
1304
+ };
1305
+ /** The names an account answers to, any of which a mode can be keyed by. */
1306
+ type AccountNames = {
1307
+ id: string;
1308
+ ref?: string;
1309
+ label?: string;
1310
+ };
1263
1311
  /**
1264
1312
  * Thrown when a write or destructive operation is attempted inside a
1265
1313
  * {@link runReadonly} scope. Aborts the whole script so the agent must retry with
@@ -1270,10 +1318,17 @@ declare class ReadonlyForbiddenError extends Error {
1270
1318
  readonly riskLevel: EndpointRiskLevel;
1271
1319
  constructor(endpointPath: string, riskLevel: EndpointRiskLevel);
1272
1320
  }
1273
- /** Runs `fn` under `mode`. Nesting never widens: the stricter of the two wins. */
1274
- declare function runWithMode<T>(mode: PermissionMode, fn: () => T): T;
1275
- /** The mode in effect for the current async context, if any. */
1276
- declare function activeMode(): PermissionMode | undefined;
1321
+ /**
1322
+ * Runs `fn` under `scope`. Nesting never widens: each call takes the stricter
1323
+ * of what every open scope gives its account.
1324
+ */
1325
+ declare function runWithMode<T>(scope: ModeScope, fn: () => T): T;
1326
+ /**
1327
+ * The mode in effect for the current async context, if any. Given the plugin
1328
+ * and the account a call is for, that account's own mode counts; without
1329
+ * them, the strictest any account could get.
1330
+ */
1331
+ declare function activeMode(plugin?: string, names?: AccountNames): PermissionMode | undefined;
1277
1332
  /**
1278
1333
  * Runs `fn` in a scope where every Corsair endpoint call is forced to read-only.
1279
1334
  * Any write/destructive endpoint invoked within (including in nested async calls)
@@ -1281,19 +1336,19 @@ declare function activeMode(): PermissionMode | undefined;
1281
1336
  */
1282
1337
  declare function runReadonly<T>(fn: () => T): T;
1283
1338
  /** Whether the current async context is inside a {@link runReadonly} scope. */
1284
- declare function isReadonlyScopeActive(): boolean;
1339
+ declare function isReadonlyScopeActive(plugin?: string, names?: AccountNames): boolean;
1285
1340
  /**
1286
1341
  * Guard invoked by the endpoint binding layer before any endpoint runs. When a
1287
1342
  * read-only scope is active and the endpoint is not a `read` operation, throws
1288
1343
  * {@link ReadonlyForbiddenError}. No-op otherwise.
1289
1344
  */
1290
- declare function assertReadonlyAllowed(endpointPath: string, riskLevel: EndpointRiskLevel): void;
1345
+ declare function assertReadonlyAllowed(endpointPath: string, riskLevel: EndpointRiskLevel, plugin?: string, names?: AccountNames): void;
1291
1346
  /**
1292
1347
  * Guard for paths that reach data without the endpoint binding layer: the
1293
1348
  * entity store and the cloud entity proxy. Neither records approval state, so
1294
1349
  * anything short of `allow` is refused rather than held.
1295
1350
  */
1296
- declare function assertModeAllows(endpointPath: string, riskLevel: EndpointRiskLevel): void;
1351
+ declare function assertModeAllows(endpointPath: string, riskLevel: EndpointRiskLevel, plugin?: string, names?: AccountNames): void;
1297
1352
  /**
1298
1353
  * The `corsair.permissions` namespace available at the root of every corsair instance.
1299
1354
  * Provides methods for querying and transitioning permission records.
@@ -1729,7 +1784,11 @@ type InferPluginNamespace<P extends CorsairPlugin> = P extends CorsairPlugin<inf
1729
1784
  * Only present if the plugin defines `pluginTenantWebhookMatcher`.
1730
1785
  */
1731
1786
  pluginTenantWebhookMatcher?: CorsairWebhookTenantMatcher;
1732
- } : {}) & (ExtractAuthType<InferPluginOptions<P>, InferDefaultAuthType<P>> extends AuthTypes ? {
1787
+ } : {}) & {
1788
+ accounts: {
1789
+ list(): Promise<AccountSummary[]>;
1790
+ };
1791
+ } & (ExtractAuthType<InferPluginOptions<P>, InferDefaultAuthType<P>> extends AuthTypes ? {
1733
1792
  keys: AccountKeyManagerFor<ExtractAuthType<InferPluginOptions<P>, InferDefaultAuthType<P>>, InferAuthConfig<P>>;
1734
1793
  } : {});
1735
1794
  } : never;
@@ -1769,7 +1828,11 @@ type CorsairClient<Plugins extends readonly CorsairPlugin[]> = InferPluginNamesp
1769
1828
  * Also includes integration-level `keys` for managing shared secrets (OAuth2 client credentials, etc.)
1770
1829
  */
1771
1830
  type CorsairTenantWrapper<Plugins extends readonly CorsairPlugin[]> = {
1772
- withTenant: (tenantId: string) => CorsairClient<Plugins>;
1831
+ withTenant: (tenantId: string, options?: {
1832
+ accounts?: {
1833
+ [P in Plugins[number]['id']]?: string;
1834
+ };
1835
+ }) => CorsairClient<Plugins>;
1773
1836
  /**
1774
1837
  * Integration-level key managers for each plugin.
1775
1838
  * Used to manage secrets shared across all tenants (e.g., OAuth2 client_id, client_secret).
@@ -1808,6 +1871,10 @@ type CorsairSingleTenantClient<Plugins extends readonly CorsairPlugin[]> = Corsa
1808
1871
  */
1809
1872
  manage: CorsairManageNamespace;
1810
1873
  };
1874
+ /** Options of `withTenant`: per-plugin account refs. */
1875
+ type WithTenantOptions = {
1876
+ accounts?: Record<string, string | undefined>;
1877
+ };
1811
1878
 
1812
1879
  /**
1813
1880
  * Risk level classification for plugin endpoints.
@@ -1954,6 +2021,12 @@ type PluginPermissionsConfig<T extends EndpointTree = EndpointTree> = {
1954
2021
  * Only valid paths for this specific plugin compile — typos are type errors.
1955
2022
  */
1956
2023
  overrides?: Partial<Record<EndpointPathsOf<T>, PermissionPolicy>>;
2024
+ /**
2025
+ * A mode per account, keyed by its id or ref (e.g. its email). It
2026
+ * stands in for `mode` on that account's calls; the caller's mode still
2027
+ * tightens either.
2028
+ */
2029
+ accounts?: Record<string, PermissionMode>;
1957
2030
  };
1958
2031
  /**
1959
2032
  * Extracts the context type from an endpoint function.
@@ -2424,6 +2497,11 @@ type CorsairIntegration<Plugins extends readonly CorsairPlugin[]> = {
2424
2497
  plugins: Plugins;
2425
2498
  /** If true, enables tenant-scoped access via `withTenant()` */
2426
2499
  multiTenancy?: boolean;
2500
+ /**
2501
+ * Allow several accounts per tenant and plugin. Off (default): one account,
2502
+ * and connecting a different identity replaces it.
2503
+ */
2504
+ multiAccount?: boolean;
2427
2505
  /** Root-level error handlers that apply when plugin-specific handlers are not defined */
2428
2506
  errorHandlers?: CorsairErrorHandler;
2429
2507
  /**
@@ -2465,4 +2543,4 @@ type CorsairDeprecatedApprovalConfig = {
2465
2543
  approval?: CorsairPermissionsOptions;
2466
2544
  };
2467
2545
 
2468
- export { type EndpointMetaEntry as $, type AuthTypes as A, BASE_AUTH_FIELDS as B, type CorsairPlugin as C, type CorsairClient as D, type EndpointRiskLevel as E, type CorsairContext as F, type CorsairEndpoint as G, type HubConfig as H, type IntegrationKeyManagerFor as I, type CorsairErrorHandler as J, type CorsairKeyBuilder as K, type CorsairKeyBuilderBase as L, type CorsairOAuthWebhookTenantLinkResolver as M, type CorsairPermissionsNamespace as N, type OAuthConfig as O, type CorsairPluginContext as P, type CorsairPluginSubscribe as Q, type CorsairRunsNamespace as R, type CorsairWebhook as S, type CorsairWebhookHandler as T, type CorsairWebhookMatcher as U, type CorsairWebhookTenantMatcher as V, type WebhookTenantMatch as W, type CorsairWorkflowsNamespace as X, type CreateChatResult as Y, type EndpointHooks as Z, type EndpointJob as _, type CorsairPermissionsOptions as a, type HubPermissionSessionResult as a$, type EndpointPathsOf as a0, type EndpointTree as a1, type EnforcePermissionOptions as a2, type EnforcePermissionResult as a3, type ErrorContext as a4, type ErrorHandler as a5, type ErrorHandlerAndMatchFunction as a6, type ErrorMatcher as a7, type IntegrationFieldNames as a8, type KeyBuilderContext as a9, type WorkflowStatus as aA, type WorkflowSummary as aB, activeMode as aC, assertModeAllows as aD, assertReadonlyAllowed as aE, exchangeCodeForTokens as aF, formatProviderDisplayName as aG, isReadonlyScopeActive as aH, runReadonly as aI, runWithMode as aJ, type ManagementOk as aK, type Tenant as aL, type CreateTenantInput as aM, type PluginInfo as aN, type ConnectionStatus as aO, type PermissionLookupInput as aP, type PermissionRecord as aQ, type CreateConnectLinkInput as aR, type ConnectLink as aS, type ResolvedConnectLink as aT, type OAuthCallbackInput as aU, type OAuthCallbackResult as aV, type ConnectRequest as aW, type CorsairManageNamespace as aX, type PluginConnectionState as aY, type HubOAuthMode as aZ, type HubConnectSessionResult as a_, type OAuth2IntegrationCredentials as aa, type PermissionMode as ab, type PermissionPolicy as ac, type PickAuth as ad, type PluginAuthConfig as ae, type PluginEndpointMeta as af, type PluginPermissionsConfig as ag, ProviderDisplayNames as ah, type RawWebhookRequest as ai, ReadonlyForbiddenError as aj, type RequiredPluginEndpointMeta as ak, type RequiredPluginEndpointSchemas as al, type RequiredPluginWebhookSchemas as am, type RetryStrategies as an, type RetryStrategy as ao, type TokenResponse as ap, type TriggerRunResult as aq, type UnionToIntersection$1 as ar, type WebhookHooks as as, type WebhookPathsOf as at, type WebhookRequest as au, type WebhookResponse as av, type WebhookTree as aw, type WorkflowRun as ax, type WorkflowRunStatus as ay, type WorkflowRunStep as az, type CorsairManualConfig as b, type HubConfigInput as b0, type HubConnectSessionInput as b1, type HubListProjectConnectionsInput as b2, type HubPermissionSessionInput as b3, DEFAULT_HUB_API_URL as b4, type HubEnvironmentSlug as b5, type CorsairIntegration as c, type CorsairTenantWrapper as d, type CorsairSingleTenantClient as e, type AccountKeyManagerFor as f, type CorsairPluginSubscribeResult as g, type AccountFieldNames as h, type AgentMessageRole as i, type AgentReply as j, type AllProviders as k, type BaseAuthFieldConfig as l, type BaseKeyManager as m, BaseProviders as n, type BeforeHookResult as o, type BindEndpoints as p, type BindWebhooks as q, type Bivariant$2 as r, type BoundEndpointFn as s, type BoundEndpointTree as t, type BoundWebhook as u, type BoundWebhookTree as v, type ChatHandle as w, type ChatMessage as x, type ChatSummary as y, type CorsairChatsNamespace as z };
2546
+ export { type CreateChatResult as $, type AuthTypes as A, BASE_AUTH_FIELDS as B, type CorsairPlugin as C, type ChatMessage as D, type EndpointRiskLevel as E, type ChatSummary as F, type CorsairChatsNamespace as G, type HubConfig as H, type IntegrationKeyManagerFor as I, type CorsairClient as J, type CorsairContext as K, type CorsairEndpoint as L, type CorsairErrorHandler as M, type CorsairKeyBuilder as N, type OAuthConfig as O, type CorsairKeyBuilderBase as P, type CorsairOAuthWebhookTenantLinkResolver as Q, type CorsairPermissionsNamespace as R, type CorsairPluginContext as S, type CorsairPluginSubscribe as T, type CorsairRunsNamespace as U, type CorsairWebhook as V, type WebhookTenantMatch as W, type CorsairWebhookHandler as X, type CorsairWebhookMatcher as Y, type CorsairWebhookTenantMatcher as Z, type CorsairWorkflowsNamespace as _, type CorsairPermissionsOptions as a, type CorsairManageNamespace as a$, type EndpointHooks as a0, type EndpointJob as a1, type EndpointMetaEntry as a2, type EndpointPathsOf as a3, type EndpointTree as a4, type EnforcePermissionOptions as a5, type EnforcePermissionResult as a6, type ErrorContext as a7, type ErrorHandler as a8, type ErrorHandlerAndMatchFunction as a9, type WebhookTree as aA, type WorkflowRun as aB, type WorkflowRunStatus as aC, type WorkflowRunStep as aD, type WorkflowStatus as aE, type WorkflowSummary as aF, activeMode as aG, assertModeAllows as aH, assertReadonlyAllowed as aI, exchangeCodeForTokens as aJ, formatProviderDisplayName as aK, isReadonlyScopeActive as aL, runReadonly as aM, runWithMode as aN, type ManagementOk as aO, type Tenant as aP, type CreateTenantInput as aQ, type PluginInfo as aR, type ConnectionStatus as aS, type PermissionLookupInput as aT, type PermissionRecord as aU, type CreateConnectLinkInput as aV, type ConnectLink as aW, type ResolvedConnectLink as aX, type OAuthCallbackInput as aY, type OAuthCallbackResult as aZ, type ConnectRequest as a_, type ErrorMatcher as aa, type IntegrationFieldNames as ab, type KeyBuilderContext as ac, type ModeScope as ad, type OAuth2IntegrationCredentials as ae, type PermissionMode as af, type PermissionPolicy as ag, type PickAuth as ah, type PluginAuthConfig as ai, type PluginEndpointMeta as aj, type PluginPermissionsConfig as ak, ProviderDisplayNames as al, type RawWebhookRequest as am, ReadonlyForbiddenError as an, type RequiredPluginEndpointMeta as ao, type RequiredPluginEndpointSchemas as ap, type RequiredPluginWebhookSchemas as aq, type RetryStrategies as ar, type RetryStrategy as as, type TokenResponse as at, type TriggerRunResult as au, type UnionToIntersection$1 as av, type WebhookHooks as aw, type WebhookPathsOf as ax, type WebhookRequest as ay, type WebhookResponse as az, type CorsairManualConfig as b, type PluginConnectionState as b0, type WithTenantOptions as b1, type HubOAuthMode as b2, type HubConnectSessionResult as b3, type HubPermissionSessionResult as b4, type HubConfigInput as b5, type HubConnectSessionInput as b6, type HubListProjectConnectionsInput as b7, type HubPermissionSessionInput as b8, DEFAULT_HUB_API_URL as b9, type HubEnvironmentSlug as ba, type CorsairIntegration as c, type CorsairTenantWrapper as d, type CorsairSingleTenantClient as e, type AccountKeyManagerFor as f, type CorsairPluginSubscribeResult as g, type Account as h, type AccountFieldNames as i, type AccountModes as j, AccountSelectionError as k, type AgentMessageRole as l, type AgentReply as m, type AllProviders as n, type BaseAuthFieldConfig as o, type BaseKeyManager as p, BaseProviders as q, type BeforeHookResult as r, type BindEndpoints as s, type BindWebhooks as t, type Bivariant$2 as u, type BoundEndpointFn as v, type BoundEndpointTree as w, type BoundWebhook as x, type BoundWebhookTree as y, type ChatHandle as z };
@@ -1,4 +1,4 @@
1
- import { W as WebhookTenantMatch, A as AuthTypes } from './index-DfwzI6WA.js';
1
+ import { W as WebhookTenantMatch, A as AuthTypes } from './index-CVBmlS4w.js';
2
2
  import { CorsairDatabase, CorsairAccount } from './db.js';
3
3
 
4
4
  /**
@@ -140,6 +140,11 @@ type BrowserDeliveryPayload = {
140
140
  authType?: 'managed' | 'oauth_2';
141
141
  /** Provider token-body identity (team, workspace_id, …) for the SDK resolver. */
142
142
  providerData?: Record<string, unknown>;
143
+ /** Provider account identity for multi-account delivery (`deliveryMode: oauth.tokens`). */
144
+ account?: {
145
+ id: string;
146
+ label?: string;
147
+ };
143
148
  /** SDK permission token to approve or deny (`deliveryMode: permission.*`). */
144
149
  permissionToken?: string;
145
150
  /** Hub page origin for iframe postMessage replies (legacy client bridge). */
@@ -165,6 +170,8 @@ declare function setWebhookTenantLink(options: {
165
170
  link: WebhookTenantLink;
166
171
  authType?: AuthTypes;
167
172
  extraAccountFields?: readonly string[];
173
+ accountId?: string;
174
+ accountRef?: string;
168
175
  }): Promise<void>;
169
176
  type ResolveAccountFromWebhookLinkInput = {
170
177
  database: CorsairDatabase;
@@ -172,6 +179,7 @@ type ResolveAccountFromWebhookLinkInput = {
172
179
  pluginId: string;
173
180
  linkType: string;
174
181
  externalId: string;
182
+ tenantId?: string;
175
183
  };
176
184
  /**
177
185
  * Resolves the matching corsair_accounts row for a webhook tenant link.
@@ -248,6 +256,10 @@ type OAuthTokensTunnelPayload = {
248
256
  scope?: string;
249
257
  authType?: 'managed' | 'oauth_2';
250
258
  providerData?: Record<string, unknown>;
259
+ account?: {
260
+ id: string;
261
+ label?: string;
262
+ };
251
263
  };
252
264
  type ProcessCorsairRequest = {
253
265
  headers: Headers | Record<string, string | string[] | undefined>;
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { ZodTypeAny, z } from 'zod';
2
- import { e as CorsairSingleTenantClient, d as CorsairTenantWrapper, C as CorsairPlugin, D as CorsairClient, aK as ManagementOk, aL as Tenant, aM as CreateTenantInput, aN as PluginInfo, aO as ConnectionStatus, aP as PermissionLookupInput, aQ as PermissionRecord, aR as CreateConnectLinkInput, aS as ConnectLink, aT as ResolvedConnectLink, aU as OAuthCallbackInput, aV as OAuthCallbackResult, aW as ConnectRequest, N as CorsairPermissionsNamespace, v as BoundWebhookTree, ai as RawWebhookRequest, V as CorsairWebhookTenantMatcher, n as BaseProviders, av as WebhookResponse } from './index-DfwzI6WA.js';
3
- export { aX as CorsairManageNamespace, b as CorsairManualConfig, a as CorsairPermissionsOptions, aY as PluginConnectionState, aj as ReadonlyForbiddenError, aI as runReadonly, aJ as runWithMode } from './index-DfwzI6WA.js';
4
- import { aD as FormFieldSchema, Z as ListOperationsOptions } from './tenant-match-utils-CyrwBjB5.js';
5
- export { A as AuthMissingError, a as AuthType, C as CloudAccess, b as CloudApiError, c as CloudCatalogIntegration, d as CloudConnectSession, e as CloudConnection, f as CloudDeleted, g as CloudDelivery, h as CloudEmbeddedList, i as CloudInstance, j as CloudInstanceApply, k as CloudInstancePlane, l as CloudInstanceRemoval, m as CloudIntegration, n as CloudIntegrationOperations, o as CloudKey, p as CloudKeyRotation, q as CloudLink, r as CloudLinkLine, s as CloudList, t as CloudMcpToken, u as CloudOauthApp, v as CloudOperation, w as CloudProject, x as CloudProjectPlane, y as CloudSigningSecret, z as CloudSigningSecretRotation, B as CloudTenant, D as CloudWebhook, E as CorsairCloudConfig, F as CorsairCloudInstance, G as CorsairCloudInstanceHandle, H as CorsairCloudManage, I as CorsairCloudRegistry, J as CorsairKekMissingError, K as CreateConnectSessionInput, L as CreateInstanceInput, N as CreateWebhookInput, O as CredentialSource, X as LinkLine, Y as LinkPolicy, _ as ListQuery, $ as ManagementApiError, a0 as MintLinkInput, a1 as MintTokenInput, a2 as Permission, a3 as PermissionDecision, aE as PermissionMode, a4 as PermissionRequiredError, a6 as PluginWebhookMatchers, a7 as ProjectStatus, a8 as PutIntegrationInput, a9 as PutOauthAppInput, aa as ReconnectRequiredError, ab as RequestOptions, ac as ResolveConnectLinkResult, ad as RotateWebhookSecretInput, ae as SetAccessInput, af as UpdateInstanceInput, ag as UpdateLinkInput, ah as UpdateTenantInput, ai as V1Transport, aj as WebhookPluginTenantMatch, ak as asRecord, al as buildInstancePlane, am as buildProjectPlane, an as collectPluginWebhookMatchers, ao as corsairCloud, ap as decodePubSubData, ar as firstString, as as formatDocSchemaShape, at as getHeader, aw as mapV1Error, ax as matchWebhookPlugin, ay as matchWebhookPluginAndTenant, az as readBodyRecord, aB as resolveConnectLink, aC as toExternalId } from './tenant-match-utils-CyrwBjB5.js';
6
- export { c as createCorsair } from './index-CBAM12HG.js';
2
+ import { e as CorsairSingleTenantClient, d as CorsairTenantWrapper, C as CorsairPlugin, J as CorsairClient, aO as ManagementOk, aP as Tenant, aQ as CreateTenantInput, aR as PluginInfo, aS as ConnectionStatus, aT as PermissionLookupInput, aU as PermissionRecord, aV as CreateConnectLinkInput, aW as ConnectLink, aX as ResolvedConnectLink, aY as OAuthCallbackInput, aZ as OAuthCallbackResult, a_ as ConnectRequest, R as CorsairPermissionsNamespace, y as BoundWebhookTree, am as RawWebhookRequest, Z as CorsairWebhookTenantMatcher, q as BaseProviders, az as WebhookResponse } from './index-CVBmlS4w.js';
3
+ export { a$ as CorsairManageNamespace, b as CorsairManualConfig, a as CorsairPermissionsOptions, b0 as PluginConnectionState, an as ReadonlyForbiddenError, aM as runReadonly, aN as runWithMode } from './index-CVBmlS4w.js';
4
+ import { aD as FormFieldSchema, Z as ListOperationsOptions } from './tenant-match-utils-BiOexLyr.js';
5
+ export { A as AuthMissingError, a as AuthType, C as CloudAccess, b as CloudApiError, c as CloudCatalogIntegration, d as CloudConnectSession, e as CloudConnection, f as CloudDeleted, g as CloudDelivery, h as CloudEmbeddedList, i as CloudInstance, j as CloudInstanceApply, k as CloudInstancePlane, l as CloudInstanceRemoval, m as CloudIntegration, n as CloudIntegrationOperations, o as CloudKey, p as CloudKeyRotation, q as CloudLink, r as CloudLinkLine, s as CloudList, t as CloudMcpToken, u as CloudOauthApp, v as CloudOperation, w as CloudProject, x as CloudProjectPlane, y as CloudSigningSecret, z as CloudSigningSecretRotation, B as CloudTenant, D as CloudWebhook, E as CorsairCloudConfig, F as CorsairCloudInstance, G as CorsairCloudInstanceHandle, H as CorsairCloudManage, I as CorsairCloudRegistry, J as CorsairKekMissingError, K as CreateConnectSessionInput, L as CreateInstanceInput, N as CreateWebhookInput, O as CredentialSource, X as LinkLine, Y as LinkPolicy, _ as ListQuery, $ as ManagementApiError, a0 as MintLinkInput, a1 as MintTokenInput, a2 as Permission, a3 as PermissionDecision, aE as PermissionMode, a4 as PermissionRequiredError, a6 as PluginWebhookMatchers, a7 as ProjectStatus, a8 as PutIntegrationInput, a9 as PutOauthAppInput, aa as ReconnectRequiredError, ab as RequestOptions, ac as ResolveConnectLinkResult, ad as RotateWebhookSecretInput, ae as SetAccessInput, af as UpdateInstanceInput, ag as UpdateLinkInput, ah as UpdateTenantInput, ai as V1Transport, aj as WebhookPluginTenantMatch, ak as asRecord, al as buildInstancePlane, am as buildProjectPlane, an as collectPluginWebhookMatchers, ao as corsairCloud, ap as decodePubSubData, ar as firstString, as as formatDocSchemaShape, at as getHeader, aw as mapV1Error, ax as matchWebhookPlugin, ay as matchWebhookPluginAndTenant, az as readBodyRecord, aB as resolveConnectLink, aC as toExternalId } from './tenant-match-utils-BiOexLyr.js';
6
+ export { c as createCorsair } from './index-B5PVm2FS.js';
7
7
  export { SetupCorsairOptions, setupCorsair } from './setup.js';
8
- export { O as OAuthCallbackTunnelPayload, b as ProcessCorsairOptions, c as ProcessCorsairRequest, l as ResolveAccountFromWebhookLinkInput, T as TunnelAck, g as TunnelEnvelope, h as TunnelType, m as WebhookTenantLink, W as WebhookTunnelPayload, p as processCorsair, r as resolveAccountFromWebhookLink, j as resolveTenantFromWebhookLink, k as resolveTenantIdFromWebhookLink, s as setWebhookTenantLink } from './index-uHFiiaZb.js';
8
+ export { O as OAuthCallbackTunnelPayload, b as ProcessCorsairOptions, c as ProcessCorsairRequest, l as ResolveAccountFromWebhookLinkInput, T as TunnelAck, g as TunnelEnvelope, h as TunnelType, m as WebhookTenantLink, W as WebhookTunnelPayload, p as processCorsair, r as resolveAccountFromWebhookLink, j as resolveTenantFromWebhookLink, k as resolveTenantIdFromWebhookLink, s as setWebhookTenantLink } from './index-Cnk2Dmi2.js';
9
9
  import './db.js';
10
10
  import 'kysely';
11
11
  import 'pg';
@@ -518,7 +518,9 @@ type PluginWithWebhooks = {
518
518
  * The corsair instance type - a record of plugin namespaces.
519
519
  */
520
520
  type CorsairInstance = Record<string, PluginWithWebhooks | undefined> & {
521
- withTenant?: (tenantId: string) => CorsairInstance;
521
+ withTenant?: (tenantId: string, options?: {
522
+ accounts?: Record<string, string | undefined>;
523
+ }) => CorsairInstance;
522
524
  };
523
525
  /**
524
526
  * Filters an incoming webhook request through all plugins in a corsair instance.
@@ -560,6 +562,8 @@ declare function processWebhook(corsair: CorsairInstance, headers: WebhookHeader
560
562
  plugin?: string;
561
563
  /** Hub already verified the provider signature; skip app-side re-verify. */
562
564
  hubVerified?: boolean;
565
+ /** The account row the delivery matched; the handler runs as it. */
566
+ accountId?: string;
563
567
  }): Promise<WebhookFilterResult>;
564
568
 
565
569
  export { type AnyCorsairInstance, type BuildCorsairToolsOptions, ConnectLink, ConnectionStatus, CorsairClientError, type CorsairClientOptions, type CorsairManagementClient, type CorsairOperationTool, CreateConnectLinkInput, CreateTenantInput, DEFAULT_BODY_STALL_TIMEOUT_MS, DEFAULT_MAX_BODY_BYTES, type ExpressHandler, type FastifyHandler, FormFieldSchema, type HonoHandler, ListOperationsOptions, type ManagementHandlerOptions, ManagementOk, type NodeHandler, type NodeLikeRequest, type NodeLikeResponse, OAuthCallbackInput, OAuthCallbackResult, type PermissionExecuteResult, PermissionLookupInput, PermissionRecord, PluginInfo, ResolvedConnectLink, Tenant, buildCorsairTools, createCorsairClient, executePermission, formFieldToZod, getInputSchema, getSchema, getStructuredSchema, listOperations, managementHandler, processWebhook, registerCorsairRawBodyParser, resolveBodyStallTimeoutMs, resolveMaxBodyBytes, toAstroHandler, toExpressHandler, toFastifyHandler, toHonoHandler, toNextJsHandler, toNodeHandler, toNuxtHandler, toRemixHandler, toSvelteKitHandler, toTanStackHandler, toWebHandler };