corsair 0.1.78 → 0.1.79
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-6D4UDUPJ.js +1 -0
- package/dist/chunk-T3RG3J3R.js +30 -0
- package/dist/core.d.ts +5 -5
- package/dist/core.js +1 -1
- package/dist/hub.d.ts +41 -17
- package/dist/hub.js +1 -1
- package/dist/{index-mZfhN-6e.d.ts → index-B06cXWWA.d.ts} +2 -2
- package/dist/{index-aVkEGoHG.d.ts → index-D9gndzCb.d.ts} +1 -0
- package/dist/{index-BHyMcpwm.d.ts → index-DXZWwzui.d.ts} +1 -1
- package/dist/index.d.ts +8 -8
- package/dist/index.js +2 -2
- package/dist/oauth.js +1 -1
- package/dist/orm.js +1 -1
- package/dist/setup.d.ts +3 -3
- package/dist/setup.js +1 -1
- package/dist/{tenant-links-UNTSO7K7.d.ts → tenant-links-CN6FYmyf.d.ts} +2 -2
- package/dist/{tenant-match-utils-DXoUP9o9.d.ts → tenant-match-utils-CAvC74W2.d.ts} +2 -2
- package/dist/tunnel.d.ts +4 -4
- package/dist/tunnel.js +1 -1
- package/dist/{types-B1We8TTP.d.ts → types-CqV508wD.d.ts} +49 -44
- package/package.json +1 -1
- package/dist/chunk-3X6WVI5I.js +0 -1
- package/dist/chunk-J6HIPZAR.js +0 -26
- package/dist/chunk-KLJBBN2T.js +0 -5
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as F,c as D,d as P,e as B}from"./chunk-IGGCNGU2.js";var R={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"]}};function L(e,t){if(!e||typeof e!="object")return;let r=e[t];return typeof r=="function"?(...n)=>Reflect.apply(r,e,n):void 0}import{Kysely as J}from"kysely";var H=Symbol.for("corsair:internal"),x=class extends Error{constructor(t="Invalid corsair instance"){super(t),this.name="InvalidCorsairInstanceError"}};function I(e){return typeof e=="object"&&e!==null}function S(e){return!I(e)||!Array.isArray(e.plugins)||typeof e.kek!="string"||typeof e.multiTenancy!="boolean"?!1:e.database===void 0?!0:I(e.database)?e.database.db instanceof J:!1}function O(e){if(!e||typeof e!="object")return;let r=Object.getOwnPropertyDescriptor(e,H)?.value;return S(r)?r:void 0}function G(e,t){let r=O(e);if(!r)throw t?.()??new x;return r}function v(e,t){return e.plugins.find(r=>r.id===t)}function X(e,t,r){let n=v(e,t);if(!n)throw r(`Plugin '${t}' not found`);return n}function Y(e){return"withTenant"in e&&typeof e.withTenant=="function"}import{v7 as q}from"uuid";function T(){return q()}function N(e){return e==="oauth_2"||e==="api_key"||e==="bot_token"}function V(e){let t=e.options?.authType;return N(t)?t:void 0}function ee(e,t){let r=e.authConfig,n=R[t].account,i=r?.[t]?.account??[];return[...n,...i]}import{z as h}from"zod";import{sql as w}from"kysely";function A(e){return e.replace(/'/g,"''")}function W(e){let t=A(e);return w`data->>'${w.raw(t)}'`}function j(e){let t=A(e);return w`(data->>'${w.raw(t)}')::numeric`}function K(e){let t=A(e);return w`(data->>'${w.raw(t)}')::boolean`}function U(e){let t=A(e);return w`(data->>'${w.raw(t)}')::timestamptz`}function te(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function Z(e){let t=e;for(;t;){if(t instanceof h.ZodOptional||t instanceof h.ZodNullable){t=t._def.innerType;continue}if(t instanceof h.ZodDefault){t=t._def.innerType;continue}break}return t}function ne(e){let t=Z(e);if(t instanceof h.ZodString)return"string";if(t instanceof h.ZodNumber)return"number";if(t instanceof h.ZodBoolean)return"boolean";if(t instanceof h.ZodDate)return"date"}function re(e){let t=Z(e);if(!(t instanceof h.ZodObject))return{};let r=t.shape,n={};for(let[i,a]of Object.entries(r)){let u=ne(a);u&&(n[i]=u)}return n}function ie(e,t,r){if(typeof r=="string")return e.where(t,"=",r);if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;"equals"in n&&typeof n.equals=="string"&&(e=e.where(t,"=",n.equals)),"contains"in n&&typeof n.contains=="string"&&(e=e.where(t,"like",`%${n.contains}%`)),"startsWith"in n&&typeof n.startsWith=="string"&&(e=e.where(t,"like",`${n.startsWith}%`)),"endsWith"in n&&typeof n.endsWith=="string"&&(e=e.where(t,"like",`%${n.endsWith}`)),"in"in n&&Array.isArray(n.in)&&(e=e.where(t,"in",n.in))}return e}function oe(e,t,r){if(typeof r=="number")return e.where(t,"=",r);if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;typeof n.equals=="number"&&(e=e.where(t,"=",n.equals)),typeof n.gt=="number"&&(e=e.where(t,">",n.gt)),typeof n.gte=="number"&&(e=e.where(t,">=",n.gte)),typeof n.lt=="number"&&(e=e.where(t,"<",n.lt)),typeof n.lte=="number"&&(e=e.where(t,"<=",n.lte)),Array.isArray(n.in)&&(e=e.where(t,"in",n.in))}return e}function se(e,t,r){if(typeof r=="boolean")return e.where(t,"=",r);if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;typeof n.equals=="boolean"&&(e=e.where(t,"=",n.equals))}return e}function ae(e,t,r){if(r instanceof Date)return e.where(t,"=",r);if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;if(n.equals instanceof Date&&(e=e.where(t,"=",n.equals)),n.before instanceof Date&&(e=e.where(t,"<",n.before)),n.after instanceof Date&&(e=e.where(t,">",n.after)),Array.isArray(n.between)&&n.between.length===2){let[i,a]=n.between;i instanceof Date&&(e=e.where(t,">=",i)),a instanceof Date&&(e=e.where(t,"<=",a))}}return e}function ue(e,t,r,n){return r==="number"?oe(e,j(t),n):r==="boolean"?se(e,K(t),n):r==="date"?ae(e,U(t),n):ie(e,W(t),n)}function ce(e,t,r){if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;return"equals"in n&&(e=e.where(t,"=",n.equals)),"contains"in n&&typeof n.contains=="string"&&(e=e.where(t,"like",`%${n.contains}%`)),"startsWith"in n&&typeof n.startsWith=="string"&&(e=e.where(t,"like",`${n.startsWith}%`)),"endsWith"in n&&typeof n.endsWith=="string"&&(e=e.where(t,"like",`%${n.endsWith}`)),"in"in n&&Array.isArray(n.in)&&(e=e.where(t,"in",n.in)),e}return e.where(t,"=",r)}function de(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function C(e,t,r){return e.selectFrom("corsair_entities").selectAll().where("account_id","=",t).where("entity_type","=",r)}function $(e,t,r,n,i){let a=re(i);function u(o){let y=te(o.data);return{...o,data:i.parse(y)}}return{findByEntityId:async o=>{let y=await t(),d=await C(e,y,r).where("entity_id","=",o).executeTakeFirst();return d?u(d):null},findById:async o=>{let y=await t(),d=await C(e,y,r).where("id","=",o).executeTakeFirst();return d?u(d):null},findManyByEntityIds:async o=>{if(o.length===0)return[];let y=await t();return(await C(e,y,r).where("entity_id","in",o).execute()).map(u)},list:async o=>{let y=await t(),d=C(e,y,r);return typeof o?.limit=="number"&&(d=d.limit(o.limit)),typeof o?.offset=="number"&&(d=d.offset(o.offset)),(await d.execute()).map(u)},search:async o=>{let y=await t(),d=C(e,y,r),c=new Set(["data","limit","offset"]);for(let[l,f]of Object.entries(o))c.has(l)||f===void 0||(d=ce(d,l,f));if(o.data&&typeof o.data=="object")for(let[l,f]of Object.entries(o.data)){if(f===void 0)continue;let g=a[l]??"string";d=ue(d,l,g,f)}return typeof o.limit=="number"&&(d=d.limit(o.limit)),typeof o.offset=="number"&&(d=d.offset(o.offset)),(await d.execute()).map(u)},upsertByEntityId:async(o,y)=>{let d=await t(),c=i.parse(y),s=new Date,l=await C(e,d,r).select("id").where("entity_id","=",o).executeTakeFirst();if(l?.id){await e.updateTable("corsair_entities").set({version:n,data:c,updated_at:s}).where("id","=",l.id).execute();let E=await e.selectFrom("corsair_entities").selectAll().where("id","=",l.id).executeTakeFirst();return u(E)}let f=T();await e.insertInto("corsair_entities").values({id:f,created_at:s,updated_at:s,account_id:d,entity_id:o,entity_type:r,version:n,data:c}).execute();let g=await e.selectFrom("corsair_entities").selectAll().where("id","=",f).executeTakeFirst();return u(g)},deleteById:async o=>{let y=await t(),d=await e.deleteFrom("corsair_entities").where("account_id","=",y).where("entity_type","=",r).where("id","=",o).executeTakeFirst();return Number(d.numDeletedRows)>0},deleteByEntityId:async o=>{let y=await t(),d=await e.deleteFrom("corsair_entities").where("account_id","=",y).where("entity_type","=",r).where("entity_id","=",o).executeTakeFirst();return Number(d.numDeletedRows)>0},count:async()=>{let o=await t(),y=await e.selectFrom("corsair_entities").select(d=>d.fn.countAll().as("count")).where("account_id","=",o).where("entity_type","=",r).executeTakeFirst();return de(y?.count)}}}var le={corsair_integrations:F,corsair_accounts:D,corsair_entities:P,corsair_events:B};function ye(e){return le[e]}function M(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function p(e){if(!e)throw new Error("Corsair database is not configured. Pass `database` to createCorsair(...) to enable ORM.")}function b(e){if(!e)return[];let t=[];for(let r in e){let n=r,i=e[n];if(i!==void 0)if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&!(i instanceof Date)){let a=i;"in"in a&&Array.isArray(a.in)?t.push({field:n,operator:"in",value:a.in}):"like"in a&&typeof a.like=="string"&&t.push({field:n,operator:"like",value:a.like})}else t.push({field:n,value:i})}return t}function m(e,t){if(!t?.length)return e;let r=e;for(let n of t){let i=n.operator??"=";r=r.where(n.field,i,n.value)}return r}function fe(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function k(e,t){let r=ye(t),n=()=>(p(e),e),i=()=>n().db.selectFrom(t),a=()=>n().db.insertInto(t),u=()=>n().db.updateTable(t),o=()=>n().db.deleteFrom(t);function y(c){let s={};for(let[l,f]of Object.entries(c))s[l]=M(f);return r.parse(s)}function d(c){let s={};for(let[l,f]of Object.entries(c))s[l]=M(f);return r.parse(s)}return{findById:async c=>{p(e);let s=i().selectAll();s=m(s,[{field:"id",value:c}]);let l=await s.executeTakeFirst();return l?y(l):null},findOne:async c=>{p(e);let s=i().selectAll();s=m(s,b(c));let l=await s.executeTakeFirst();return l?y(l):null},findMany:async c=>{p(e);let s=i().selectAll();return s=m(s,b(c?.where)),typeof c?.limit=="number"&&(s=s.limit(c.limit)),typeof c?.offset=="number"&&(s=s.offset(c.offset)),(await s.execute()).map(f=>y(f))},create:async c=>{p(e);let s=new Date,l={id:c.id??T(),created_at:s,updated_at:s,...c},f=await a().values(l).returningAll().executeTakeFirst();return f?y(f):d(l)},update:async(c,s)=>{p(e);let l={...s,updated_at:new Date},f=u().set(l).returningAll();f=m(f,[{field:"id",value:c}]);let g=await f.executeTakeFirst();return g?y(g):null},updateMany:async(c,s)=>{p(e);let l={...s,updated_at:new Date},f=i().select("id");f=m(f,b(c));let g=await f.execute();for(let E of g){let _=u().set(l);_=m(_,[{field:"id",value:E.id}]),await _.execute()}return g.length},delete:async c=>{p(e);let s=o();s=m(s,[{field:"id",value:c}]);let l=await s.executeTakeFirst();return Number(l?.numDeletedRows??0)>0},deleteMany:async c=>{p(e);let s=o();s=m(s,b(c));let l=await s.executeTakeFirst();return Number(l?.numDeletedRows??0)},count:async c=>{p(e);let s=i().select(f=>f.fn.countAll().as("count"));s=m(s,b(c));let l=await s.executeTakeFirst();return fe(l?.count)}}}function pe(e){let t=k(e,"corsair_integrations");return{...t,findByName:r=>t.findOne({name:r}),upsertByName:async(r,n)=>{let i=await t.findOne({name:r});return i?await t.update(i.id,n):t.create({...n,name:r})}}}function ge(e){let t=k(e,"corsair_accounts");return{...t,findByTenantAndIntegration:async(r,n)=>{p(e);let i=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();return i?t.findOne({tenant_id:r,integration_id:i.id}):null},listByTenant:(r,n)=>t.findMany({where:{tenant_id:r},limit:n?.limit,offset:n?.offset}),upsertByTenantAndIntegration:async(r,n,i)=>{let a=await t.findOne({tenant_id:r,integration_id:n});return a?await t.update(a.id,i):t.create({...i,tenant_id:r,integration_id:n})}}}function me(e){let t=k(e,"corsair_entities");return{...t,findByEntityId:({accountId:r,entityType:n,entityId:i})=>t.findOne({account_id:r,entity_type:n,entity_id:i}),findManyByEntityIds:async({accountId:r,entityType:n,entityIds:i})=>i.length===0?[]:(p(e),await e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",r).where("entity_type","=",n).where("entity_id","in",i).execute()),listByScope:({accountId:r,entityType:n,limit:i,offset:a})=>t.findMany({where:{account_id:r,entity_type:n},limit:i,offset:a}),searchByEntityId:async({accountId:r,entityType:n,query:i,limit:a,offset:u})=>{p(e);let o=e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",r).where("entity_type","=",n).where("entity_id","like",`%${i}%`);return typeof a=="number"&&(o=o.limit(a)),typeof u=="number"&&(o=o.offset(u)),await o.execute()},upsertByEntityId:async({accountId:r,entityType:n,entityId:i,version:a,data:u})=>{let o=await t.findOne({account_id:r,entity_type:n,entity_id:i});return o?await t.update(o.id,{version:a,data:u}):t.create({account_id:r,entity_type:n,entity_id:i,version:a,data:u})},deleteByEntityId:async({accountId:r,entityType:n,entityId:i})=>{p(e);let a=await e.db.deleteFrom("corsair_entities").where("account_id","=",r).where("entity_type","=",n).where("entity_id","=",i).executeTakeFirst();return Number(a.numDeletedRows)>0}}}function we(e){let t=k(e,"corsair_events");return{...t,listByAccount:(r,n)=>t.findMany({where:{account_id:r},limit:n?.limit,offset:n?.offset}),listByStatus:(r,n)=>{let i={status:r};return n?.accountId&&(i.account_id=n.accountId),t.findMany({where:i,limit:n?.limit,offset:n?.offset})},listPending:r=>{let n={status:"pending"};return r?.accountId&&(n.account_id=r.accountId),t.findMany({where:n,limit:r?.limit??100})},updateStatus:(r,n)=>t.update(r,{status:n})}}function Q(e){return{integrations:pe(e),accounts:ge(e),entities:me(e),events:we(e)}}function he(e,t,r,n,i){let a=null;async function u(){if(a!==null)return a;p(e);let o=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t.integrationName).executeTakeFirst();if(!o)throw new Error(`Integration "${t.integrationName}" not found. Make sure to create the integration first.`);let y=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t.tenantId).where("integration_id","=",o.id).executeTakeFirst();if(!y)throw new Error(`Account not found for tenant "${t.tenantId}" and integration "${t.integrationName}". Make sure to create the account first.`);return a=y.id,a}return p(e),$(e.db,u,r,n,i)}function z(e){let{database:t,integrationName:r,schema:n,tenantId:i}=e,a=Q(t),u={tenantId:i,integrationName:r},o=null;async function y(){if(o!==null)return o;p(t);let c=await t.db.selectFrom("corsair_integrations").selectAll().where("name","=",r).executeTakeFirst();if(!c)throw new Error(`Integration "${r}" not found. Make sure to create the integration first.`);let s=await t.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",i).where("integration_id","=",c.id).executeTakeFirst();if(!s)throw new Error(`Account not found for tenant "${i}" and integration "${r}". Make sure to create the account first.`);return o=s.id,o}let d={};for(let[c,s]of Object.entries(n.entities))d[c]=he(t,u,c,n.version,s);return{...d,$orm:a,$integrationName:r,$tenantId:i,$getAccountId:y}}function $e(e,t){let r=Q(e);return{$tenantId:t,$orm:r,listAccounts:n=>r.accounts.listByTenant(t,n),findAccountByIntegration:n=>r.accounts.findByTenantAndIntegration(t,n),listEntities:async n=>{p(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",t).execute();if(i.length===0)return[];let a=i.map(o=>o.id),u=e.db.selectFrom("corsair_entities").selectAll().where("account_id","in",a);return n?.entityType&&(u=u.where("entity_type","=",n.entityType)),typeof n?.limit=="number"&&(u=u.limit(n.limit)),typeof n?.offset=="number"&&(u=u.offset(n.offset)),await u.execute()},listEvents:async n=>{p(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",t).execute();if(i.length===0)return[];let a=i.map(o=>o.id),u=e.db.selectFrom("corsair_events").selectAll().where("account_id","in",a);return n?.status&&(u=u.where("status","=",n.status)),typeof n?.limit=="number"&&(u=u.limit(n.limit)),typeof n?.offset=="number"&&(u=u.offset(n.offset)),await u.execute()},forIntegration:n=>z({database:e,integrationName:n.integrationName,schema:n.schema,tenantId:t})}}function Me(e,t){return{forTenant:r=>z({database:e,integrationName:t.integrationName,schema:t.schema,tenantId:r})}}export{I as a,O as b,G as c,X as d,Y as e,L as f,R as g,V as h,ee as i,T as j,$ as k,le as l,Q as m,z as n,$e as o,Me as p};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import{a as ie,b as ot,c as P,d as B,e as it,f as z,g as U,h as se,i as Re,j as st,k as kn,l as at,m as ct}from"./chunk-6D4UDUPJ.js";import{a as rt}from"./chunk-IGGCNGU2.js";import*as mr from"querystring";var Fe=["ahrefs","airtable","amplitude","asana","bitwarden","bluesky","box","cal","calendly","cloudflare","cursor","discord","dodopayments","dropbox","exa","figma","firecrawl","fireflies","github","gitlab","gmail","googlecalendar","googledrive","googlesheets","grafana","hackernews","hubspot","intercom","jira","linear","monday","notion","onedrive","openweathermap","oura","outlook","pagerduty","posthog","razorpay","reddit","resend","sentry","sharepoint","slack","spotify","strava","stripe","tally","tavily","teams","telegram","todoist","trello","twilio","twitter","twitterapiio","typeform","vapi","xquik","youtube","zendesk","zohomail","zoom"],ut={ahrefs:"Ahrefs",airtable:"Airtable",amplitude:"Amplitude",asana:"Asana",bitwarden:"Bitwarden",bluesky:"Bluesky",box:"Box",cal:"Cal",calendly:"Calendly",cloudflare:"Cloudflare",cursor:"Cursor",discord:"Discord",dodopayments:"Dodo Payments",dropbox:"Dropbox",exa:"Exa",figma:"Figma",firecrawl:"Firecrawl",fireflies:"Fireflies",github:"GitHub",gitlab:"GitLab",gmail:"Gmail",googlecalendar:"Google Calendar",googledrive:"Google Drive",googlesheets:"Google Sheets",grafana:"Grafana",hackernews:"Hacker News",hubspot:"HubSpot",intercom:"Intercom",jira:"Jira",linear:"Linear",monday:"Monday",notion:"Notion",onedrive:"OneDrive",openweathermap:"OpenWeatherMap",oura:"Oura",outlook:"Outlook",pagerduty:"PagerDuty",posthog:"PostHog",razorpay:"Razorpay",reddit:"Reddit",resend:"Resend",sentry:"Sentry",sharepoint:"SharePoint",slack:"Slack",spotify:"Spotify",strava:"Strava",stripe:"Stripe",tally:"Tally",tavily:"Tavily",teams:"Teams",telegram:"Telegram",todoist:"Todoist",trello:"Trello",twilio:"Twilio",twitter:"Twitter",twitterapiio:"Twitter API IO",typeform:"Typeform",vapi:"Vapi",xquik:"XQuik",youtube:"YouTube",zendesk:"Zendesk",zohomail:"Zoho Mail",zoom:"Zoom"};function ve(e){let n=ut[e];return n||e.charAt(0).toUpperCase()+e.slice(1)}var Ie="https://auth.corsair.dev";var V=class extends Error{constructor(){super("Hub is not configured. Pass hub: { projectApiKey, signingSecret, deliveryUrl } to createCorsair()."),this.name="HubNotConfiguredError"}};function Be(e){let n=(e.apiUrl?.trim()||Ie).replace(/\/$/,""),t=e.projectApiKey.trim(),r=e.signingSecret.trim(),o=e.deliveryUrl.trim();if(!t||!r||!o)throw new Error("Hub config requires non-empty projectApiKey, signingSecret, and deliveryUrl");return{apiUrl:n,projectApiKey:t,signingSecret:r,deliveryUrl:o,oauthCallbackUrl:e.oauthCallbackUrl?.trim()}}function br(e){return e.apiUrl.trim().length>0&&e.deliveryUrl.trim().length>0&&e.projectApiKey.trim().length>0&&e.signingSecret.trim().length>0}function M(e){let n=P(e).hub;if(!n||!br(n))throw new V;return n}function Ue(e){return e.oauthCallbackUrl?e.oauthCallbackUrl:`${e.apiUrl.replace(/\/$/,"")}/oauth/callback`}function N(e){return typeof e=="string"&&e.length>0}function dt(e){if(!e||typeof e!="object")throw new Error("Hub API returned an empty connect session");let n=e;if(!N(n.connectUrl)||!N(n.token)||!N(n.projectId))throw new Error("Hub API returned an incomplete connect session (expected connectUrl, token, and projectId)");let t={connectUrl:n.connectUrl,token:n.token,projectId:n.projectId};return N(n.expiresAt)&&(t.expiresAt=n.expiresAt),t}function lt(e){if(!e||typeof e!="object")throw new Error("Hub API returned an empty permission session");let n=e;if(!N(n.approvalUrl)||!N(n.token)||!N(n.projectId)||!N(n.expiresAt))throw new Error("Hub API returned an incomplete permission session (expected approvalUrl, token, projectId, and expiresAt)");return{approvalUrl:n.approvalUrl,token:n.token,projectId:n.projectId,expiresAt:n.expiresAt}}function pt(e){if(!e||typeof e!="object")throw new Error("Hub token refresh returned an empty response");let n=e;if(!N(n.access_token))throw new Error("Hub token refresh returned no access_token");return{access_token:n.access_token,refresh_token:N(n.refresh_token)?n.refresh_token:void 0,expires_in:typeof n.expires_in=="number"?n.expires_in:void 0,scope:N(n.scope)?n.scope:void 0}}function gt(e){if(!e||typeof e!="object")return null;let n=e;return n.error??n.message??null}function wr(e){return e.replace(/\/$/,"")}async function Cr(e){let n=e.headers.get("content-type")??"",t=await e.text();if(!t)return null;if(!n.includes("application/json")&&t.trimStart().startsWith("<"))throw new Error(`Hub API returned HTML instead of JSON (HTTP ${e.status}). Check HUB_API_URL and deploy the latest hub API.`);try{return JSON.parse(t)}catch{throw new Error(`Hub API returned invalid JSON (HTTP ${e.status})`)}}function Tr(e,n,t){if(n===404&&t)return t;let r=gt(e);return r||`Hub API returned HTTP ${n}`}async function me(e){let n=wr(e.hub.apiUrl),t=await fetch(`${n}${e.path}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.hub.projectApiKey}`},body:JSON.stringify(e.body)}),r=await Cr(t);if(!t.ok)throw new Error(Tr(r,t.status,e.notFoundMessage));return e.parseResponse(r)}import*as Se from"crypto";function J(e,n){return Buffer.from(JSON.stringify({plugin:e,tenantId:n,iat:Date.now()})).toString("base64url")}function bn(e,{maxAgeMs:n}={}){try{let t=e.includes(".")?e.split(".")[0]:e,r=JSON.parse(Buffer.from(t,"base64url").toString("utf-8"));if(r!==null&&typeof r=="object"&&"plugin"in r&&"tenantId"in r&&typeof r.plugin=="string"&&typeof r.tenantId=="string"){let o=r;return n!==void 0&&typeof o.iat=="number"&&Date.now()-o.iat>n?null:o}return null}catch{return null}}function ae(e,n){let t=Se.createHmac("sha256",n).update(e).digest("base64url");return`${e}.${t}`}var Pr=600*1e3;function Ne(e,n){let t=e.lastIndexOf(".");if(t===-1)return null;let r=e.slice(0,t),o=e.slice(t+1),i=Se.createHmac("sha256",n).update(r).digest("base64url"),s=Buffer.from(o,"base64url"),a=Buffer.from(i,"base64url");return s.length!==a.length||!Se.timingSafeEqual(s,a)?null:bn(r,{maxAgeMs:Pr})}var xr=new Set(["localhost","127.0.0.1","[::1]","::1"]);function _e(e){try{let{hostname:n,protocol:t}=new URL(e);return t!=="http:"&&t!=="https:"?!1:xr.has(n)}catch{return!1}}function ke(e){return _e(e)?"client":"server"}function ft(e,n){return e==="client"||_e(n)}function be(e){if(!e.source)return null;let n=_e(e.deliveryUrl);return e.source==="server"&&n?{error:'source "server" cannot be used with a loopback delivery URL \u2014 omit source to auto-detect or use "client"',status:400}:e.oauthMode==="managed"&&e.source==="client"&&!n?{error:'managed OAuth with source "client" requires a loopback delivery URL \u2014 omit source for production server delivery',status:400}:null}import{ZodBoolean as Ar,ZodDate as Rr,ZodEnum as vr,ZodNullable as Ir,ZodNumber as Sr,ZodObject as _r,ZodOptional as Er,ZodRecord as Or,ZodString as Dr,ZodType as Hr}from"zod";var wn={slack:{channels:{list:{}},users:{list:{}}},linear:{projects:{list:{}},issues:{list:{}},users:{list:{}}},github:{issues:{list:{}},repositories:{list:{}}},discord:{guilds:{list:{}},channels:{list:{}}},hubspot:{contacts:{getMany:{}},companies:{getMany:{}},deals:{getMany:{}}},gmail:{messages:{list:{}},labels:{list:{}},drafts:{list:{}},threads:{list:{}}},googlecalendar:{events:{getMany:{}}},googledrive:{files:{list:{}},folders:{list:{}},sharedDrives:{list:{}}},notion:{databases:{getManyDatabases:{}},databasePages:{getManyDatabasePages:{}},users:{getManyUsers:{}}},airtable:{bases:{getMany:{}}},todoist:{projects:{getMany:{}},tasks:{getMany:{}}},cal:{bookings:{list:{}}},zohomail:{folders:{list:{}},messages:{list:{}}}};async function ht(e,n){let t=[],r=g=>{t.push(g),console.log(g)},o=g=>{t.push(g),console.warn(g)},i=n?.caller??"script",s=ot(e);if(!s)throw new Error("setupCorsair: invalid corsair instance");if(!s.database)throw new Error("setupCorsair: a database must be configured on the corsair instance");let a=$r(e,s.plugins,n),c={...s,database:s.database},d=c.database.db;await Ur(d,o);let l=await Nr(d,c,a.tenantId,a.provisionAccounts,r);n?.credentials&&Object.keys(n.credentials).length>0&&await jr(e,a,n.credentials,c,r,o);let u=await Zr(l,a,r,i);if(n?.backfill){r("[corsair:setup] Starting backfill...");let g=kt({plugins:s.plugins,database:d,kek:s.kek,multiTenancy:!0}).withTenant(a.tenantId);await qr(g,s.plugins,u,r,o),r("[corsair:setup] Backfill complete.")}return t.join(`
|
|
2
|
+
`)}function Cn(e,n,t){let r=t==="integration"?e.authConfig?.[n]?.integration??[]:e.authConfig?.[n]?.account??[];return new Set([...U[n][t],...r])}function Mr(e,n){if(!e)return!1;for(let[t,r]of Object.entries(e)){let o=n.find(a=>a.id===t);if(!o)continue;let i=se(o);if(!i)continue;let s=Cn(o,i,"account");for(let a of Object.keys(r))if(s.has(a))return!0}return!1}function $r(e,n,t){let r=it(e),o=t?.tenantId?.trim(),i=o!==void 0&&o.length>0;if(r&&t?.backfill&&!i)throw new Error("setupCorsair: tenantId is required for backfill on a multi-tenant instance");if(r&&Mr(t?.credentials,n)&&!i)throw new Error("setupCorsair: tenantId is required when setting account-level credentials on a multi-tenant instance");if(i&&!o)throw new Error("setupCorsair: tenantId must be a non-empty string");return{multiTenant:r,tenantIdProvided:i,tenantId:i?o:"default",provisionAccounts:!r||i}}function mt(e,n){return ie(e)?n===0?!0:Object.values(e).every(t=>mt(t,n-1)):!1}function Fr(e){return mt(e,4)}var Br={...at};function We(e){if(e instanceof _r){let n={};for(let[t,r]of Object.entries(e.shape))n[t]=r instanceof Hr?We(r):"unknown";return n}return e instanceof Ir?`${We(e.unwrap())} | null`:e instanceof Er?`${We(e.unwrap())} | undefined`:e instanceof vr?e.options.join(" | "):e instanceof Dr?"string":e instanceof Sr?"number":e instanceof Ar?"boolean":e instanceof Rr?"date":e instanceof Or?"jsonb":"unknown"}async function Ur(e,n){let t=await e.introspection.getTables(),r=new Set(t.map(o=>o.name));for(let[o,i]of Object.entries(Br))r.has(o)||n(`[corsair:setup] Table "${o}" does not exist. Run your database migrations before calling setupCorsair.
|
|
3
|
+
Schema: ${JSON.stringify(We(i),null,2)}`)}async function Nr(e,n,t,r,o){let i=new Date,s=new Map;for(let a of n.plugins){let c=a.id,d=se(a),l=await e.selectFrom("corsair_integrations").selectAll().where("name","=",c).executeTakeFirst();if(!l){let f=crypto.randomUUID();await e.insertInto("corsair_integrations").values({id:f,name:c,config:{},created_at:i,updated_at:i}).execute(),l=await e.selectFrom("corsair_integrations").selectAll().where("id","=",f).executeTakeFirst(),o(`[corsair:setup] Created integration: ${c}`)}let u=d?a.authConfig?.[d]?.integration??[]:[],g=d?a.authConfig?.[d]?.account??[]:[],y=d&&l?D({authType:d,integrationName:c,kek:n.kek,database:n.database,extraIntegrationFields:u}):void 0;if(l&&!l.dek&&y&&(await y.issue_new_dek(),o(`[corsair:setup] Issued integration DEK: ${c}`)),!l||!d||!y)continue;let p;if(r){let f=await e.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t).where("integration_id","=",l.id).executeTakeFirst();if(!f){let h=crypto.randomUUID();await e.insertInto("corsair_accounts").values({id:h,tenant_id:t,integration_id:l.id,config:{},created_at:i,updated_at:i}).execute(),f=await e.selectFrom("corsair_accounts").selectAll().where("id","=",h).executeTakeFirst(),o(`[corsair:setup] Created account: ${c}`)}p=f&&I({authType:d,integrationName:c,tenantId:t,kek:n.kek,database:n.database,extraAccountFields:g}),f&&p&&!f.dek&&(await p.issue_new_dek(),o(`[corsair:setup] Issued account DEK: ${c}`))}s.set(c,{pluginId:c,authType:d,integration:y,account:p,integrationFields:[...U[d].integration,...u],accountFields:r?[...U[d].account,...g]:[]})}return s}function Wr(e){if(!ie(e))return;let n=e.keys;return ie(n)?n:void 0}function Lr(e,n){return"withTenant"in e&&typeof e.withTenant=="function"?e.withTenant(n):e}async function jr(e,n,t,r,o,i){let s=Wr(e),a=n.provisionAccounts?Lr(e,n.tenantId):void 0;for(let[c,d]of Object.entries(t)){let l=r.plugins.find(m=>m.id===c);if(!l){i(`[corsair:setup] Unknown plugin '${c}' \u2014 skipping credentials.`);continue}let u=se(l);if(!u){i(`[corsair:setup] Plugin '${c}' has no auth type \u2014 skipping credentials.`);continue}let g=Cn(l,u,"integration"),y=Cn(l,u,"account"),p=s?.[c],f=a?.[c],h=ie(f)?f.keys:void 0;for(let[m,C]of Object.entries(d))if(C){if(g.has(m)){if(n.multiTenant&&n.tenantIdProvided)throw new Error(`[corsair:setup] '${c}.${m}' is an integration-level credential shared across all tenants. You passed tenantId="${n.tenantId}", which only scopes account-level credentials. Run setup without --tenant if you intend to change this credential globally.`);let b=z(p,`set_${m}`);if(!b){i(`[corsair:setup] Cannot set integration field '${m}' for '${c}'.`);continue}await b(C),o(`[corsair:setup] Set ${c} integration.${m}`);continue}if(y.has(m)){if(n.multiTenant&&!n.tenantIdProvided)throw new Error(`setupCorsair: tenantId is required to set account-level credential '${c}.${m}' on a multi-tenant instance`);let b=z(h,`set_${m}`);if(!b){i(`[corsair:setup] Cannot set account field '${m}' for '${c}'.`);continue}await b(C),o(`[corsair:setup] Set ${c} account.${m} (tenant=${n.tenantId})`);continue}i(`[corsair:setup] Unknown credential field '${m}' for plugin '${c}'.`)}}}var yt=new Set(["webhook_signature","expires_at","scope","redirect_url"]);async function Kr(e,n,t,r,o,i,s,a,c){let d=[],l=[];for(let g of o){if(yt.has(g))continue;let y=z(t,`get_${g}`);if(!y)continue;let p=null;try{let f=await y();p=typeof f=="string"?f:null}catch{}p||d.push(g)}if(r&&i.length>0)for(let g of i){if(yt.has(g))continue;let y=z(r,`get_${g}`);if(!y)continue;let p=null;try{let f=await y();p=typeof f=="string"?f:null}catch{}p||l.push(g)}let u=d.length===0&&l.length===0;if(u)a(`[corsair:setup] '${e}' (${n}) is configured \u2713`);else{let g=[...d,...l];if(c==="cli"){let y=g.map(p=>`${p}=VALUE`).join(" ");a(`[corsair:setup] '${e}' (${n}) needs credentials. Run:
|
|
4
|
+
corsair setup --${e} ${y}`)}else{let y=[`[corsair:setup] '${e}' (${n}) needs credentials. Call:`];for(let p of d)y.push(` await corsair.keys.${e}.set_${p}(value)`);for(let p of l){let f=s.provisionAccounts?s.tenantId==="default"?`corsair.${e}`:`corsair.withTenant(${JSON.stringify(s.tenantId)}).${e}`:`corsair.withTenant(<tenant>).${e}`;y.push(` await ${f}.keys.set_${p}(value)`)}a(y.join(`
|
|
5
|
+
`))}}return u}async function Zr(e,n,t,r){let o=new Set;for(let i of e.values())await Kr(i.pluginId,i.authType,i.integration,i.account,i.integrationFields,i.accountFields,n,t,r)&&o.add(i.pluginId);return o}async function qr(e,n,t,r,o){if(!Fr(wn)){o("[corsair:setup] Backfill config is invalid - skipping backfill.");return}let i=wn,s=new Set(n.map(a=>a.id));for(let[a,c]of Object.entries(i)){if(!s.has(a))continue;if(!t.has(a)){r(`[corsair:setup] Skipping backfill for '${a}' \u2014 auth not configured.`);continue}let d=ie(e)?e[a]:void 0,l=ie(d)?d.api:void 0;if(l)for(let[u,g]of Object.entries(c))for(let[y,p]of Object.entries(g)){r(`[corsair:setup] Backfilling ${a} \u203A ${u}.${y}...`);try{let f=ie(l)?l[u]:void 0;await z(f,y)?.(p)}catch(f){o(`[corsair:setup] ${a} \u203A ${u}.${y} failed: `+(f instanceof Error?f.message:String(f)))}}}}async function we(e,n){if(!P(e).database)throw new Error("A database must be configured to provision Corsair for connect");await ht(e,{tenantId:n})}var bt=new Set(["webhook_signature","expires_at","scope"]);function Gr(e){return e==="oauth_2"||e==="managed"?"oauth":e==="bot_token"?"bot_token":"api_key"}async function zr(e,n,t,r){let o=Re(n,t).filter(c=>!bt.has(c));if(o.length===0)return!0;let s=(typeof e.withTenant=="function"?e.withTenant(r):e)[n.id],a=s&&typeof s=="object"&&"keys"in s?s.keys:null;if(!a)return!1;for(let c of o){if((t==="oauth_2"||t==="managed")&&c==="refresh_token")continue;let d=z(a,`get_${c}`);if(!d)continue;let l=null;try{let u=await d();l=typeof u=="string"?u:null}catch{l=null}if(!l)return!1}return!0}function Jr(e,n){return e==="oauth_2"||e==="managed"?[]:n.filter(t=>!bt.has(t))}async function wt(e,n,t={}){let r=P(e),o=M(e),i=Ue(o),s=[],a=t.pluginIds?new Set(t.pluginIds):null;for(let c of r.plugins){if(a&&!a.has(c.id))continue;let d=se(c);if(!d)continue;let l=Gr(d),u=ve(c.id),g=await zr(e,c,d,n),y=Re(c,d),p={plugin:c.id,providerName:u,authKind:l,alreadyConfigured:g};if(l==="oauth"){let h=t.oauthModeOverrides?.[c.id]??(d==="managed"?"managed":"byo");if(p.oauthMode=h,!g)if(h==="managed")p.state=ae(J(c.id,n),r.kek);else try{let m=await Tn(e,c.id,{tenantId:n,redirectUri:i});p.oauthUrl=m.url,p.state=m.state}catch{continue}}else{let f=Jr(d,y);f.length>0&&(p.credentialFields=f)}s.push(p)}return s}function Ct(e,n){let t=M(e);if(n){let r=be({source:n,deliveryUrl:t.deliveryUrl});if(r)throw new Error(r.error);return n}return ke(t.deliveryUrl)}async function Tt(e,n){await we(e,n)}async function Le(e,n){let t=M(e);await Tt(e,n.tenantId);let r=n.plugin?[n.plugin]:void 0,o=n.plugin&&n.oauthMode?{[n.plugin]:n.oauthMode}:void 0,i=await wt(e,n.tenantId,{pluginIds:r,oauthModeOverrides:o});if(i.length===0)throw new Error(n.plugin?`Plugin '${n.plugin}' is not configured on this Corsair instance`:"No plugins are configured on this Corsair instance");if(i.filter(c=>!c.alreadyConfigured).length===0)throw new Error(n.plugin?`Plugin '${n.plugin}' is already configured for this tenant`:"All plugins are already configured for this tenant");let a=Ct(e,n.source);return me({hub:t,path:"/connect/sessions",notFoundMessage:"Hub REST API not found at /connect/sessions. Check HUB_API_URL and ensure the Hub API is deployed.",body:{tenantId:n.tenantId,deliveryUrl:t.deliveryUrl,source:a,plugins:i},parseResponse:dt})}function Vr(e){if(e==="byo"||e==="managed")return e}function Yr(e){if(e==="client"||e==="server")return e}function Pn(e){let n=e.plugin?.trim(),t=e.tenantId?.trim()||"default",r=Yr(e.source),o=Vr(e.oauthMode),i=e.providerName?.trim();if(e.source!==void 0&&e.source!==null&&String(e.source).trim()!==""&&!r)return{error:'source must be "client" or "server"',status:400};if(e.oauthMode&&!o)return{error:'oauthMode must be "byo" or "managed"',status:400};let s={tenantId:t,oauthMode:o};return n&&(s.plugin=n),r&&(s.source=r),i&&(s.providerName=i),s}function xn(e){let{searchParams:n}=new URL(e),t=n.get("oauthMode");return{plugin:n.get("plugin")??void 0,tenantId:n.get("tenantId")??void 0,source:n.get("source")??void 0,oauthMode:t??void 0,providerName:n.get("providerName")??void 0}}function Qr(e){return{ok:!0,connectUrl:e.connectUrl,token:e.token,projectId:e.projectId,expiresAt:e.expiresAt}}async function Xr(e,n,t){if(t?.resolveTenantId){let r=await t.resolveTenantId(e);return r?.trim()?r.trim():{error:"Unauthorized",status:401}}return n.tenantId?.trim()||t?.defaultTenantId?.trim()||"default"}async function An(e,n,t){let o=n.method.toUpperCase()==="GET"?xn(n.url):await n.json().catch(()=>null);if(!o)return{error:"Invalid JSON body",status:400};let i=await Xr(n,o,t);if(typeof i!="string")return i;let s=Pn({...o,tenantId:i});if("error"in s)return s;let a=M(e);if(s.source){let l=be({source:s.source,deliveryUrl:a.deliveryUrl,oauthMode:s.oauthMode});if(l)return l}let c={...s,source:s.source??ke(a.deliveryUrl)},d=await Le(e,c);return Qr(d)}async function Rn(e,n,t){try{let r=await An(e,n,t);return"error"in r?Response.json({error:r.error},{status:r.status}):Response.json(r)}catch(r){if(r instanceof V)return Response.json({error:r.message},{status:503});let o=r instanceof Error?r.message:String(r);return Response.json({error:o},{status:500})}}async function je(e,n,t){let r=n.method.toUpperCase();return r!=="GET"&&r!=="POST"?Response.json({error:"Method not allowed"},{status:405}):Rn(e,n,t)}var Y=class extends Error{code;constructor(n,t){super(t),this.name="AuthCredentialsDeliveryError",this.code=n}};async function Pt(e,n){let t=P(e,()=>new Y("invalid_corsair_instance","Invalid corsair instance"));if(!t.database)throw new Y("no_database","Database not configured");let r=B(t,n.plugin,d=>new Y("plugin_not_found",d)),o=se(r);if(!o)throw new Y("invalid_credentials",`Plugin '${r.id}' has no authType configured`);if(o==="oauth_2"||o==="managed")throw new Y("invalid_credentials","OAuth plugins must be connected via sign-in, not credentials delivery");await we(e,n.tenantId);let i=new Set(Re(r,o)),a=r.authConfig?.[o]?.account??[],c=I({authType:o,integrationName:n.plugin,tenantId:n.tenantId,kek:t.kek,database:t.database,extraAccountFields:a});for(let[d,l]of Object.entries(n.credentials)){if(!l.trim())continue;if(!i.has(d))throw new Y("invalid_credentials",`Unknown credential field '${d}' for plugin '${n.plugin}'`);let u=z(c,`set_${d}`);if(!u)throw new Y("invalid_credentials",`Cannot set credential field '${d}' for plugin '${n.plugin}'`);await u(l.trim())}return{plugin:n.plugin,tenantId:n.tenantId}}async function Ke(e,n,t){for(let r of e){if(r.id!==n)continue;let o=r.oauthWebhookTenantLinkResolver;return o?o(t):null}return null}import{createCipheriv as xt,createDecipheriv as At,randomBytes as Ze,scrypt as eo}from"crypto";import{promisify as no}from"util";var Rt=no(eo),qe="aes-256-gcm",vt=12,Ge=16,to=16,Ee=32;function Q(){return Ze(Ee).toString("base64")}async function X(e,n){let t=Ze(to),r=await Rt(n,t,Ee),o=Ze(vt),i=xt(qe,r,o,{authTagLength:Ge}),s=Buffer.concat([i.update(e,"utf8"),i.final()]),a=i.getAuthTag();return[t.toString("base64"),o.toString("base64"),a.toString("base64"),s.toString("base64")].join(":")}async function W(e,n){let[t,r,o,i]=e.split(":");if(!t||!r||!o||!i)throw new Error("Invalid encrypted DEK format");let s=Buffer.from(t,"base64"),a=Buffer.from(r,"base64"),c=Buffer.from(o,"base64"),d=Buffer.from(i,"base64"),l=await Rt(n,s,Ee),u=At(qe,l,a,{authTagLength:Ge});return u.setAuthTag(c),Buffer.concat([u.update(d),u.final()]).toString("utf8")}function vn(e,n){let t=Buffer.from(n,"base64"),r=Ze(vt),o=xt(qe,t,r,{authTagLength:Ge}),i=Buffer.concat([o.update(e,"utf8"),o.final()]),s=o.getAuthTag();return[r.toString("base64"),s.toString("base64"),i.toString("base64")].join(":")}function Oe(e,n){let[t,r,o]=e.split(":");if(!t||!r||!o)throw new Error("Invalid encrypted data format");let i=Buffer.from(n,"base64"),s=Buffer.from(t,"base64"),a=Buffer.from(r,"base64"),c=Buffer.from(o,"base64"),d=At(qe,i,s,{authTagLength:Ge});return d.setAuthTag(a),Buffer.concat([d.update(c),d.final()]).toString("utf8")}function ce(e,n){let t={};for(let[r,o]of Object.entries(e))t[r]=vn(o,n);return t}function ee(e,n){let t={};for(let[r,o]of Object.entries(e))t[r]=Oe(o,n);return t}function De(e,n,t){let r=ee(e,n);return ce(r,t)}function It(e,n,t){let r={};for(let o of t)r[`get_${o}`]=async()=>(await e())[o]??null,r[`set_${o}`]=async i=>{let s=[null,void 0,""].includes(i)?null:i;await n({[o]:s})};return r}var In=e=>{if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e};function D(e){let{authType:n,integrationName:t,kek:r,database:o,extraIntegrationFields:i=[]}=e,s=[...U[n].integration,...i],a=null,c={kek:r,integrationName:t,getIntegration:async()=>{if(a)return a;let p=await o.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!p)throw new Error(`Integration "${t}" not found. Make sure to create the integration first.`);return a={id:p.id,config:In(p.config),dek:p.dek??null},a},updateIntegration:async p=>{let f=await c.getIntegration();await o.db.updateTable("corsair_integrations").set({...p.config!==void 0?{config:p.config}:{},...p.dek!==void 0?{dek:p.dek}:{},updated_at:new Date}).where("id","=",f.id).execute(),a=null}},d=null,l=async()=>{if(d)return d;let p=await c.getIntegration();if(!p.dek)throw new Error(`No DEK found for integration "${t}". Initialize the integration first.`);return d=await W(p.dek,r),d},u=async()=>{let p=await c.getIntegration(),f=await l(),h=p.config;return!h||Object.keys(h).length===0?{}:ee(h,f)};return{get_dek:l,issue_new_dek:async()=>{let p=await c.getIntegration(),f=Q(),h={};if(p.dek){let C=await W(p.dek,r),b=p.config;b&&Object.keys(b).length>0&&(h=De(b,C,f))}let m=await X(f,r);return await c.updateIntegration({config:h,dek:m}),d=f,f},...It(u,async p=>{let f=await l(),h;try{h=await u()}catch(b){console.error(`[corsair] Failed to decrypt config for integration "${t}", starting fresh:`,b),h={}}let m={...h};for(let[b,k]of Object.entries(p))k===null?delete m[b]:m[b]=k;let C=ce(m,f);await c.updateIntegration({config:C})},s)}}function I(e){let{authType:n,integrationName:t,tenantId:r,kek:o,database:i,extraAccountFields:s=[]}=e,a=[...U[n].account,...s],c=null,d=null,l=async()=>{if(d)return d;let k=await i.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!k)throw new Error(`Integration "${t}" not found. Make sure to create the integration first.`);return d={id:k.id,config:In(k.config),dek:k.dek??null},d},u={kek:o,integrationName:t,tenantId:r,getIntegration:l,getAccount:async()=>{if(c)return c;let k=await l(),w=await i.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",r).where("integration_id","=",k.id).executeTakeFirst();if(!w)throw new Error(`Account not found for tenant "${r}" and integration "${t}". Make sure to create the account first.`);return c={id:w.id,config:In(w.config),dek:w.dek??null},c},updateAccount:async k=>{let w=await u.getAccount();await i.db.updateTable("corsair_accounts").set({...k.config!==void 0?{config:k.config}:{},...k.dek!==void 0?{dek:k.dek}:{},updated_at:new Date}).where("id","=",w.id).execute(),c=null}},g=null,y=null,p=async()=>{if(g)return g;let k=await u.getAccount();if(!k.dek)throw new Error(`No DEK found for account (tenant: "${r}", integration: "${t}"). Initialize the account first.`);return g=await W(k.dek,o),g},f=async()=>{if(y)return y;let k=await u.getIntegration();if(!k.dek)throw new Error(`No DEK found for integration "${t}". Initialize the integration first.`);return y=await W(k.dek,o),y},h=async()=>{let k=await u.getAccount(),w=await p(),T=k.config;return!T||Object.keys(T).length===0?{}:ee(T,w)},m=async()=>{let k=await u.getIntegration(),w=await f(),T=k.config;return!T||Object.keys(T).length===0?{}:ee(T,w)},b={get_dek:p,issue_new_dek:async()=>{let k=await u.getAccount(),w=Q(),T={};if(k.dek){let _=await W(k.dek,o),E=k.config;E&&Object.keys(E).length>0&&(T=De(E,_,w))}let S=await X(w,o);return await u.updateAccount({config:T,dek:S}),g=w,w},...It(h,async k=>{let w=await p(),T;try{T=await h()}catch(E){console.error(`[corsair] Failed to decrypt config for account (tenant: "${r}", integration: "${t}"), starting fresh:`,E),T={}}let S={...T};for(let[E,x]of Object.entries(k))x===null?delete S[E]:S[E]=x;let _=ce(S,w);await u.updateAccount({config:_})},a)};return n==="oauth_2"&&(b.get_integration_credentials=async()=>{let k=await m();return{client_id:k.client_id||null,client_secret:k.client_secret||null,redirect_url:k.redirect_url??null}}),b}async function St(e,n,t){let r=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!r)throw new Error(`Integration "${n}" not found.`);let o=Q(),i=await X(o,t);return await e.db.updateTable("corsair_integrations").set({dek:i,updated_at:new Date}).where("id","=",r.id).execute(),o}async function _t(e,n,t,r){let o=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!o)throw new Error(`Integration "${n}" not found.`);let i=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t).where("integration_id","=",o.id).executeTakeFirst();if(!i)throw new Error(`Account not found for tenant "${t}" and integration "${n}".`);let s=Q(),a=await X(s,r);return await e.db.updateTable("corsair_accounts").set({dek:a,updated_at:new Date}).where("id","=",i.id).execute(),s}var Et=e=>{if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e};async function ro(e){let n=await e.database.db.selectFrom("corsair_integrations").selectAll().where("name","=",e.pluginId).executeTakeFirst();if(!n)throw new Error(`Integration '${e.pluginId}' not found. Run setupCorsair before registering webhook tenant links.`);let t=await e.database.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",e.tenantId).where("integration_id","=",n.id).executeTakeFirst();if(!t)throw new Error(`Account not found for tenant '${e.tenantId}' and integration '${e.pluginId}'.`);return{integrationId:n.id,accountId:t.id}}async function oo(e){let n=await e.database.db.selectFrom("corsair_accounts").selectAll().where("id","=",e.accountId).executeTakeFirst();if(!n?.dek)throw new Error(`Account '${e.accountId}' has no DEK.`);let t=await W(n.dek,e.kek),r=Et(n.config),o={};Object.keys(r).length>0&&(o=ee(r,t)),o[e.link.linkType]=e.link.externalId;let i=ce(o,t);await e.database.db.updateTable("corsair_accounts").set({config:i,updated_at:new Date}).where("id","=",n.id).execute()}async function Ce(e){let{database:n,kek:t,pluginId:r,tenantId:o,link:i,authType:s,extraAccountFields:a=[]}=e,{accountId:c}=await ro({database:n,pluginId:r,tenantId:o}),d=!1;if(s){let l=I({authType:s,integrationName:r,tenantId:o,kek:t,database:n,extraAccountFields:a}),u=`set_${i.linkType}`,g=l[u];typeof g=="function"&&(await g(i.externalId),d=!0)}d||await oo({database:n,kek:t,accountId:c,link:i})}async function Sn(e){let{database:n,kek:t,pluginId:r,linkType:o,externalId:i}=e,s=await n.db.selectFrom("corsair_accounts as accounts").innerJoin("corsair_integrations as integrations","integrations.id","accounts.integration_id").selectAll("accounts").where("integrations.name","=",r).execute();for(let a of s)if(a.dek)try{let c=await W(a.dek,t),l=Et(a.config)[o];if(!l)continue;if(Oe(l,c)===i)return a}catch{continue}return null}async function ze(e){return(await Sn(e))?.tenant_id??null}async function Ot(e){return ze({database:e.database,kek:e.kek,pluginId:e.pluginId,linkType:e.match.linkType,externalId:e.match.externalId})}var ue=class extends Error{code;constructor(n,t){super(t),this.name="ManagedOAuthDeliveryError",this.code=n}};async function Te(e,n){let{plugin:t,tenantId:r,accessToken:o,refreshToken:i,expiresIn:s,scope:a}=n;if(!o.trim())throw new ue("no_access_token","Managed OAuth delivery missing access_token");let c=P(e,()=>new ue("invalid_corsair_instance","Invalid corsair instance"));if(!c.database)throw new ue("no_database","No database configured on corsair instance");let d=B(c,t,u=>new ue("plugin_not_found",u));await we(e,r);let l=I({authType:"managed",integrationName:t,tenantId:r,kek:c.kek,database:c.database});await l.set_access_token(o),i&&await l.set_refresh_token(i),s&&await l.set_expires_at(String(Math.floor(Date.now()/1e3)+s)),a&&await l.set_scope(a);try{let u=await Ke(c.plugins,t,{access_token:o,refresh_token:i,scope:a});if(u)try{let g=d.authConfig?.managed?.account??[];await Ce({database:c.database,kek:c.kek,pluginId:t,tenantId:r,link:u,authType:"managed",extraAccountFields:g})}catch(g){console.warn(`[corsair:managed-oauth] Failed to persist webhook tenant link for '${t}' tenant '${r}':`,g)}}catch(u){console.warn(`[corsair:managed-oauth] Failed to resolve webhook tenant link for '${t}' tenant '${r}':`,u)}return{plugin:t,tenantId:r}}function io(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function Dt(e,n,t=[]){for(let[r,o]of Object.entries(e))if(io(o)){if(o.match(n))return{webhook:o,path:[...t,r]}}else if(o&&typeof o=="object"){let i=Dt(o,n,[...t,r]);if(i)return i}return null}function so(e){let n={};for(let[t,r]of Object.entries(e))n[t.toLowerCase()]=Array.isArray(r)?r[0]:r;return n}function ao(e){let n=e["x-goog-resource-uri"],t=e["x-goog-channel-id"];if(!n||!t)return null;let r={resourceId:e["x-goog-resource-id"]||"",resourceState:e["x-goog-resource-state"]||"",resourceUri:n,channelId:t,channelExpiration:e["x-goog-channel-expiration"]||""};return n.includes("/drive/")&&(r.kind="drive#change"),{message:{data:Buffer.from(JSON.stringify(r)).toString("base64"),messageId:e["x-goog-message-number"]||""}}}async function Ht(e,n,t,r){let o=so(n),i=typeof t=="string"?JSON.parse(t):t;(!i||typeof i=="object"&&Object.keys(i).length===0)&&o["x-goog-resource-uri"]&&(i=ao(o)||i);let a={headers:o,body:i,...r?{query:r}:{}},c=r?.tenantId||"default",d=e.withTenant?e.withTenant(c):e,l=Fe;for(let u of l){let g=d[u];if(!g||!g.webhooks||g.pluginWebhookMatcher&&!g.pluginWebhookMatcher(a))continue;let y=Dt(g.webhooks,a);if(!y)continue;let p=y.path.join("."),f={payload:i,headers:o,rawBody:typeof t=="string"?t:JSON.stringify(t),...r?{query:r}:{}};try{let h=await y.webhook.handler(f),m=!!Object.keys(h.returnToSender||{})?.length;return{plugin:u,action:p,body:i,response:m?{...h?.returnToSender,success:!0}:{success:!0},...h.responseHeaders&&{responseHeaders:h.responseHeaders}}}catch(h){return console.error(`Error executing webhook handler for ${u}.${p}:`,h),{plugin:u,action:p,body:i,response:{success:!1,error:h instanceof Error?h.message:"Unknown error"}}}}return{plugin:null,action:null,body:null}}import{createHmac as co,timingSafeEqual as uo}from"crypto";var lo=300*1e3;function po(e){if(e)return e.startsWith("sha256=")?e.slice(7):e}function _n(e){let n=e.signingSecret.trim();if(!n)return{ok:!1,error:"Tunnel signing secret is required"};let t=po(e.signatureHeader);if(!t)return{ok:!1,error:"Invalid tunnel signature"};let r=Number(e.timestampHeader);if(!Number.isFinite(r))return{ok:!1,error:"Invalid or missing tunnel timestamp"};if(Math.abs(Date.now()-r*1e3)>lo)return{ok:!1,error:"Tunnel request timestamp is outside the allowed window"};let i=co("sha256",n).update(e.body).digest("hex");try{if(!uo(Buffer.from(i,"utf8"),Buffer.from(t,"utf8")))return{ok:!1,error:"Invalid tunnel signature"}}catch{return{ok:!1,error:"Invalid tunnel signature"}}return{ok:!0}}import{createHmac as go,timingSafeEqual as fo}from"crypto";function Je(e){return e.deliveryMode==="permission.approve"||e.deliveryMode==="permission.deny"}function Ve(e){return e.deliveryMode==="oauth.tokens"||typeof e.accessToken=="string"&&e.accessToken.length>0}function Mt(e){let n=e.trim();return n.length>0?n:null}function yo(e,n){let t=Mt(n);if(!t)throw new Error("Signing secret is required for browser delivery tokens");return go("sha256",t).update(e).digest("base64url")}function Ye(e,n){let t=Mt(n);if(!t)return null;let r=e.split(".");if(r.length!==2)return null;let[o,i]=r;if(!o||!i)return null;let s=yo(o,t);try{if(!fo(Buffer.from(i,"utf8"),Buffer.from(s,"utf8")))return null}catch{return null}let a;try{a=JSON.parse(Buffer.from(o,"base64url").toString("utf8"))}catch{return null}return a.exp*1e3<Date.now()?null:a}function $t(e,n){if(e instanceof Headers)return e.get(n)??void 0;let t=e[n]??e[n.toLowerCase()];return Array.isArray(t)?t[0]:typeof t=="string"?t:void 0}async function ho(e,n,t){let r=typeof t.tenantId=="string"?t.tenantId:typeof t.query?.tenantId=="string"?t.query.tenantId:void 0;return r||(!n.database||!t.plugin||!t.linkType||!t.externalId?void 0:await ze({database:n.database,kek:n.kek,pluginId:t.plugin,linkType:t.linkType,externalId:t.externalId})??void 0)}async function mo(e,n,t){let r=await ho(e,n,t),o={...t.query??{},...r?{tenantId:r}:{}},i=await Ht(e,t.headers,t.body,o);if(!i.plugin)return{status:"failed",retryable:!1,error:"No matching webhook handler found"};if(i.response&&i.response.success===!1)return{status:"failed",retryable:!1,error:typeof i.response.error=="string"?i.response.error:"Webhook handler failed"};let s=i.response?.returnToSender,a=s&&typeof s=="object"&&typeof s.validationToken=="string"&&Object.keys(s).length===1?s.validationToken:s||(i.response?.data??i.response);return{status:"ok",webhookResponse:{status:i.response?.statusCode??200,body:a,headers:i.responseHeaders}}}async function ko(e,n){return await He(e,n),{status:"ok"}}async function bo(e,n){return await Te(e,{plugin:n.plugin,tenantId:n.tenantId,accessToken:n.accessToken,refreshToken:n.refreshToken,expiresIn:n.expiresIn,scope:n.scope}),{status:"ok"}}async function On(e,n,t){let r=await En(e,{token:n},t);if(r.status!=="ok")throw new Error(r.error??"Permission decision failed")}async function En(e,n,t){let r=P(e),o=n.token?.trim();if(!o)return{status:"failed",retryable:!1,error:"Permission token is required"};if(!r.database)return{status:"failed",retryable:!1,error:"Database not configured"};let i=new Date().toISOString(),s=await r.database.db.selectFrom("corsair_permissions").selectAll().where("token","=",o).executeTakeFirst();return s?s.status!=="pending"?{status:"ok"}:s.expires_at<i?(await r.database.db.updateTable("corsair_permissions").set({status:"expired",updated_at:new Date}).where("id","=",s.id).execute(),{status:"failed",retryable:!1,error:"Permission has expired"}):(await r.database.db.updateTable("corsair_permissions").set({status:t,updated_at:new Date}).where("id","=",s.id).execute(),{status:"ok"}):{status:"failed",retryable:!1,error:"Permission not found"}}async function wo(e,n){try{return await Pt(e,n),{status:"ok"}}catch(t){return{status:"failed",retryable:!1,error:t instanceof Error?t.message:"Credential delivery failed"}}}async function Dn(e,n,t={}){let r=P(e),o=$t(n.headers,"x-corsair-signature"),i=$t(n.headers,"x-corsair-timestamp");if(t.signingSecret?.trim()){let a=_n({body:n.body,signatureHeader:o,timestampHeader:i,signingSecret:t.signingSecret});if(!a.ok)return{status:"failed",retryable:!1,error:a.error}}else if(!t.allowUnsignedTunnel)return{status:"failed",retryable:!1,error:"Tunnel signing secret is required"};let s;try{s=JSON.parse(n.body)}catch{return{status:"failed",retryable:!1,error:"Invalid tunnel envelope JSON"}}switch(s.type){case"webhook":return mo(e,r,s.payload);case"oauth.callback":return ko(e,s.payload);case"oauth.tokens":return bo(e,s.payload);case"permission.approve":return En(e,s.payload,"approved");case"permission.deny":return En(e,s.payload,"denied");case"auth.credentials":return wo(e,s.payload);default:return{status:"failed",retryable:!1,error:`Unsupported tunnel type: ${s.type}`}}}async function Hn(e,n){let t=M(e),o=new URL(n).searchParams.get("d");if(!o)return{type:"json",status:200,body:{status:"ok",message:"Corsair tunnel endpoint is active",timestamp:new Date().toISOString()}};let i=Ye(o,t.signingSecret);if(!i)return{type:"json",status:400,body:{error:"Invalid or expired delivery token"}};try{if(Je(i)){if(!i.permissionToken)return{type:"json",status:400,body:{error:"Permission delivery missing permission token"}};await On(e,i.permissionToken,i.deliveryMode==="permission.approve"?"approved":"denied")}else if(Ve(i)){if(!i.accessToken)return{type:"json",status:400,body:{error:"Managed OAuth delivery missing access_token"}};await Te(e,{plugin:i.plugin,tenantId:i.tenantId,accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,scope:i.scope})}else{if(!i.code||!i.state||!i.redirectUri)return{type:"json",status:400,body:{error:"Invalid BYO OAuth delivery token"}};await He(e,{code:i.code,state:i.state,redirectUri:i.redirectUri})}}catch(s){return{type:"json",status:400,body:{error:s instanceof Error?s.message:"Hub delivery failed"}}}return{type:"redirect",url:i.hubSuccessUrl}}async function Mn(e,n){let t=M(e),r=await Dn(e,n,{signingSecret:t.signingSecret});if(r.status!=="ok")return{type:"json",status:r.retryable===!1?400:502,body:{error:r.error??"Tunnel processing failed"}};let o=r.webhookResponse;if(!o)return{type:"json",status:200,body:{status:"ok"}};let i=o.status??200,s=o.headers;return o.body&&typeof o.body=="object"&&!(o.body instanceof ArrayBuffer)?{type:"json",status:i,body:o.body,headers:s}:{type:"text",status:i,body:typeof o.body=="string"?o.body:o.body?JSON.stringify(o.body):null,headers:s}}function $n(e){if(e.type==="redirect")return Response.redirect(e.url,302);let n=new Headers;for(let[t,r]of Object.entries(e.headers??{}))typeof r=="string"&&n.set(t,r);return e.type==="json"?Response.json(e.body,{status:e.status,headers:n}):new Response(e.body,{status:e.status,headers:n})}async function Fn(e,n){return n.method==="GET"?Hn(e,n.url):Mn(e,{headers:n.headers,body:n.body??""})}async function Bn(e,n){try{let t=await Fn(e,n);return $n(t)}catch(t){if(t instanceof V)return Response.json({error:t.message},{status:503});throw t}}async function Qe(e,n){let t=n.method.toUpperCase();return t!=="GET"&&t!=="POST"?Response.json({error:"Method not allowed"},{status:405}):Bn(e,{method:t,url:n.url,headers:n.headers,body:t==="POST"?await n.text():void 0})}var ne=class extends Error{pluginId;authType;constructor(n,t,r){super(r??`[auth-missing:${n}:${t}]`),Object.setPrototypeOf(this,new.target.prototype),this.name="AuthMissingError",this.pluginId=n,this.authType=t}};var Co=300;async function Un(e,n){let{keys:t,hub:r,plugin:o,tenantId:i}=e,s=n?.forceRefresh??!1,[a,c,d]=await Promise.all([t.get_access_token(),t.get_expires_at(),t.get_refresh_token()]);if(!a&&!d)throw new ne(o,"managed");let l=Math.floor(Date.now()/1e3);if(!s&&a&&c&&Number(c)>l+Co)return{accessToken:a,expiresAt:Number(c),refreshed:!1};if(!d&&a&&!s)return{accessToken:a,expiresAt:c?Number(c):l+3600,refreshed:!1};let u=await me({hub:r,path:"/oauth/refresh",body:{plugin:o,tenantId:i},parseResponse:pt}),g=u.expires_in?l+u.expires_in:c?Number(c):l+3600;return await t.set_access_token(u.access_token),await t.set_expires_at(String(g)),u.refresh_token&&await t.set_refresh_token(u.refresh_token),u.scope&&await t.set_scope(u.scope),{accessToken:u.access_token,expiresAt:g,refreshed:!0}}async function Ft(e,n){e._refreshAuth=async()=>(await Un(n,{forceRefresh:!0})).accessToken}async function Nn(e,n){return me({hub:e,path:"/permission/sessions",notFoundMessage:"Hub REST API not found at /permission/sessions. Check HUB_API_URL and ensure the Hub API is deployed.",body:{permissionId:n.permissionId,permissionToken:n.permissionToken,plugin:n.plugin,endpoint:n.endpoint,args:n.args,tenantId:n.tenantId,deliveryUrl:e.deliveryUrl,expiresAt:n.expiresAt},parseResponse:lt})}function Wn(e){return`Approval required. Visit ${e} to approve or deny, then tell the agent to retry this action.`}function Bt(e,n){return{delivery:t=>Qe(e,t),createConnectSession:t=>je(e,t,n)}}function Xe(e,n){let t=[];e||t.push("database"),n||t.push("kek");let r={};return new Proxy(r,{get(o,i){let s=t.length>1;throw new Error(`corsair.keys.${String(i)}: Cannot access keys because ${t.join(" and ")} ${s?"are":"is"} not configured. Provide both 'database' and 'kek' in createCorsair() to enable key management.
|
|
6
|
+
|
|
7
|
+
To generate a KEK, run: openssl rand -base64 ${Ee}`)}})}var To=async(e,n)=>(console.error(`[corsair:${n.pluginId}:${n.operation}]`,{error:e.message,input:n.input}),{maxRetries:0});async function Ut(e,n,t,r,o){let i={pluginId:n,operation:t,input:r,originalError:e},s=Object.keys(o).find(d=>o[d]?.match(e,i));return await(o[s||"DEFAULT"]?.handler||To)(e,i)}import{randomBytes as Po}from"crypto";import{v4 as xo}from"uuid";var Ao={open:{read:"allow",write:"allow",destructive:"allow"},cautious:{read:"allow",write:"allow",destructive:"require_approval"},strict:{read:"allow",write:"require_approval",destructive:"deny"},readonly:{read:"allow",write:"deny",destructive:"deny"}};function Ro(e,n,t){return t!==void 0?t:Ao[n][e]}function Ln(e){let n=/(\d+)(d|h|m|s)/g,t=0,r;for(;(r=n.exec(e))!==null;){let o=parseInt(r[1],10);switch(r[2]){case"d":t+=o*864e5;break;case"h":t+=o*36e5;break;case"m":t+=o*6e4;break;case"s":t+=o*1e3;break}}return t>0?t:600*1e3}function Wt(e){return{async find_by_permission_id(n){if(e)return e.db.selectFrom("corsair_permissions").selectAll().where("id","=",n).executeTakeFirst()},async find_by_token(n){if(e)return e.db.selectFrom("corsair_permissions").selectAll().where("token","=",n).executeTakeFirst()},async set_executing(n){e&&await e.db.updateTable("corsair_permissions").set({status:"executing",updated_at:new Date}).where("id","=",n).execute()},async set_completed(n){e&&await e.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",n).execute()}}}async function Nt(e,n,t){let r=Date.now()+t;for(;Date.now()<r;){let o=await e.db.selectFrom("corsair_permissions").select(["id","status"]).where("id","=",n).executeTakeFirst();if(!o)return{result:"blocked",reason:"pending"};if(o.status==="approved")return{result:"allow",onComplete:async()=>{await e.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",n).execute()}};if(o.status==="denied")return{result:"blocked",reason:"denied"};if(o.status==="expired"||o.status==="failed")return{result:"blocked",reason:"timeout"};await new Promise(i=>setTimeout(i,500))}return{result:"blocked",reason:"timeout"}}async function Lt(e){let n=Ro(e.riskLevel,e.mode,e.override);if(n==="allow")return{result:"allow"};let t=e.meta?.irreversible?" (irreversible)":"",r=e.meta?.description?`${e.meta.description}${t}`:`${e.pluginId}.${e.endpointPath}${t}`;if(n==="deny"||!e.db)return console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 denied by permission mode '${e.mode}'.`,`
|
|
8
|
+
Action: ${r}`,`
|
|
9
|
+
To allow this, update the permission mode or add an override in your corsair config.`),{result:"blocked",reason:"policy"};let o=JSON.stringify(e.args),i=new Date().toISOString(),s=e.tenantId??"default",a=await e.db.db.selectFrom("corsair_permissions").selectAll().where("plugin","=",e.pluginId).where("endpoint","=",e.endpointPath).where("args","=",o).where("tenant_id","=",s).where("expires_at",">",i).where("status","in",["pending","approved","executing"]).orderBy("created_at","desc").limit(1).executeTakeFirst();if(a){if(a.status==="approved"){let p=e.db,f=a.id;return{result:"allow",onComplete:async()=>{await p.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",f).execute()}}}return a.status==="executing"?{result:"allow"}:(console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval already pending.`,`
|
|
10
|
+
Action: ${r}`,`
|
|
11
|
+
Permission ID: ${a.id}`,`
|
|
12
|
+
Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?Nt(e.db,a.id,e.timeoutMs??600*1e3):{result:"blocked",reason:"pending",id:a.id,token:a.token,expiresAt:a.expires_at})}let c=xo(),d=Po(32).toString("hex"),l=e.timeoutMs??600*1e3,u=new Date(Date.now()+l).toISOString();return await e.db.db.insertInto("corsair_permissions").values({id:c,created_at:new Date,updated_at:new Date,token:d,plugin:e.pluginId,endpoint:e.endpointPath,args:o,tenant_id:s,status:"pending",expires_at:u}).execute(),console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval required.`,`
|
|
13
|
+
Action: ${r}`,`
|
|
14
|
+
Permission ID: ${c}`,`
|
|
15
|
+
Permission token: ${d}`,`
|
|
16
|
+
Expires at: ${u}`,`
|
|
17
|
+
Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?Nt(e.db,c,l):{result:"blocked",reason:"pending",id:c,token:d,expiresAt:u}}function vo(e){return typeof e=="function"}function Io(e,n,t){let r=ae(J(e,n.tenantId??t??"default"),n.kek),o=new URL(n.baseUrl);o.searchParams.set("state",r);let i=o.toString(),s=n.onAuthMissing?n.onAuthMissing({plugin:e,connectUrl:i,state:r}):`[auth-missing:${e}] Authentication required. Direct the user to connect their account: ${i}`;return new Error(s)}function jn({endpoints:e,hooks:n,ctx:t,tree:r,pluginId:o,errorHandlers:i,currentPath:s=[],keyBuilder:a,permissionsConfig:c,endpointMeta:d,database:l,approvalConfig:u,tenantId:g,connectConfig:y,hubConfig:p}){for(let[f,h]of Object.entries(e)){let m=n?.[f];if(vo(h)){let C=m,b=[...s,f].join("."),k=async(w={})=>{let T;if(c){let v=d?.[b],{result:he,reason:q,onComplete:Ae,token:G,id:oe,expiresAt:F}=await Lt({pluginId:o,endpointPath:b,args:w,mode:c.mode,override:c.overrides?.[b],riskLevel:v?.riskLevel??"write",meta:v,db:l,timeoutMs:u?Ln(u.timeout):void 0,tenantId:g,approvalMode:u?.mode});if(he==="blocked"){let O;if(q==="denied")O=`Action '${b}' was denied by the user. Await further instructions before proceeding.`;else if(q==="policy")O=`Action '${b}' is blocked by the permission policy. Update the corsair config to allow it.`;else if(q==="timeout")O=`Action '${b}' timed out waiting for approval.`;else if(G&&oe)if(u?.formatAsyncMessage)O=u.formatAsyncMessage({token:G,id:oe,plugin:o,endpoint:b,args:w});else if(p)try{let pe=u?Ln(u.timeout):6e5,mn=await Nn(p,{permissionId:oe,permissionToken:G,plugin:o,endpoint:b,args:w,tenantId:g??"default",expiresAt:F??new Date(Date.now()+pe).toISOString()});O=Wn(mn.approvalUrl)}catch(pe){let mn=pe instanceof Error?pe.message:String(pe);O=`Action '${b}' requires user approval before it can run. Could not create approval link: ${mn}`}else O=`Action '${b}' requires user approval before it can run.`;else O=`Action '${b}' requires user approval before it can run.`;throw new Error(O)}T=Ae}let S=async(v,he,q)=>{try{return await h(he,q)}catch(Ae){if(Ae instanceof Error){let G=await Ut(Ae,o,b,typeof q=="object"&&q!==null?q:{args:q},i);if(v<(G.maxRetries||0)){let oe=v+1;console.log(`Retrying (${oe} / ${G.maxRetries})...`);let F;if(G.headersRetryAfterMs)F=G.headersRetryAfterMs;else switch(G.retryStrategy){case"exponential_backoff":F=Math.pow(2,oe-1)*1e3;break;case"exponential_backoff_jitter":let O=Math.pow(2,oe-1)*1e3,pe=(Math.random()-.5)*1e3;F=Math.max(0,O+pe);break;case"linear_1s":F=1e3;break;case"linear_2s":F=2e3;break;case"linear_3s":F=3e3;break;case"linear_4s":F=4e3;break;default:F=1e3;break}await new Promise(O=>setTimeout(O,F)),await S(oe,he,q),console.log(`[corsair:${o}:${b}] Retry strategy:`,G)}}throw Ae}},_;try{_=a?await a(t,"endpoint"):void 0}catch(v){throw y?.oauthConfig&&y.kek&&v instanceof ne&&v.authType==="oauth_2"?Io(o,y,g):v}if(!C?.before&&!C?.after){let v=await S(0,{...t,key:_},w);return await T?.(),v}let E={...t,key:_},x=C.before?await C.before(E,w):{ctx:E,args:w,continue:!0,passToAfter:void 0};if(x.continue===!1)return;let ye=await S(0,x.ctx,x.args);return await C.after?.(x.ctx,ye,x.passToAfter),await T?.(),ye};r[f]=k}else if(h&&typeof h=="object"){let C={};jn({endpoints:h,hooks:m,ctx:t,tree:C,pluginId:o,errorHandlers:i,currentPath:[...s,f],keyBuilder:a,permissionsConfig:c,endpointMeta:d,database:l,approvalConfig:u,tenantId:g,connectConfig:y,hubConfig:p}),r[f]=C}}}function So(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function Kn({webhooks:e,hooks:n,ctx:t,webhooksTree:r,keyBuilder:o}){for(let[i,s]of Object.entries(e)){let a=n?.[i];if(So(s)){let c=a,d=async l=>{let u=(y,p)=>s.handler(y,p),g=o?await o(t,"webhook"):void 0;return!c?.before&&!c?.after?u({...t,key:g},l):(async()=>{let y={...t,key:g},p=c.before?await c.before(y,l):{ctx:y,args:l,continue:!0,passToAfter:void 0};if(p.continue===!1)return;let f=await u(p.ctx,p.args);return f?.success===!0&&await c.after?.(p.ctx,f,p.passToAfter),f})()};r[i]={match:s.match,handler:d}}else if(s&&typeof s=="object"){let c={};Kn({webhooks:s,hooks:a,ctx:t,webhooksTree:c,keyBuilder:o}),r[i]=c}}}function _o(e,n,t){let r=null;return async()=>{if(r)return r;if(!e)throw new Error("Database not configured");let o=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!o)throw new Error(`Integration "${n}" not found. Make sure to create the integration first.`);let i=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t).where("integration_id","=",o.id).executeTakeFirst();if(!i)throw new Error(`Account not found for tenant "${t}" and integration "${n}". Make sure to create the account first.`);return r=i.id,r}}function Eo(e,n,t,r,o){return e?kn(e.db,n,t,r,o):{findByEntityId:async()=>null,findById:async()=>null,findManyByEntityIds:async()=>[],list:async()=>[],search:async()=>[],upsertByEntityId:async()=>{throw new Error("Database not configured")},deleteById:async()=>!1,deleteByEntityId:async()=>!1,count:async()=>0}}function Zn(e,n){let{database:t,tenantId:r,kek:o,rootErrorHandlers:i,approvalConfig:s,connectConfig:a,hubConfig:c}=n,d={},l={};for(let u of e)d[u.id]={},l[u.id]={};for(let u of e){let g=u.schema,y=r??"default",p=_o(t,u.id,y);if(g?.entities){let x={};for(let[ye,v]of Object.entries(g.entities)){let he=t?kn(t.db,p,ye,g.version,v):Eo(void 0,p,ye,g.version,v);x[ye]=he}l[u.id].db=x,d[u.id].db=x}let f=u.options,h=u.authConfig,m;if(t&&o&&f?.authType){let x=h?.[f.authType]?.account??[];m=I({authType:f.authType,integrationName:u.id,tenantId:y,kek:o,database:t,extraAccountFields:x}),d[u.id].keys=m}let C={database:t,db:l[u.id]?.db??{},$getAccountId:p,...u.options?{options:u.options}:{},...m?{keys:m,authType:f?.authType}:{},tenantId:y,...c?{hub:c}:{}},b=u.endpoints??{},k=u.hooks,w={...i,...u.errorHandlers},T={},S=u.options?.permissions;jn({endpoints:b,hooks:k,ctx:C,tree:T,pluginId:u.id,errorHandlers:w,currentPath:[],keyBuilder:u.keyBuilder,permissionsConfig:S,endpointMeta:u.endpointMeta,database:t,approvalConfig:s,tenantId:r,connectConfig:a?{...a,oauthConfig:u.oauthConfig,kek:o,tenantId:y}:void 0,hubConfig:c}),Object.keys(T).length>0&&(d[u.id].api=T),C.endpoints=T;let _=u.webhooks??{},E=u.webhookHooks;if(Object.keys(_).length>0){let x={};Kn({webhooks:_,hooks:E,ctx:C,webhooksTree:x,keyBuilder:u.keyBuilder}),d[u.id].webhooks=x,u.pluginWebhookMatcher&&(d[u.id].pluginWebhookMatcher=u.pluginWebhookMatcher),u.pluginTenantWebhookMatcher&&(d[u.id].pluginTenantWebhookMatcher=u.pluginTenantWebhookMatcher)}}return d}function jt(e,n,t){let r={};for(let o of e){let i=o.options,s=o.authConfig;if(i?.authType){let a=s?.[i.authType]?.integration??[],c=D({authType:i.authType,integrationName:o.id,kek:t,database:n,extraIntegrationFields:a});r[o.id]=c}}return r}import*as Kt from"querystring";var L=class extends Error{code;constructor(n,t){super(t),this.name="ConnectError",this.code=n}};function Oo(e){let n=e.oauthConfig;if(!n)throw new L("plugin_has_no_oauth_config",`Plugin '${e.id}' has no oauthConfig`);return n}async function qn(e,n){let t=P(e,()=>new L("invalid_corsair_instance","Invalid corsair instance"));if(!t.database)throw new L("no_database","No database configured on corsair instance");let r=t.connect?.redirectUri;if(!r)throw new L("no_redirect_uri","No redirectUri configured. Set connect.redirectUri in createCorsair().");let o=Ne(n,t.kek);if(!o)throw new L("invalid_state","Invalid or tampered state parameter");let{plugin:i,tenantId:s}=o,a=B(t,i,y=>new L("plugin_not_found",y)),c=Oo(a),l=await D({authType:"oauth_2",integrationName:i,kek:t.kek,database:t.database}).get_client_id();if(!l)throw new L("client_id_not_configured",`client_id not configured for '${i}'`);let u={...c.authParams,client_id:l,redirect_uri:r,response_type:"code",scope:c.scopes.join(" "),state:n},g=`${c.authUrl}?${Kt.stringify(u)}`;return{plugin:i,tenantId:s,providerName:c.providerName,oauthUrl:g,state:n}}var A=class extends Error{status;code;extra;constructor(n,t,r,o={}){super(r??t),this.name="ManagementApiError",this.status=n,this.code=t,this.extra=o}};function R(e,n){return new Response(JSON.stringify(n),{status:e,headers:{"content-type":"application/json"}})}function Zt(e){let n={error:e.code,message:e.message,...e.extra};return R(e.status,n)}function de(e){return new A(404,"not_found",e)}function te(e,n={}){return new A(400,"bad_request",e,n)}function qt(e,n){return B(e,n,t=>de(t))}async function Gn(e,n){let t=e.options?.authType;if(!t||!n.database||!n.kek)return{configured:!1,missingFields:[]};let r=D({authType:t,integrationName:e.id,kek:n.kek,database:n.database}),o=U[t].integration,i=r,s;try{s=await Promise.all(o.map(d=>i[`get_${d}`]()))}catch{s=o.map(()=>null)}let a=o.filter((d,l)=>s[l]==null),c;return t==="oauth_2"?c=!a.includes("client_id")&&!a.includes("client_secret"):c=a.length===0,{configured:c,missingFields:a}}async function Gt(e,n){let t=e.options?.authType??null,r=e.oauthConfig,{configured:o,missingFields:i}=await Gn(e,n);return{id:e.id,authType:t,configured:o,missingFields:i,oauth:r?{providerName:r.providerName,scopes:r.scopes,requiresRegisteredRedirect:!!r.requiresRegisteredRedirect}:null}}function en(){return{ok:!0}}async function nn(e){return Promise.all(e.plugins.map(n=>Gt(n,e)))}async function tn(e,n){let t=qt(e,n);return Gt(t,e)}async function zt(e,n){return e.database?(await e.database.db.selectFrom("corsair_accounts as a").innerJoin("corsair_integrations as i","i.id","a.integration_id").select(["a.id as accountId","a.dek as dek","i.name as integrationName"]).where("a.tenant_id","=",n).execute()).map(r=>({integrationName:r.integrationName,hasCredentials:!!r.dek})):[]}async function Jt(e,n){let t=await zt(e,n),r=t.filter(o=>o.hasCredentials).map(o=>o.integrationName);return{id:n,accounts:t,connectedPlugins:r}}async function rn(e){let n=new Map;if(n.set("default",{id:"default",accounts:[],connectedPlugins:[]}),e.database){let t=await e.database.db.selectFrom("corsair_accounts as a").innerJoin("corsair_integrations as i","i.id","a.integration_id").select(["a.tenant_id","a.dek as dek","i.name as integrationName"]).execute();for(let r of t){let o=r.tenant_id;if(!o)continue;let i=n.get(o);i||(i={id:o,accounts:[],connectedPlugins:[]},n.set(o,i));let s=!!r.dek;i.accounts.push({integrationName:r.integrationName,hasCredentials:s}),s&&i.connectedPlugins.push(r.integrationName)}}return[...n.values()]}async function on(e,n){if(!n)throw te("Tenant id must be a non-empty string");return Jt(e,n)}async function sn(e,n){let t=n?.id?.trim();if(!t)throw te("Tenant id is required",{missingFields:["id"]});return Jt(e,t)}async function an(e,n){let t=n?.trim()||"default",r={},o=e.database?await zt(e,t):[],i=new Map(o.map(s=>[s.integrationName,s]));for(let s of e.plugins){if(!(await Gn(s,e)).configured){r[s.id]="missing_credentials";continue}let c=i.get(s.id),d;c&&c.hasCredentials?d="connected":d="not_connected",r[s.id]=d}return r}async function cn(e,n){if(!e.database)throw de(`Permission '${n}' not found`);let t=await e.database.db.selectFrom("corsair_permissions").selectAll().where("id","=",n).executeTakeFirst();if(!t)throw de(`Permission '${n}' not found`);return t}function Do(e){if(!e.oauthConfig)throw te(`Plugin '${e.id}' has no oauthConfig`)}function zn(e){if(!e.connect)throw new A(500,"connect_not_configured","createCorsair was not given a connect config. Set { connect: { baseUrl, redirectUri } } to enable /connect routes.");return e.connect}async function un(e,n){let t=n?.plugin?.trim();if(!t)throw te("Plugin id is required",{missingFields:["plugin"]});let r=n.tenantId?.trim()||"default",o=qt(e,t);Do(o);let i=zn(e);if(!e.database||!e.kek)throw new A(500,"database_not_configured","A database and kek are required to issue connect links.");let s=await Gn(o,e);if(!s.configured)throw new A(400,"missing_credentials",`Plugin '${t}' is missing OAuth client credentials`,{missingFields:s.missingFields});let a=ae(J(t,r),e.kek),c;try{c=new URL(i.baseUrl)}catch{throw new A(500,"connect_misconfigured","connect.baseUrl is not a valid URL. Set a full URL including protocol (e.g. https://app.example.com/connect).")}return c.searchParams.set("state",a),{connectUrl:c.toString(),state:a}}async function dn(e,n,t){let r=t?.trim();if(!r)throw te("state is required",{missingFields:["state"]});zn(n);try{return await qn(e,r)}catch(o){if(o instanceof L)switch(o.code){case"invalid_state":throw te("Invalid or expired state");case"client_id_not_configured":throw new A(400,"missing_credentials","OAuth client_id is not configured for this plugin",{missingFields:["client_id"]});case"no_redirect_uri":break}throw new A(500,"resolve_failed","Could not resolve connect link. Check server logs for details.")}}async function ln(e,n,t){let r=t?.code?.trim(),o=t?.state?.trim(),i=[];if(r||i.push("code"),o||i.push("state"),i.length)throw te("Missing required fields",{missingFields:i});let s=zn(n),{processOAuthCallback:a}=await import("./oauth.js");try{return await a(e,{code:r,state:o,redirectUri:s.redirectUri})}catch(c){if(c instanceof Error&&c.name==="OAuthCallbackError")switch(c.code){case"invalid_state":throw te("Invalid or expired state");case"credentials_not_configured":throw new A(400,"missing_credentials","OAuth client credentials are not configured for this plugin",{missingFields:["client_id","client_secret"]})}throw new A(502,"oauth_callback_failed","OAuth callback did not complete. Check server logs for details.")}}async function pn(e,n){if(!e.database)throw de("Permission not found");let t=await e.database.db.selectFrom("corsair_permissions").selectAll().where("token","=",n).executeTakeFirst();if(!t)throw de("Permission not found");return t}var Vt=[{method:"GET",pattern:"/ok",handler:async()=>R(200,en())},{method:"GET",pattern:"/tenants",handler:async({internal:e})=>R(200,await rn(e))},{method:"POST",pattern:"/tenants",handler:async({internal:e,body:n})=>R(201,await sn(e,n))},{method:"GET",pattern:"/tenants/:id",handler:async({internal:e,params:n})=>R(200,await on(e,n.id))},{method:"GET",pattern:"/plugins",handler:async({internal:e})=>R(200,await nn(e))},{method:"GET",pattern:"/plugins/:id",handler:async({internal:e,params:n})=>R(200,await tn(e,n.id))},{method:"GET",pattern:"/connection-status",handler:async({internal:e,query:n})=>R(200,await an(e,n.tenantId))},{method:"GET",pattern:"/permissions/:id",handler:async({internal:e,params:n})=>R(200,await cn(e,n.id))},{method:"POST",pattern:"/permissions/lookup-by-token",handler:async({internal:e,body:n})=>{let t=n?.token?.trim();return t?R(200,await pn(e,t)):R(400,{error:"bad_request",message:"token is required",missingFields:["token"]})}},{method:"POST",pattern:"/connect/links",handler:async({internal:e,body:n})=>R(200,await un(e,n))},{method:"GET",pattern:"/connect/resolve",handler:async({corsair:e,internal:n,query:t})=>R(200,await dn(e,n,t.state??""))},{method:"POST",pattern:"/connect/oauth/callback",handler:async({corsair:e,internal:n,body:t})=>R(200,await ln(e,n,t))}];(()=>{let e=new Set;for(let n of Vt){let t=`${n.method} ${n.pattern}`;if(e.has(t))throw new Error(`Duplicate management route registered: ${t}`);e.add(t)}})();function Ho(e,n){let t=e.split("/").filter(Boolean),r=n.split("/").filter(Boolean);if(t.length!==r.length)return null;let o={};for(let i=0;i<t.length;i++){let s=t[i],a=r[i];if(s.startsWith(":"))o[s.slice(1)]=decodeURIComponent(a);else if(s!==a)return null}return o}function Mo(e,n){if(!n)return e;let t=n.endsWith("/")?n.slice(0,-1):n;return e===t?"/":e.startsWith(`${t}/`)?e.slice(t.length):e}async function $o(e){if(!(e.method==="GET"||e.method==="HEAD"||!(e.headers.get("content-type")??"").includes("application/json")))try{let t=await e.text();return t?JSON.parse(t):void 0}catch{throw new A(400,"invalid_json","Request body is not valid JSON")}}var Fo="/api/corsair";function ge(e,n={}){let t=n.basePath??Fo,r=P(e,()=>new Error("managementHandler: invalid corsair instance (missing internal config)"));return async o=>{try{let i=new URL(o.url),s=Mo(i.pathname,t),a=o.method.toUpperCase(),c=Object.fromEntries(i.searchParams);for(let d of Vt){if(d.method!==a)continue;let l=Ho(d.pattern,s);if(!l)continue;let u=await $o(o);return await d.handler({corsair:e,internal:r,req:o,params:l,query:c,body:u})}throw de(`No route for ${a} ${s}`)}catch(i){if(n.onError){let a=await n.onError(i,o);if(a)return a}if(i instanceof A)return Zt(i);let s=i instanceof Error?i.message:"Internal server error";return R(500,{error:"internal_error",message:s})}}}function Bo(e){let n=e.get?.("host")??"localhost",t=e.protocol??"http",r=e.originalUrl??e.url,o=`${t}://${n}${r}`,i=new Headers;for(let[c,d]of Object.entries(e.headers))if(d!=null)if(Array.isArray(d))for(let l of d)i.append(c,l);else i.set(c,d);let s=e.method!=="GET"&&e.method!=="HEAD",a={method:e.method,headers:i};return s&&e.body!==void 0&&(a.body=typeof e.body=="string"?e.body:JSON.stringify(e.body),i.has("content-type")||i.set("content-type","application/json")),new Request(o,a)}async function Uo(e,n){e.status(n.status),n.headers.forEach((r,o)=>e.setHeader(o,r));let t=Buffer.from(await n.arrayBuffer());e.send(t)}function Yt(e,n){let t=ge(e,n);return async(r,o,i)=>{try{let s=await t(Bo(r));await Uo(o,s)}catch(s){i(s)}}}function Qt(e,n){let t=ge(e,n);return r=>t(r.req.raw)}function Xt(e,n){let t=ge(e,n);return{GET:t,POST:t}}function er(e){let n={[Me]:e};return{ok:en,tenants:{list:()=>rn(e),create:t=>sn(e,t),get:t=>on(e,t)},plugins:{list:()=>nn(e),get:t=>tn(e,t)},connectionStatus:{get:t=>an(e,t?.tenantId)},permissions:{get:t=>cn(e,t),getByToken:t=>pn(e,t)},connect:{createLink:t=>un(e,t),resolve:t=>dn(n,e,t),oauthCallback:t=>ln(n,e,t)}}}async function nr(e,n,t,r,o="pending"){if(!e)return null;try{let i=st(),s=new Date;return await e.db.insertInto("corsair_events").values({id:i,created_at:s,updated_at:s,account_id:n,event_type:t,payload:r,status:o}).execute(),i}catch(i){return console.warn("Failed to log event:",i),null}}async function No(e,n,t,r="pending"){try{let o=await e.$getAccountId();return nr(e.database,o,n,t,r)}catch(o){return console.warn("Failed to log event:",o),null}}import*as tr from"https";import*as rr from"querystring";function gn(e,n,t,r,o){let i=new URL(r.tokenUrl),s=r.tokenAuthMethod==="basic";return new Promise((a,c)=>{let d={code:e.trim(),redirect_uri:o,grant_type:"authorization_code"};s||(d.client_id=n,d.client_secret=t);let l=rr.stringify(d),u={"Content-Type":"application/x-www-form-urlencoded","Content-Length":Buffer.byteLength(l).toString()};s&&(u.Authorization=`Basic ${Buffer.from(`${n}:${t}`).toString("base64")}`);let g=tr.request({hostname:i.hostname,...i.port?{port:Number(i.port)}:{},path:i.pathname+i.search,method:"POST",headers:u},y=>{let p="";y.on("data",f=>{p+=f}),y.on("end",()=>{if(y.statusCode!==200){c(new Error(`Token exchange failed (${y.statusCode}): ${p}`));return}try{a(JSON.parse(p))}catch{c(new Error(`Token endpoint returned non-JSON response: ${p}`))}})});g.on("error",y=>c(new Error(`Request failed: ${y.message}`))),g.write(l),g.end()})}var or=" ";function K(e){let n=e;return n._def??n.def??{}}function Z(e){let n=e.typeName;if(n)return n;let t=e.type;if(t)return`Zod${t.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}`}function j(e){return e.innerType??e.schema??e.out??e.in}function sr(e,n){switch(n){case"ZodPipe":return e.in??e.innerType;case"ZodEffects":return e.schema??e.innerType;case"ZodTransform":return e.schema??e.innerType??e.in;default:return j(e)}}function ar(e){let n=e.type;return e.element??(typeof n=="string"?void 0:n)}function yn(e,n){let t=n.shape??e.shape;return typeof t=="function"?t():t}function Pe(e){return Array.isArray(e.options)?e.options:Array.isArray(e.values)?e.values:e.entries!==null&&typeof e.entries=="object"&&!Array.isArray(e.entries)?Object.values(e.entries):[]}function cr(e,n){return e.description??n.description}function Wo(e){let n=e;for(;n;){let t=K(n),r=cr(n,t);if(r)return r;let o=Z(t);if(Xn(o)||o==="ZodPipe"||o==="ZodEffects"||o==="ZodTransform"){n=sr(t,o);continue}break}}function Xn(e){return e==="ZodOptional"||e==="ZodNullable"||e==="ZodDefault"||e==="ZodCatch"}function H(e){let n=K(e),t=Z(n);switch(t){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodDate":return"Date";case"ZodNull":return"null";case"ZodUnknown":case"ZodAny":return"any";case"ZodLiteral":return String(n.value??Pe(n)[0]??"unknown");case"ZodEnum":return Pe(n).map(r=>String(r)).join(" | ");case"ZodOptional":{let r=j(n);return r?H(r):"unknown"}case"ZodNullable":{let r=j(n);return`${r?H(r):"unknown"} | null`}case"ZodDefault":case"ZodCatch":{let r=j(n);return r?H(r):"unknown"}case"ZodArray":{let r=ar(n);if(!r)return"unknown[]";let o=K(r),i=Z(o)==="ZodUnion",s=H(r);return`${i?`(${s})`:s}[]`}case"ZodRecord":return"{}";case"ZodObject":{let r=yn(e,n),o=Object.entries(r);return o.length===0?"{}":`{ ${o.map(([s,a])=>{let c=Z(K(a));return`${c==="ZodOptional"||c==="ZodNullable"?s+"?":s}: ${H(a)}`}).join(", ")} }`}case"ZodUnion":return Pe(n).map(r=>H(r)).join(" | ");case"ZodIntersection":return`${H(n.left)} & ${H(n.right)}`;case"ZodPipe":case"ZodTransform":case"ZodEffects":{let r=sr(n,t);return r?H(r):"unknown"}default:return(t??"unknown").replace("Zod","").toLowerCase()}}function re(e){let n=K(e),t=Z(n),r=cr(e,n);switch(t){case"ZodString":return{kind:"string",optional:!1,description:r};case"ZodNumber":return{kind:"number",optional:!1,description:r};case"ZodBoolean":return{kind:"boolean",optional:!1,description:r};case"ZodLiteral":{let o=n.value??Pe(n)[0],i=typeof o=="string"||typeof o=="number"||typeof o=="boolean"?o:String(o??"");return{kind:"literal",optional:!1,description:r,value:i}}case"ZodEnum":{let o=Pe(n).map(i=>String(i));return{kind:"string",optional:!1,description:r,enum:o}}case"ZodOptional":{let o=j(n),i=o?re(o):{kind:"unknown",optional:!1};return{...i,optional:!0,description:r??i.description}}case"ZodNullable":{let o=j(n),i=o?re(o):{kind:"unknown",optional:!1};return{...i,optional:!0,description:r??i.description}}case"ZodDefault":case"ZodCatch":{let o=j(n);return o?{...re(o),description:r}:{kind:"unknown",optional:!1,description:r}}case"ZodArray":{let o=ar(n);return{kind:"array",optional:!1,description:r,items:o?re(o):{kind:"unknown",optional:!1}}}case"ZodObject":{let o=yn(e,n),i={};for(let[s,a]of Object.entries(o))i[s]=re(a);return{kind:"object",optional:!1,description:r,fields:i}}case"ZodRecord":return{kind:"unknown",optional:!1,description:r};case"ZodUnion":{let o=Pe(n);for(let i of o){let s=K(i);if(Z(s)==="ZodObject")return{...re(i),description:r}}return{kind:"unknown",optional:!1,description:r}}case"ZodIntersection":case"ZodPipe":case"ZodTransform":case"ZodEffects":{let o=j(n);return o?{...re(o),description:r}:{kind:"unknown",optional:!1,description:r}}default:return{kind:"unknown",optional:!1,description:r}}}function pc(e,n){let t=n.toLowerCase(),r=t.indexOf(".");if(r===-1)return null;let o=t.slice(0,r),i=t.slice(r+1),s=e.find(l=>l.id===o);if(!s)return null;let a=i;a.startsWith("api.")&&(a=a.slice(4));let c=le(s.endpointMeta,a),d=le(s.endpointSchemas,a);return!c&&!d?null:{input:d?.input?re(d.input):null,output:d?.output?re(d.output):null,description:c?.description}}var et=["equals","contains","startsWith","endsWith","in"],Lo=["equals","gt","gte","lt","lte","in"],jo=["equals"],Ko=["equals","before","after","between"];function ur(e){let n=K(e);switch(Z(n)){case"ZodOptional":case"ZodNullable":case"ZodDefault":case"ZodCatch":{let r=j(n);return r?ur(r):null}case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodDate":return"date";default:return null}}function nt(e){let n=K(e),t=Z(n);if(Xn(t)){let i=j(n);return i?nt(i):{}}if(t!=="ZodObject")return{};let r=yn(e,n),o={};for(let[i,s]of Object.entries(r)){let a=ur(s);a==="string"?o[i]={type:"string",operators:et}:a==="number"?o[i]={type:"number",operators:Lo}:a==="boolean"?o[i]={type:"boolean",operators:jo}:a==="date"&&(o[i]={type:"date",operators:Ko})}return o}function dr(e,n){for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return[t,r]}function Vn(e,n,t){for(let[r,o]of Object.entries(e)){let i=[...n,r];typeof o=="function"?t.push(i.join(".")):o!==null&&typeof o=="object"&&Vn(o,i,t)}}function Yn(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function Qn(e,n,t){for(let[r,o]of Object.entries(e)){let i=[...n,r];Yn(o)?t.push(i.join(".")):o!==null&&typeof o=="object"&&Qn(o,i,t)}}function tt(e,n){if(n.length===0)return null;let[t,...r]=n,o=Object.entries(e).find(([a])=>a.toLowerCase()===t);if(!o)return null;let[i,s]=o;if(r.length===0)return Yn(s)?[i]:null;if(s!==null&&typeof s=="object"&&!Yn(s)){let a=tt(s,r);if(a!==null)return[i,...a]}return null}function lr(e,n){let t=[];t.push(`${e}({`),t.push(" webhookHooks: {");for(let i=0;i<n.length;i++){let s=" ".repeat(i+2);t.push(`${s}${n[i]}: {`)}let r=" ".repeat(n.length+2),o=r+" ";t.push(`${r}before(ctx, args) {`),t.push(`${o}return { ctx, args };`),t.push(`${r}},`),t.push(`${r}after(ctx, response) {`),t.push(`${r}},`);for(let i=n.length-1;i>=0;i--){let s=" ".repeat(i+2);t.push(`${s}},`)}return t.push(" },"),t.push("})"),t.join(`
|
|
18
|
+
`)}var Zo=new Set(Fe);function fe(e,n){let t=n?.type??"api",r=n?.plugin;if(r!==void 0){let i=e.find(a=>a.id===r);if(!i)return Zo.has(r)?`This plugin (${r}) is not configured. Please add it to the Corsair instance to see its associated methods.`:fe(e);if(t==="webhooks"){if(!i.webhooks)return[];let a=[];return Qn(i.webhooks,[],a),a.map(c=>`${i.id}.webhooks.${c}`)}if(t==="db"){let a=i.schema?.entities;return a?Object.keys(a).map(c=>`${i.id}.db.${c}.search`):[]}if(!i.endpoints)return[];let s=[];return Vn(i.endpoints,[],s),s.map(a=>`${i.id}.api.${a}`)}let o={};if(t==="webhooks")for(let i of e){if(!i.webhooks)continue;let s=[];Qn(i.webhooks,[],s),o[i.id]=s.map(a=>`${i.id}.webhooks.${a}`)}else if(t==="db")for(let i of e){let s=i.schema?.entities;s&&(o[i.id]=Object.keys(s).map(a=>`${i.id}.db.${a}.search`))}else for(let i of e){if(!i.endpoints)continue;let s=[];Vn(i.endpoints,[],s),o[i.id]=s.map(a=>`${i.id}.api.${a}`)}return o}function le(e,n){if(e){for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r}}function qo(e,n){let t=e.toLowerCase(),r=n.toLowerCase();if(!t.startsWith(`${r}.`)){let i=t.slice(n.length+1),s=i.startsWith(".")?i.slice(1):i;return s.startsWith("api.")&&(s=s.slice(4)),{shortPath:s,lookupKey:s}}let o=e.slice(n.length+1);return o.toLowerCase().startsWith("api.")&&(o=o.slice(4)),{shortPath:o,lookupKey:o.toLowerCase()}}function Jn(e,n){return typeof e=="string"?e:Array.isArray(e)?`${n}:
|
|
19
|
+
${e.join(", ")}`:`${n}:
|
|
20
|
+
`+Object.entries(e).map(([t,r])=>` ${t}: ${r.join(", ")}`).join(`
|
|
21
|
+
`)}function gc(e,n){let t=n.toLowerCase(),r=t.indexOf(".");if(r!==-1){let o=t.slice(0,r),i=t.slice(r+1),s=e.find(a=>a.id===o);if(s){if(i.startsWith("db.")){let l=i.slice(3),u=l.lastIndexOf(".");if(u!==-1){let g=l.slice(0,u),y=l.slice(u+1),p=s.schema?.entities;if(y==="search"&&p){let f=dr(p,g);if(f){let[h,m]=f,C=nt(m),b=[`Search ${o} ${h} stored in the local database.`,"Pass limit and offset as numbers for pagination.","","filters {",` entity_id: string [${et.join(", ")}]`];for(let[k,w]of Object.entries(C))b.push(` ${k}?: ${w.type} [${w.operators.join(", ")}]`);return b.push("}"),b.join(`
|
|
22
|
+
`)}}}return Jn(fe(e,{type:"db"}),"Path not found. Available db operations")}if(i.startsWith("webhooks.")){let l=i.slice(9);if(s.webhooks){let u=tt(s.webhooks,l.split("."));if(u!==null){let g=u.join("."),y=le(s.webhookSchemas,g.toLowerCase()),p=y?.response?H(y.response):null,f=[];return y?.description&&f.push(y.description),y?.payload&&f.push(`payload ${fn(xe(y.payload))}`),p&&f.push(`response: ${p}`),f.push(`usage:
|
|
23
|
+
${lr(o,u)}`),f.join(`
|
|
24
|
+
|
|
25
|
+
`)}}return Jn(fe(e,{type:"webhooks"}),"Path not found. Available webhooks")}let a=i;a.startsWith("api.")&&(a=a.slice(4));let c=le(s.endpointMeta,a),d=le(s.endpointSchemas,a);if(c||d){let l=[],u=[c?.riskLevel?`[${c.riskLevel}]`:"",c?.irreversible?"[irreversible]":""].filter(Boolean).join(" "),g=[c?.description,u].filter(Boolean).join(" ");return g&&l.push(g),d?.input&&l.push(`input ${fn(xe(d.input))}`),d?.output&&l.push(`output ${fn(xe(d.output))}`),l.join(`
|
|
26
|
+
|
|
27
|
+
`)}}}return Jn(fe(e),"Path not found. Available operations")}function ir(e){let n=e;for(;;){let t=K(n),r=Z(t);if(Xn(r)){let o=j(t);if(!o)return n;n=o;continue}return n}}function xe(e){if(e===void 0)return{kind:"inline",type:"unknown"};let n=ir(e),t=K(n);if(Z(t)==="ZodObject"){let o=yn(n,t),i=[];for(let[s,a]of Object.entries(o)){let c=K(a),d=Z(c),l=d==="ZodOptional"||d==="ZodNullable",u=ir(a),g=Wo(a);i.push({key:s,optional:l,type:H(u),...g!==void 0?{description:g}:{}})}return{kind:"object",fields:i}}return{kind:"inline",type:H(n)}}function fn(e,n=0){if(e===void 0)return"{}";if(e.kind==="inline")return e.type;if(e.kind==="object"){if(e.fields.length===0)return"{}";let t=or.repeat(n+1),r=or.repeat(n);return`{
|
|
28
|
+
${e.fields.map(i=>{let s=i.optional?`${i.key}?`:i.key,a=i.description?` // ${i.description}`:"";return`${t}${s}: ${i.type}${a}`}).join(`
|
|
29
|
+
`)}
|
|
30
|
+
${r}}`}return"unknown"}function Go(e,n){let t=fe(e,{plugin:n,type:"api"});if(typeof t=="string")return{ok:!1,error:t};if(!Array.isArray(t))return{ok:!1,error:"list_operations did not return a path array \u2014 pass a configured plugin id."};let r=e.find(l=>l.id===n);if(!r)return{ok:!1,error:`Plugin "${n}" is not configured on this instance.`};let o=[];for(let l of t){let{shortPath:u,lookupKey:g}=qo(l,n),y=le(r.endpointMeta,g),p=le(r.endpointSchemas,g);!y&&!p||o.push({path:l,shortPath:u,description:y?.description,riskLevel:y?.riskLevel,irreversible:y?.irreversible,input:xe(p?.input),output:xe(p?.output)})}o.sort((l,u)=>l.path.localeCompare(u.path));let i=[],s=fe(e,{plugin:n,type:"webhooks"});if(Array.isArray(s)&&r.webhooks)for(let l of s){let g=l.toLowerCase().slice(n.length+1),y=g.startsWith(".")?g.slice(1):g;if(!y.startsWith("webhooks."))continue;let p=y.slice(9),f=tt(r.webhooks,p.split("."));if(f===null)continue;let h=f.join("."),m=le(r.webhookSchemas,h.toLowerCase()),C=m?.response?H(m.response):void 0;i.push({path:l,description:m?.description,payload:xe(m?.payload),responseType:C,usageExample:lr(n,f)})}i.sort((l,u)=>l.path.localeCompare(u.path));let a=[],c=fe(e,{plugin:n,type:"db"}),d=r.schema?.entities;if(Array.isArray(c)&&d)for(let l of c){let g=l.toLowerCase().slice(n.length+1),y=g.startsWith(".")?g.slice(1):g;if(!y.startsWith("db."))continue;let p=y.slice(3),f=p.lastIndexOf(".");if(f===-1)continue;let h=p.slice(0,f);if(p.slice(f+1)!=="search")continue;let C=dr(d,h);if(!C)continue;let[b,k]=C,w=nt(k),T=Object.entries(w).map(([S,_])=>({field:S,type:_.type,operators:_.operators}));a.push({path:l,entityName:b,filters:[{field:"entity_id",type:"string",operators:et},...T]})}return a.sort((l,u)=>l.path.localeCompare(u.path)),{ok:!0,data:{pluginId:n,api:o,webhooks:i,db:a}}}function pr(e,n){for(let[t,r]of Object.entries(e))if(r?.pluginWebhookMatcher&&r.pluginWebhookMatcher(n))return t;return null}function zo(e,n){let t=pr(e,n);if(!t)return null;let r=e[t];if(!r?.pluginTenantWebhookMatcher)return null;let o=r.pluginTenantWebhookMatcher(n);return o?{plugin:t,tenantMatch:o}:null}function Jo(e){let n={};for(let t of e)!t.pluginWebhookMatcher&&!t.pluginTenantWebhookMatcher||(n[t.id]={pluginWebhookMatcher:t.pluginWebhookMatcher,pluginTenantWebhookMatcher:t.pluginTenantWebhookMatcher});return n}function gr(e,n){let t=n.toLowerCase(),r=e[t]??e[n];return Array.isArray(r)?r[0]:typeof r=="string"?r:void 0}function fr(e){if(typeof e=="string"){let n=e.trim();return n.length>0?n:void 0}if(typeof e=="number"&&Number.isFinite(e))return String(e)}function $e(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Vo(e){return $e(e.body)}function yr(e,n){let t=e.query;if(!t)return;let r=t[n]??t[n.toLowerCase()];return hn(Array.isArray(r)?r:[r])}function hr(e){let n=e.headers??{},t=[n.validationtoken,n.validationToken,n["validation-token"],n["ms-validation-token"]];for(let c of t){let d=hn(Array.isArray(c)?c:[c]);if(d)return decodeURIComponent(d)}let r=yr({query:e.query},"validationToken");if(r)return r;let o=["x-forwarded-uri","x-original-uri","x-rewrite-url","x-envoy-original-path","referer"];for(let c of o){let d=n[c],l=Array.isArray(d)?d[0]:d;if(!(!l||typeof l!="string"))try{let g=(l.startsWith("http")?new URL(l):new URL(`https://example.invalid${l.startsWith("/")?l:`/${l}`}`)).searchParams.get("validationToken");if(g?.trim())return g.trim()}catch{continue}}let i=e.payload!==void 0?e.payload:e.body!==void 0?e.body:void 0,s=$e(typeof i=="string"?(()=>{try{return JSON.parse(i)}catch{return i}})():i);return hn([s?.validationToken])??null}function Yo(e){if(hr(e))return!0;let n=$e(e.body??e.payload);return gr(e.headers??{},"content-type")?.includes("text/plain")?!n||Object.keys(n).length===0:!1}function hn(e){for(let n of e){let t=fr(n);if(t)return t}}function Qo(e){let t=$e(e.message)?.data;if(typeof t!="string")return null;try{return JSON.parse(Buffer.from(t,"base64").toString("utf8"))}catch{return null}}var Me=Symbol.for("corsair:internal");function kt(e){let n=e.database?rt(e.database):void 0,t=n&&e.kek?jt(e.plugins,n,e.kek):Xe(!!n,!!e.kek),r={plugins:e.plugins,database:n,kek:e.kek,multiTenancy:!!e.multiTenancy,approval:e.approval,connect:e.connect,hub:e.hub?Be(e.hub):void 0},o=Wt(n),i=er(r);if(e.multiTenancy)return Object.assign({withTenant:a=>{if(!a)throw new Error("corsair.withTenant(tenantId): tenantId must be a non-empty string");let c=Zn(e.plugins,{database:n,tenantId:a,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval,connectConfig:e.connect,hubConfig:r.hub});return Object.assign(c,{[Me]:r})},keys:t,permissions:o,manage:i},{[Me]:r});let s=Zn(e.plugins,{database:n,tenantId:void 0,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval,connectConfig:e.connect,hubConfig:r.hub});return Object.assign({},s,{keys:t,permissions:o,manage:i,[Me]:r})}var $=class extends Error{code;constructor(n,t){super(t),this.name="OAuthCallbackError",this.code=n}};function kr(e){let n=e.oauthConfig;if(!n)throw new $("plugin_has_no_oauth_config",`Plugin '${e.id}' has no oauthConfig`);return n}async function Xo(e,n,t,r){let o=ct(e),i=await o.integrations.findByName(n);if(!i)throw new Error(`Integration '${n}' not found. Run setupCorsair first.`);if(await o.accounts.findOne({tenant_id:t,integration_id:i.id}))return;let a=Q(),c=await X(a,r);await o.accounts.create({tenant_id:t,integration_id:i.id,config:{},dek:c})}async function Tn(e,n,t){let{tenantId:r,redirectUri:o}=t,i=P(e,()=>new $("invalid_corsair_instance","Invalid corsair instance"));if(!i.database)throw new Error("No database configured on corsair instance");let s=B(i,n,g=>new $("plugin_not_found",g)),a=kr(s),d=await D({authType:"oauth_2",integrationName:n,kek:i.kek,database:i.database}).get_client_id();if(!d)throw new Error(`client_id not configured for '${n}'`);let l=ae(J(n,r),i.kek),u={...a.authParams,client_id:d,redirect_uri:o,response_type:"code",scope:a.scopes.join(" "),state:l};return{url:`${a.authUrl}?${mr.stringify(u)}`,state:l}}async function He(e,n){let{code:t,state:r,redirectUri:o}=n,i=P(e,()=>new $("invalid_corsair_instance","Invalid corsair instance")),s=Ne(r,i.kek);if(!s)throw new $("invalid_state","Invalid or tampered state parameter");let{plugin:a,tenantId:c}=s;if(!i.database)throw new $("no_database","No database configured on corsair instance");let d=B(i,a,h=>new $("plugin_not_found",h)),l=kr(d),u=D({authType:"oauth_2",integrationName:a,kek:i.kek,database:i.database}),g=await u.get_client_id(),y=await u.get_client_secret();if(!g||!y)throw new $("credentials_not_configured",`Credentials not configured for '${a}'`);await Xo(i.database,a,c,i.kek);let p=await gn(t,g,y,l,o);if(!p.access_token)throw new $("no_access_token",`No access_token returned from ${l.providerName}`);let f=I({authType:"oauth_2",integrationName:a,tenantId:c,kek:i.kek,database:i.database});await f.set_access_token(p.access_token),p.refresh_token&&await f.set_refresh_token(p.refresh_token),p.expires_in&&await f.set_expires_at(String(Math.floor(Date.now()/1e3)+p.expires_in));try{let h=await Ke(i.plugins,a,p);if(h)try{let m=d.authConfig?.oauth_2?.account??[];await Ce({database:i.database,kek:i.kek,pluginId:a,tenantId:c,link:h,authType:"oauth_2",extraAccountFields:m})}catch(m){console.warn(`[corsair:oauth] Failed to persist webhook tenant link for '${a}' tenant '${c}':`,m)}}catch(h){console.warn(`[corsair:oauth] Failed to resolve webhook tenant link for '${a}' tenant '${c}':`,h)}return{plugin:a,tenantId:c}}export{ut as a,ve as b,Ie as c,V as d,Be as e,M as f,Ue as g,J as h,bn as i,Q as j,X as k,W as l,vn as m,Oe as n,ce as o,ee as p,De as q,D as r,I as s,St as t,_t as u,Ce as v,Sn as w,ze as x,Ot as y,$ as z,Tn as A,He as B,_e as C,ke as D,ft as E,be as F,ht as G,jr as H,Le as I,Pn as J,xn as K,An as L,Rn as M,je as N,ue as O,Te as P,Ht as Q,Je as R,Ve as S,Ye as T,On as U,Dn as V,Hn as W,Mn as X,$n as Y,Fn as Z,Bn as _,Qe as $,ne as aa,Un as ba,Ft as ca,Bt as da,qn as ea,ge as fa,Yt as ga,Qt as ha,Xt as ia,nr as ja,No as ka,gn as la,pc as ma,fe as na,gc as oa,fn as pa,Go as qa,pr as ra,zo as sa,Jo as ta,gr as ua,fr as va,$e as wa,Vo as xa,yr as ya,hr as za,Yo as Aa,hn as Ba,Qo as Ca,Me as Da,kt as Ea};
|
package/dist/core.d.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
export { C as CORSAIR_INTERNAL, a as CorsairInternalConfig, c as createCorsair } from './index-
|
|
1
|
+
export { C as CORSAIR_INTERNAL, a as CorsairInternalConfig, c as createCorsair } from './index-B06cXWWA.js';
|
|
2
2
|
import { CorsairDatabase } from './db.js';
|
|
3
|
-
import { A as AuthTypes, a as AccountKeyManagerFor, I as IntegrationKeyManagerFor } from './types-
|
|
4
|
-
export { b as AccountFieldNames, f as AllProviders, e as BASE_AUTH_FIELDS, B as BaseAuthFieldConfig, c as BaseKeyManager, g as BaseProviders, k as Bivariant, d as IntegrationFieldNames, O as OAuth2IntegrationCredentials, h as PickAuth, P as PluginAuthConfig, j as ProviderDisplayNames, U as UnionToIntersection, i as formatProviderDisplayName } from './types-
|
|
5
|
-
export { t as BeforeHookResult, B as BindEndpoints, L as BindWebhooks, f as BoundEndpointFn, g as BoundEndpointTree, M as BoundWebhook, N as BoundWebhookTree, d as CorsairClient, h as CorsairContext, i as CorsairEndpoint, k as CorsairErrorHandler, a as CorsairIntegration, u as CorsairKeyBuilder, v as CorsairKeyBuilderBase, Q as CorsairOAuthWebhookTenantLinkResolver, q as CorsairPermissionsNamespace, C as CorsairPlugin, w as CorsairPluginContext, c as CorsairSingleTenantClient, b as CorsairTenantWrapper, S as CorsairWebhook, U as CorsairWebhookHandler, V as CorsairWebhookMatcher, X as CorsairWebhookTenantMatcher, x as EndpointHooks, y as EndpointMetaEntry, E as EndpointPathsOf, z as EndpointRiskLevel, j as EndpointTree, r as EnforcePermissionOptions, s as EnforcePermissionResult, l as ErrorContext, m as ErrorHandler, n as ErrorHandlerAndMatchFunction, o as ErrorMatcher, K as KeyBuilderContext, O as OAuthConfig, P as PermissionMode, A as PermissionPolicy, D as PluginEndpointMeta, F as PluginPermissionsConfig, Y as RawWebhookRequest, G as RequiredPluginEndpointMeta, H as RequiredPluginEndpointSchemas, I as RequiredPluginWebhookSchemas, R as RetryStrategies, p as RetryStrategy, T as TokenResponse, J as WebhookHooks, Z as WebhookPathsOf, _ as WebhookRequest, $ as WebhookResponse, W as WebhookTenantMatch, a0 as WebhookTree, e as exchangeCodeForTokens } from './index-
|
|
6
|
-
export { A as AuthMissingError, D as DocSchemaFieldRow, a as DocSchemaShape, b as DocsApiEndpoint, c as DocsDbEntity, d as DocsDbFilterField, e as DocsWebhook, E as EndpointSchemaResult, I as IntrospectPluginForDocsResult, L as ListOperationsOptions, P as PluginDocsIntrospection, j as PluginWebhookMatchers, R as ResolveConnectLinkResult, W as WebhookPluginTenantMatch, k as asRecord, g as collectPluginWebhookMatchers, l as decodePubSubData, n as extractMicrosoftGraphValidationToken, o as firstString, f as formatDocSchemaShape, p as getHeader, i as introspectPluginForDocs, q as isMicrosoftGraphValidationHandshake, m as matchWebhookPlugin, h as matchWebhookPluginAndTenant, s as readBodyRecord, t as readQueryParam, r as resolveConnectLink, u as toExternalId } from './tenant-match-utils-
|
|
3
|
+
import { A as AuthTypes, a as AccountKeyManagerFor, I as IntegrationKeyManagerFor } from './types-CqV508wD.js';
|
|
4
|
+
export { b as AccountFieldNames, f as AllProviders, e as BASE_AUTH_FIELDS, B as BaseAuthFieldConfig, c as BaseKeyManager, g as BaseProviders, k as Bivariant, d as IntegrationFieldNames, O as OAuth2IntegrationCredentials, h as PickAuth, P as PluginAuthConfig, j as ProviderDisplayNames, U as UnionToIntersection, i as formatProviderDisplayName } from './types-CqV508wD.js';
|
|
5
|
+
export { t as BeforeHookResult, B as BindEndpoints, L as BindWebhooks, f as BoundEndpointFn, g as BoundEndpointTree, M as BoundWebhook, N as BoundWebhookTree, d as CorsairClient, h as CorsairContext, i as CorsairEndpoint, k as CorsairErrorHandler, a as CorsairIntegration, u as CorsairKeyBuilder, v as CorsairKeyBuilderBase, Q as CorsairOAuthWebhookTenantLinkResolver, q as CorsairPermissionsNamespace, C as CorsairPlugin, w as CorsairPluginContext, c as CorsairSingleTenantClient, b as CorsairTenantWrapper, S as CorsairWebhook, U as CorsairWebhookHandler, V as CorsairWebhookMatcher, X as CorsairWebhookTenantMatcher, x as EndpointHooks, y as EndpointMetaEntry, E as EndpointPathsOf, z as EndpointRiskLevel, j as EndpointTree, r as EnforcePermissionOptions, s as EnforcePermissionResult, l as ErrorContext, m as ErrorHandler, n as ErrorHandlerAndMatchFunction, o as ErrorMatcher, K as KeyBuilderContext, O as OAuthConfig, P as PermissionMode, A as PermissionPolicy, D as PluginEndpointMeta, F as PluginPermissionsConfig, Y as RawWebhookRequest, G as RequiredPluginEndpointMeta, H as RequiredPluginEndpointSchemas, I as RequiredPluginWebhookSchemas, R as RetryStrategies, p as RetryStrategy, T as TokenResponse, J as WebhookHooks, Z as WebhookPathsOf, _ as WebhookRequest, $ as WebhookResponse, W as WebhookTenantMatch, a0 as WebhookTree, e as exchangeCodeForTokens } from './index-DXZWwzui.js';
|
|
6
|
+
export { A as AuthMissingError, D as DocSchemaFieldRow, a as DocSchemaShape, b as DocsApiEndpoint, c as DocsDbEntity, d as DocsDbFilterField, e as DocsWebhook, E as EndpointSchemaResult, I as IntrospectPluginForDocsResult, L as ListOperationsOptions, P as PluginDocsIntrospection, j as PluginWebhookMatchers, R as ResolveConnectLinkResult, W as WebhookPluginTenantMatch, k as asRecord, g as collectPluginWebhookMatchers, l as decodePubSubData, n as extractMicrosoftGraphValidationToken, o as firstString, f as formatDocSchemaShape, p as getHeader, i as introspectPluginForDocs, q as isMicrosoftGraphValidationHandshake, m as matchWebhookPlugin, h as matchWebhookPluginAndTenant, s as readBodyRecord, t as readQueryParam, r as resolveConnectLink, u as toExternalId } from './tenant-match-utils-CAvC74W2.js';
|
|
7
7
|
import 'kysely';
|
|
8
8
|
import 'zod';
|
|
9
9
|
import 'pg';
|
package/dist/core.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Aa as F,Ba as G,Ca as H,Da as I,Ea as J,a,aa as p,b,ea as q,j as d,ja as r,k as e,ka as s,l as f,la as t,m as g,n as h,o as i,p as j,pa as u,q as k,qa as v,r as l,ra as w,s as m,sa as x,t as n,ta as y,u as o,ua as z,va as A,wa as B,xa as C,ya as D,za as E}from"./chunk-T3RG3J3R.js";import{g as c}from"./chunk-6D4UDUPJ.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";export{p as AuthMissingError,c as BASE_AUTH_FIELDS,I as CORSAIR_INTERNAL,a as ProviderDisplayNames,B as asRecord,y as collectPluginWebhookMatchers,m as createAccountKeyManager,J as createCorsair,l as createIntegrationKeyManager,H as decodePubSubData,j as decryptConfig,f as decryptDEK,h as decryptWithDEK,i as encryptConfig,e as encryptDEK,g as encryptWithDEK,t as exchangeCodeForTokens,E as extractMicrosoftGraphValidationToken,G as firstString,u as formatDocSchemaShape,b as formatProviderDisplayName,d as generateDEK,z as getHeader,o as initializeAccountDEK,n as initializeIntegrationDEK,v as introspectPluginForDocs,F as isMicrosoftGraphValidationHandshake,r as logEvent,s as logEventFromContext,w as matchWebhookPlugin,x as matchWebhookPluginAndTenant,k as reEncryptConfig,C as readBodyRecord,D as readQueryParam,q as resolveConnectLink,A as toExternalId};
|
package/dist/hub.d.ts
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
|
-
import { l as
|
|
2
|
-
export { D as DEFAULT_HUB_API_URL, i as formatProviderDisplayName } from './types-
|
|
3
|
-
import { c as ProcessCorsairRequest } from './index-
|
|
1
|
+
import { l as HubOAuthMode, m as HubConnectSource, H as HubConfig, n as HubConfigInput, o as HubConnectSessionInput, p as HubConnectSessionResult, a as AccountKeyManagerFor } from './types-CqV508wD.js';
|
|
2
|
+
export { D as DEFAULT_HUB_API_URL, q as HubPermissionSessionInput, r as HubPermissionSessionResult, i as formatProviderDisplayName } from './types-CqV508wD.js';
|
|
3
|
+
import { c as ProcessCorsairRequest } from './index-D9gndzCb.js';
|
|
4
|
+
export { d as TunnelEnvelope, e as TunnelType } from './index-D9gndzCb.js';
|
|
5
|
+
|
|
6
|
+
type ConnectAuthKind = 'oauth' | 'api_key' | 'bot_token';
|
|
7
|
+
type ConnectPluginManifestEntry = {
|
|
8
|
+
plugin: string;
|
|
9
|
+
providerName: string;
|
|
10
|
+
authKind: ConnectAuthKind;
|
|
11
|
+
credentialFields?: string[];
|
|
12
|
+
alreadyConfigured?: boolean;
|
|
13
|
+
oauthMode?: HubOAuthMode;
|
|
14
|
+
oauthUrl?: string;
|
|
15
|
+
state?: string;
|
|
16
|
+
};
|
|
17
|
+
type CreateConnectSessionRequestBody = {
|
|
18
|
+
tenantId: string;
|
|
19
|
+
deliveryUrl: string;
|
|
20
|
+
source?: 'client' | 'server';
|
|
21
|
+
plugins: ConnectPluginManifestEntry[];
|
|
22
|
+
};
|
|
23
|
+
type CreatePermissionSessionRequestBody = {
|
|
24
|
+
permissionId: string;
|
|
25
|
+
permissionToken: string;
|
|
26
|
+
plugin: string;
|
|
27
|
+
endpoint: string;
|
|
28
|
+
args: unknown;
|
|
29
|
+
tenantId: string;
|
|
30
|
+
deliveryUrl: string;
|
|
31
|
+
expiresAt: string;
|
|
32
|
+
};
|
|
33
|
+
type HubOAuthRefreshResponse = {
|
|
34
|
+
access_token: string;
|
|
35
|
+
refresh_token?: string;
|
|
36
|
+
expires_in?: number;
|
|
37
|
+
scope?: string;
|
|
38
|
+
};
|
|
4
39
|
|
|
5
40
|
type ConnectSourceValidationError = {
|
|
6
41
|
error: string;
|
|
@@ -72,15 +107,14 @@ type HubDeliveryResult = {
|
|
|
72
107
|
status: number;
|
|
73
108
|
headers?: Record<string, string>;
|
|
74
109
|
};
|
|
75
|
-
declare function handleHubDeliveryGet(corsair: unknown, requestUrl: string): Promise<HubDeliveryResult>;
|
|
76
|
-
declare function handleHubDeliveryPost(corsair: unknown, request: ProcessCorsairRequest): Promise<HubDeliveryResult>;
|
|
77
|
-
|
|
78
110
|
type HubDeliveryRequest = {
|
|
79
111
|
method: 'GET' | 'POST';
|
|
80
112
|
url: string;
|
|
81
113
|
headers: ProcessCorsairRequest['headers'];
|
|
82
114
|
body?: string;
|
|
83
115
|
};
|
|
116
|
+
declare function handleHubDeliveryGet(corsair: unknown, requestUrl: string): Promise<HubDeliveryResult>;
|
|
117
|
+
declare function handleHubDeliveryPost(corsair: unknown, request: ProcessCorsairRequest): Promise<HubDeliveryResult>;
|
|
84
118
|
declare function hubDeliveryToResponse(result: HubDeliveryResult): Response;
|
|
85
119
|
declare function handleHubDeliveryRequest(corsair: unknown, request: HubDeliveryRequest): Promise<HubDeliveryResult>;
|
|
86
120
|
declare function respondToHubDelivery(corsair: unknown, request: HubDeliveryRequest): Promise<Response>;
|
|
@@ -97,16 +131,9 @@ type ManagedAccessTokenResult = {
|
|
|
97
131
|
expiresAt: number;
|
|
98
132
|
refreshed: boolean;
|
|
99
133
|
};
|
|
100
|
-
/**
|
|
101
|
-
* Returns a valid access token for a managed OAuth connection.
|
|
102
|
-
* Uses cached credentials when still valid; otherwise refreshes via the hub.
|
|
103
|
-
*/
|
|
104
134
|
declare function getManagedAccessToken(ctx: ManagedAuthContext, options?: {
|
|
105
135
|
forceRefresh?: boolean;
|
|
106
136
|
}): Promise<ManagedAccessTokenResult>;
|
|
107
|
-
/**
|
|
108
|
-
* Attaches a `_refreshAuth` helper on the keyBuilder context for 401 retries.
|
|
109
|
-
*/
|
|
110
137
|
declare function attachManagedRefreshAuth(ctx: Record<string, unknown>, managedContext: ManagedAuthContext): Promise<void>;
|
|
111
138
|
|
|
112
139
|
type ManagedOAuthDeliveryErrorCode = 'invalid_corsair_instance' | 'no_database' | 'plugin_not_found' | 'no_access_token';
|
|
@@ -126,9 +153,6 @@ type ProcessManagedOAuthDeliveryResult = {
|
|
|
126
153
|
plugin: string;
|
|
127
154
|
tenantId: string;
|
|
128
155
|
};
|
|
129
|
-
/**
|
|
130
|
-
* Stores managed OAuth tokens delivered from the hub after a successful connect.
|
|
131
|
-
*/
|
|
132
156
|
declare function processManagedOAuthDelivery(corsair: unknown, options: ProcessManagedOAuthDeliveryOptions): Promise<ProcessManagedOAuthDeliveryResult>;
|
|
133
157
|
|
|
134
158
|
type HubRouteHandlersOptions = HubConnectSessionResponseOptions;
|
|
@@ -137,4 +161,4 @@ declare function createHubRouteHandlers(corsair: unknown, options?: HubRouteHand
|
|
|
137
161
|
createConnectSession: (request: Request) => Promise<Response>;
|
|
138
162
|
};
|
|
139
163
|
|
|
140
|
-
export { type ConnectSourceValidationError, HubConfig, HubConfigInput, HubConnectSessionInput, type HubConnectSessionParseError, type HubConnectSessionRequestBody, type HubConnectSessionResponseOptions, HubConnectSessionResult, type HubConnectSessionSuccessBody, HubConnectSource, type HubDeliveryRequest, type HubDeliveryResult, HubNotConfiguredError, HubOAuthMode, type HubRouteHandlersOptions, type ManagedAccessTokenResult, type ManagedAuthContext, ManagedOAuthDeliveryError, type ProcessManagedOAuthDeliveryOptions, type ProcessManagedOAuthDeliveryResult, type ResolveHubConnectTenantId, attachManagedRefreshAuth, createHubConnectSession, createHubRouteHandlers, getHubConfig, getManagedAccessToken, handleHubConnectSessionRequest, handleHubDeliveryGet, handleHubDeliveryPost, handleHubDeliveryRequest, hubDeliveryToResponse, isLoopbackDeliveryUrl, normalizeHubConfig, parseHubConnectSessionBody, parseHubConnectSessionSearchParams, processManagedOAuthDelivery, resolveConnectSourceFromDeliveryUrl, resolveHubOAuthCallbackUrl, respondToHubConnectSession, respondToHubConnectSessionFromRequest, respondToHubDelivery, respondToHubDeliveryFromRequest, shouldUseBrowserConnectDelivery, validateExplicitConnectSource };
|
|
164
|
+
export { type ConnectAuthKind, type ConnectPluginManifestEntry, type ConnectSourceValidationError, type CreateConnectSessionRequestBody, type CreatePermissionSessionRequestBody, HubConfig, HubConfigInput, HubConnectSessionInput, type HubConnectSessionParseError, type HubConnectSessionRequestBody, type HubConnectSessionResponseOptions, HubConnectSessionResult, type HubConnectSessionSuccessBody, HubConnectSource, type HubDeliveryRequest, type HubDeliveryResult, HubNotConfiguredError, HubOAuthMode, type HubOAuthRefreshResponse, type HubRouteHandlersOptions, type ManagedAccessTokenResult, type ManagedAuthContext, ManagedOAuthDeliveryError, type ProcessManagedOAuthDeliveryOptions, type ProcessManagedOAuthDeliveryResult, type ResolveHubConnectTenantId, attachManagedRefreshAuth, createHubConnectSession, createHubRouteHandlers, getHubConfig, getManagedAccessToken, handleHubConnectSessionRequest, handleHubDeliveryGet, handleHubDeliveryPost, handleHubDeliveryRequest, hubDeliveryToResponse, isLoopbackDeliveryUrl, normalizeHubConfig, parseHubConnectSessionBody, parseHubConnectSessionSearchParams, processManagedOAuthDelivery, resolveConnectSourceFromDeliveryUrl, resolveHubOAuthCallbackUrl, respondToHubConnectSession, respondToHubConnectSessionFromRequest, respondToHubDelivery, respondToHubDeliveryFromRequest, shouldUseBrowserConnectDelivery, validateExplicitConnectSource };
|
package/dist/hub.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{$ as x,C as g,D as h,E as i,F as j,I as k,J as l,K as m,L as n,M as o,N as p,O as q,P as r,W as s,X as t,Y as u,Z as v,_ as w,b as a,ba as y,c as b,ca as z,d as c,da as A,e as d,f as e,g as f}from"./chunk-T3RG3J3R.js";import"./chunk-6D4UDUPJ.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";export{b as DEFAULT_HUB_API_URL,c as HubNotConfiguredError,q as ManagedOAuthDeliveryError,z as attachManagedRefreshAuth,k as createHubConnectSession,A as createHubRouteHandlers,a as formatProviderDisplayName,e as getHubConfig,y as getManagedAccessToken,n as handleHubConnectSessionRequest,s as handleHubDeliveryGet,t as handleHubDeliveryPost,v as handleHubDeliveryRequest,u as hubDeliveryToResponse,g as isLoopbackDeliveryUrl,d as normalizeHubConfig,l as parseHubConnectSessionBody,m as parseHubConnectSessionSearchParams,r as processManagedOAuthDelivery,h as resolveConnectSourceFromDeliveryUrl,f as resolveHubOAuthCallbackUrl,o as respondToHubConnectSession,p as respondToHubConnectSessionFromRequest,w as respondToHubDelivery,x as respondToHubDeliveryFromRequest,i as shouldUseBrowserConnectDelivery,j as validateExplicitConnectSource};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CorsairDatabase } from './db.js';
|
|
2
|
-
import { H as HubConfig } from './types-
|
|
3
|
-
import { C as CorsairPlugin, a as CorsairIntegration, b as CorsairTenantWrapper, c as CorsairSingleTenantClient } from './index-
|
|
2
|
+
import { H as HubConfig } from './types-CqV508wD.js';
|
|
3
|
+
import { C as CorsairPlugin, a as CorsairIntegration, b as CorsairTenantWrapper, c as CorsairSingleTenantClient } from './index-DXZWwzui.js';
|
|
4
4
|
|
|
5
5
|
declare const CORSAIR_INTERNAL: unique symbol;
|
|
6
6
|
type CorsairInternalConfig = {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ZodTypeAny } from 'zod';
|
|
2
2
|
import { CorsairDatabase, CorsairPermission, CorsairDatabaseInput } from './db.js';
|
|
3
3
|
import { CorsairPluginSchema, PluginEntityClients } from './orm.js';
|
|
4
|
-
import {
|
|
4
|
+
import { s as AllErrors, A as AuthTypes, a as AccountKeyManagerFor, P as PluginAuthConfig, I as IntegrationKeyManagerFor, f as AllProviders, H as HubConfig, n as HubConfigInput } from './types-CqV508wD.js';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Bivariance hack for function types to ensure proper type inference.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { a1 as ManagementOk, a2 as Tenant, a3 as CreateTenantInput, a4 as PluginInfo, a5 as ConnectionStatus, a6 as PermissionRecord, a7 as CreateConnectLinkInput, a8 as ConnectLink, a9 as ResolvedConnectLink, aa as OAuthCallbackInput, ab as OAuthCallbackResult, c as CorsairSingleTenantClient, C as CorsairPlugin, b as CorsairTenantWrapper, d as CorsairClient, q as CorsairPermissionsNamespace, N as BoundWebhookTree, Y as RawWebhookRequest, X as CorsairWebhookTenantMatcher, $ as WebhookResponse } from './index-
|
|
2
|
-
export { ac as CorsairManageNamespace, ad as PluginConnectionState } from './index-
|
|
3
|
-
export { c as createCorsair } from './index-
|
|
4
|
-
import { F as FormFieldSchema, L as ListOperationsOptions } from './tenant-match-utils-
|
|
5
|
-
export { A as AuthMissingError, j as PluginWebhookMatchers, R as ResolveConnectLinkResult, W as WebhookPluginTenantMatch, k as asRecord, g as collectPluginWebhookMatchers, l as decodePubSubData, o as firstString, f as formatDocSchemaShape, p as getHeader, m as matchWebhookPlugin, h as matchWebhookPluginAndTenant, s as readBodyRecord, r as resolveConnectLink, u as toExternalId } from './tenant-match-utils-
|
|
1
|
+
import { a1 as ManagementOk, a2 as Tenant, a3 as CreateTenantInput, a4 as PluginInfo, a5 as ConnectionStatus, a6 as PermissionRecord, a7 as CreateConnectLinkInput, a8 as ConnectLink, a9 as ResolvedConnectLink, aa as OAuthCallbackInput, ab as OAuthCallbackResult, c as CorsairSingleTenantClient, C as CorsairPlugin, b as CorsairTenantWrapper, d as CorsairClient, q as CorsairPermissionsNamespace, N as BoundWebhookTree, Y as RawWebhookRequest, X as CorsairWebhookTenantMatcher, $ as WebhookResponse } from './index-DXZWwzui.js';
|
|
2
|
+
export { ac as CorsairManageNamespace, ad as PluginConnectionState } from './index-DXZWwzui.js';
|
|
3
|
+
export { c as createCorsair } from './index-B06cXWWA.js';
|
|
4
|
+
import { F as FormFieldSchema, L as ListOperationsOptions } from './tenant-match-utils-CAvC74W2.js';
|
|
5
|
+
export { A as AuthMissingError, j as PluginWebhookMatchers, R as ResolveConnectLinkResult, W as WebhookPluginTenantMatch, k as asRecord, g as collectPluginWebhookMatchers, l as decodePubSubData, o as firstString, f as formatDocSchemaShape, p as getHeader, m as matchWebhookPlugin, h as matchWebhookPluginAndTenant, s as readBodyRecord, r as resolveConnectLink, u as toExternalId } from './tenant-match-utils-CAvC74W2.js';
|
|
6
6
|
export { SetupCorsairOptions, setupCorsair } from './setup.js';
|
|
7
|
-
export { O as OAuthCallbackTunnelPayload, P as ProcessCorsairOptions, c as ProcessCorsairRequest, T as TunnelAck, d as TunnelEnvelope, e as TunnelType, W as WebhookTunnelPayload, p as processCorsair } from './index-
|
|
8
|
-
import { g as BaseProviders } from './types-
|
|
9
|
-
export { R as ResolveAccountFromWebhookLinkInput, W as WebhookTenantLink, r as resolveAccountFromWebhookLink, a as resolveTenantFromWebhookLink, b as resolveTenantIdFromWebhookLink, s as setWebhookTenantLink } from './tenant-links-
|
|
7
|
+
export { O as OAuthCallbackTunnelPayload, P as ProcessCorsairOptions, c as ProcessCorsairRequest, T as TunnelAck, d as TunnelEnvelope, e as TunnelType, W as WebhookTunnelPayload, p as processCorsair } from './index-D9gndzCb.js';
|
|
8
|
+
import { g as BaseProviders } from './types-CqV508wD.js';
|
|
9
|
+
export { R as ResolveAccountFromWebhookLinkInput, W as WebhookTenantLink, r as resolveAccountFromWebhookLink, a as resolveTenantFromWebhookLink, b as resolveTenantIdFromWebhookLink, s as setWebhookTenantLink } from './tenant-links-CN6FYmyf.js';
|
|
10
10
|
import 'zod';
|
|
11
11
|
import './db.js';
|
|
12
12
|
import 'kysely';
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ba as H,Ca as j,Da as k,Ea as B,G as w,Q as I,V as T,aa as S,ea as O,fa as L,ga as A,ha as v,ia as $,ma as d,na as g,oa as C,pa as f,ra as E,sa as M,ta as W,ua as F,v as P,va as _,w as x,wa as N,x as b,xa as D,y as R}from"./chunk-T3RG3J3R.js";import"./chunk-6D4UDUPJ.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";var c=class extends Error{status;code;extra;constructor(r,o,e,a={}){super(e),this.name="CorsairClientError",this.status=r,this.code=o,this.extra=a}};function J(n){return n.endsWith("/")?n.slice(0,-1):n}async function y(n){let r={};try{r=await n.json()}catch{}let o=typeof r.error=="string"?r.error:"request_failed",e=typeof r.message=="string"?r.message:`Request failed (${n.status})`,{error:a,message:u,...t}=r;return new c(n.status,o,e,t)}function U(n){let r=J(n.baseURL),o=n.fetch??globalThis.fetch.bind(globalThis);async function e(t,s){let i=s&&Object.keys(s).length?`?${new URLSearchParams(s).toString()}`:"",p=await o(`${r}${t}${i}`,{method:"GET"});if(!p.ok)throw await y(p);return await p.json()}async function a(t,s){let i=await o(`${r}${t}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)});if(!i.ok)throw await y(i);return await i.json()}let u=encodeURIComponent;return{ok:()=>e("/ok"),tenants:{list:()=>e("/tenants"),create:t=>a("/tenants",t),get:t=>e(`/tenants/${u(t)}`)},plugins:{list:()=>e("/plugins"),get:t=>e(`/plugins/${u(t)}`)},connectionStatus:{get:t=>{let s={};return t?.tenantId&&(s.tenantId=t.tenantId),e("/connection-status",s)}},permissions:{get:t=>e(`/permissions/${u(t)}`),getByToken:t=>a("/permissions/lookup-by-token",{token:t})},connect:{createLink:t=>a("/connect/links",t),resolve:t=>e("/connect/resolve",{state:t}),oauthCallback:t=>a("/connect/oauth/callback",t)}}}function l(n){let r=n[k];if(!r)throw new Error("listOperations / getSchema: invalid corsair instance. Pass the value returned by createCorsair() or corsair.withTenant().");return r.plugins}function q(n,r){let o=g(l(n),r);return typeof o=="string"?o:Array.isArray(o)?o.join(`
|
|
2
2
|
`):Object.values(o).flat().join(`
|
|
3
|
-
`)}function G(n,r){return C(l(n),r)}function Y(n,r){return d(l(n),r)}var z=Symbol.for("corsair:internal");function K(n,r){let o=n;for(let e of r){if(!o||typeof o!="object")return null;o=o[e]}return typeof o=="function"?o:null}function h(n){return n[z]?.database}async function Q(n,r){let o=new Date().toISOString(),e=await n.permissions.find_by_token(r);if(!e)return console.error("executePermission: no permission found for token."),{error:"executePermission: no permission found for token."};if(e.status!=="approved")return console.error(`executePermission: permission '${e.id}' is '${e.status}', expected 'approved'.`),{endpoint:e.endpoint,plugin:e.plugin,result:null,error:`executePermission: permission '${e.id}' is '${e.status}', expected 'approved'.`};if(e.expires_at<o){let i=h(n);return i&&await i.db.updateTable("corsair_permissions").set({status:"expired",updated_at:new Date}).where("id","=",e.id).execute(),console.error(`executePermission: permission '${e.id}' has expired.`),{error:`executePermission: permission '${e.id}' has expired.`,endpoint:e.endpoint,plugin:e.plugin,result:null}}let a=e.tenant_id??"default",t=(n.withTenant?n.withTenant(a):n)[e.plugin];if(!t?.api)return console.error(`executePermission: plugin '${e.plugin}' not found or has no API on this corsair instance.`),{error:`executePermission: plugin '${e.plugin}' not found or has no API on this corsair instance.`,plugin:e.plugin,endpoint:e.endpoint,result:null};let s=K(t.api,e.endpoint.split("."));if(!s)return console.error(`executePermission: endpoint '${e.endpoint}' not found in plugin '${e.plugin}'.`),{endpoint:e.endpoint,plugin:e.plugin,result:null,error:`executePermission: endpoint '${e.endpoint}' not found in plugin '${e.plugin}'.`};await n.permissions.set_executing(e.id);try{let i=typeof e.args=="string"?JSON.parse(e.args):e.args,p=await s(i);return await n.permissions.set_completed(e.id),{plugin:e.plugin,endpoint:e.endpoint,result:p}}catch(i){let p=i instanceof Error?i.message:String(i),m=h(n);return m&&await m.db.updateTable("corsair_permissions").set({status:"failed",error:p,updated_at:new Date}).where("id","=",e.id).execute(),{plugin:e.plugin,endpoint:e.endpoint,result:null,error:p}}}export{
|
|
3
|
+
`)}function G(n,r){return C(l(n),r)}function Y(n,r){return d(l(n),r)}var z=Symbol.for("corsair:internal");function K(n,r){let o=n;for(let e of r){if(!o||typeof o!="object")return null;o=o[e]}return typeof o=="function"?o:null}function h(n){return n[z]?.database}async function Q(n,r){let o=new Date().toISOString(),e=await n.permissions.find_by_token(r);if(!e)return console.error("executePermission: no permission found for token."),{error:"executePermission: no permission found for token."};if(e.status!=="approved")return console.error(`executePermission: permission '${e.id}' is '${e.status}', expected 'approved'.`),{endpoint:e.endpoint,plugin:e.plugin,result:null,error:`executePermission: permission '${e.id}' is '${e.status}', expected 'approved'.`};if(e.expires_at<o){let i=h(n);return i&&await i.db.updateTable("corsair_permissions").set({status:"expired",updated_at:new Date}).where("id","=",e.id).execute(),console.error(`executePermission: permission '${e.id}' has expired.`),{error:`executePermission: permission '${e.id}' has expired.`,endpoint:e.endpoint,plugin:e.plugin,result:null}}let a=e.tenant_id??"default",t=(n.withTenant?n.withTenant(a):n)[e.plugin];if(!t?.api)return console.error(`executePermission: plugin '${e.plugin}' not found or has no API on this corsair instance.`),{error:`executePermission: plugin '${e.plugin}' not found or has no API on this corsair instance.`,plugin:e.plugin,endpoint:e.endpoint,result:null};let s=K(t.api,e.endpoint.split("."));if(!s)return console.error(`executePermission: endpoint '${e.endpoint}' not found in plugin '${e.plugin}'.`),{endpoint:e.endpoint,plugin:e.plugin,result:null,error:`executePermission: endpoint '${e.endpoint}' not found in plugin '${e.plugin}'.`};await n.permissions.set_executing(e.id);try{let i=typeof e.args=="string"?JSON.parse(e.args):e.args,p=await s(i);return await n.permissions.set_completed(e.id),{plugin:e.plugin,endpoint:e.endpoint,result:p}}catch(i){let p=i instanceof Error?i.message:String(i),m=h(n);return m&&await m.db.updateTable("corsair_permissions").set({status:"failed",error:p,updated_at:new Date}).where("id","=",e.id).execute(),{plugin:e.plugin,endpoint:e.endpoint,result:null,error:p}}}export{S as AuthMissingError,c as CorsairClientError,N as asRecord,W as collectPluginWebhookMatchers,B as createCorsair,U as createCorsairClient,j as decodePubSubData,Q as executePermission,H as firstString,f as formatDocSchemaShape,F as getHeader,G as getSchema,Y as getStructuredSchema,q as listOperations,L as managementHandler,E as matchWebhookPlugin,M as matchWebhookPluginAndTenant,T as processCorsair,I as processWebhook,D as readBodyRecord,x as resolveAccountFromWebhookLink,O as resolveConnectLink,R as resolveTenantFromWebhookLink,b as resolveTenantIdFromWebhookLink,P as setWebhookTenantLink,w as setupCorsair,A as toExpressHandler,_ as toExternalId,v as toHonoHandler,$ as toNextJsHandler};
|
package/dist/oauth.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as
|
|
1
|
+
import{A as d,B as e,h as a,i as b,z as c}from"./chunk-T3RG3J3R.js";import"./chunk-6D4UDUPJ.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";export{c as OAuthCallbackError,b as decodeOAuthState,a as encodeOAuthState,d as generateOAuthUrl,e as processOAuthCallback};
|
package/dist/orm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-N2XRSSRL.js";import{
|
|
1
|
+
import"./chunk-N2XRSSRL.js";import{m as o,n as e,o as n,p as s}from"./chunk-6D4UDUPJ.js";import{b as r,c as t,d as i,e as a}from"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";export{t as CorsairAccountsSchema,i as CorsairEntitiesSchema,a as CorsairEventsSchema,r as CorsairIntegrationsSchema,o as createCorsairOrm,e as createPluginOrm,s as createPluginOrmFactory,n as createTenantScopedOrm};
|
package/dist/setup.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { a as CorsairInternalConfig } from './index-
|
|
1
|
+
import { a as CorsairInternalConfig } from './index-B06cXWWA.js';
|
|
2
2
|
import { CorsairDatabase } from './db.js';
|
|
3
|
-
import { C as CorsairPlugin, c as CorsairSingleTenantClient, b as CorsairTenantWrapper } from './index-
|
|
4
|
-
import './types-
|
|
3
|
+
import { C as CorsairPlugin, c as CorsairSingleTenantClient, b as CorsairTenantWrapper } from './index-DXZWwzui.js';
|
|
4
|
+
import './types-CqV508wD.js';
|
|
5
5
|
import 'kysely';
|
|
6
6
|
import 'zod';
|
|
7
7
|
import 'pg';
|
package/dist/setup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{G as a,H as b}from"./chunk-T3RG3J3R.js";import"./chunk-6D4UDUPJ.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";export{b as applySetupCredentials,a as setupCorsair};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as AuthTypes } from './types-
|
|
2
|
-
import { W as WebhookTenantMatch } from './index-
|
|
1
|
+
import { A as AuthTypes } from './types-CqV508wD.js';
|
|
2
|
+
import { W as WebhookTenantMatch } from './index-DXZWwzui.js';
|
|
3
3
|
import { CorsairDatabase, CorsairAccount } from './db.js';
|
|
4
4
|
|
|
5
5
|
type WebhookTenantLink = WebhookTenantMatch;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { z as EndpointRiskLevel, C as CorsairPlugin, V as CorsairWebhookMatcher, X as CorsairWebhookTenantMatcher, Y as RawWebhookRequest, W as WebhookTenantMatch } from './index-
|
|
2
|
-
import { f as AllProviders } from './types-
|
|
1
|
+
import { z as EndpointRiskLevel, C as CorsairPlugin, V as CorsairWebhookMatcher, X as CorsairWebhookTenantMatcher, Y as RawWebhookRequest, W as WebhookTenantMatch } from './index-DXZWwzui.js';
|
|
2
|
+
import { f as AllProviders } from './types-CqV508wD.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Error thrown when a plugin endpoint is called but the required auth credentials
|
package/dist/tunnel.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { O as OAuthCallbackTunnelPayload, b as OAuthTokensTunnelPayload, P as ProcessCorsairOptions, c as ProcessCorsairRequest, T as TunnelAck, d as TunnelEnvelope, e as TunnelType, W as WebhookTunnelPayload, a as applyPermissionDecision, p as processCorsair } from './index-
|
|
2
|
-
export { r as resolveAccountFromWebhookLink, a as resolveTenantFromWebhookLink, b as resolveTenantIdFromWebhookLink, s as setWebhookTenantLink } from './tenant-links-
|
|
3
|
-
import './types-
|
|
4
|
-
import './index-
|
|
1
|
+
export { O as OAuthCallbackTunnelPayload, b as OAuthTokensTunnelPayload, P as ProcessCorsairOptions, c as ProcessCorsairRequest, T as TunnelAck, d as TunnelEnvelope, e as TunnelType, W as WebhookTunnelPayload, a as applyPermissionDecision, p as processCorsair } from './index-D9gndzCb.js';
|
|
2
|
+
export { r as resolveAccountFromWebhookLink, a as resolveTenantFromWebhookLink, b as resolveTenantIdFromWebhookLink, s as setWebhookTenantLink } from './tenant-links-CN6FYmyf.js';
|
|
3
|
+
import './types-CqV508wD.js';
|
|
4
|
+
import './index-DXZWwzui.js';
|
|
5
5
|
import 'zod';
|
|
6
6
|
import './db.js';
|
|
7
7
|
import 'kysely';
|
package/dist/tunnel.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{R as e,S as f,T as g,U as h,V as i,v as a,w as b,x as c,y as d}from"./chunk-T3RG3J3R.js";import"./chunk-6D4UDUPJ.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";export{h as applyPermissionDecision,f as isManagedBrowserDelivery,e as isPermissionBrowserDelivery,i as processCorsair,b as resolveAccountFromWebhookLink,d as resolveTenantFromWebhookLink,c as resolveTenantIdFromWebhookLink,a as setWebhookTenantLink,g as verifyBrowserDeliveryToken};
|
|
@@ -1,35 +1,3 @@
|
|
|
1
|
-
type HubConnectSource = 'client' | 'server';
|
|
2
|
-
type HubOAuthMode = 'byo' | 'managed';
|
|
3
|
-
declare const DEFAULT_HUB_API_URL = "https://auth.corsair.dev";
|
|
4
|
-
type HubConfigInput = {
|
|
5
|
-
projectApiKey: string;
|
|
6
|
-
signingSecret: string;
|
|
7
|
-
deliveryUrl: string;
|
|
8
|
-
apiUrl?: string;
|
|
9
|
-
oauthCallbackUrl?: string;
|
|
10
|
-
};
|
|
11
|
-
type HubConfig = {
|
|
12
|
-
apiUrl: string;
|
|
13
|
-
projectApiKey: string;
|
|
14
|
-
signingSecret: string;
|
|
15
|
-
deliveryUrl: string;
|
|
16
|
-
oauthCallbackUrl?: string;
|
|
17
|
-
};
|
|
18
|
-
type HubConnectSessionInput = {
|
|
19
|
-
plugin: string;
|
|
20
|
-
tenantId: string;
|
|
21
|
-
/** Inferred from hub deliveryUrl when omitted (loopback → client, else server). */
|
|
22
|
-
source?: HubConnectSource;
|
|
23
|
-
providerName?: string;
|
|
24
|
-
oauthMode?: HubOAuthMode;
|
|
25
|
-
};
|
|
26
|
-
type HubConnectSessionResult = {
|
|
27
|
-
connectUrl: string;
|
|
28
|
-
token: string;
|
|
29
|
-
projectId: string;
|
|
30
|
-
expiresAt?: string;
|
|
31
|
-
};
|
|
32
|
-
|
|
33
1
|
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 & {});
|
|
34
2
|
declare const BaseProviders: readonly ["ahrefs", "airtable", "amplitude", "asana", "bitwarden", "bluesky", "box", "cal", "calendly", "cloudflare", "cursor", "discord", "dodopayments", "dropbox", "exa", "figma", "firecrawl", "fireflies", "github", "gitlab", "gmail", "googlecalendar", "googledrive", "googlesheets", "grafana", "hackernews", "hubspot", "intercom", "jira", "linear", "monday", "notion", "onedrive", "openweathermap", "oura", "outlook", "pagerduty", "posthog", "razorpay", "reddit", "resend", "sentry", "sharepoint", "slack", "spotify", "strava", "stripe", "tally", "tavily", "teams", "telegram", "todoist", "trello", "twilio", "twitter", "twitterapiio", "typeform", "vapi", "xquik", "youtube", "zendesk", "zohomail", "zoom"];
|
|
35
3
|
declare const ProviderDisplayNames: {
|
|
@@ -102,18 +70,55 @@ type AllProviders = 'ahrefs' | 'airtable' | 'amplitude' | 'asana' | 'bitwarden'
|
|
|
102
70
|
type AuthTypes = 'oauth_2' | 'api_key' | 'bot_token' | 'managed';
|
|
103
71
|
type PickAuth<T extends AuthTypes> = T;
|
|
104
72
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
73
|
+
type HubConnectSource = 'client' | 'server';
|
|
74
|
+
type HubOAuthMode = 'byo' | 'managed';
|
|
75
|
+
declare const DEFAULT_HUB_API_URL = "https://auth.corsair.dev";
|
|
76
|
+
type HubConfigInput = {
|
|
77
|
+
projectApiKey: string;
|
|
78
|
+
signingSecret: string;
|
|
79
|
+
deliveryUrl: string;
|
|
80
|
+
apiUrl?: string;
|
|
81
|
+
oauthCallbackUrl?: string;
|
|
82
|
+
};
|
|
83
|
+
type HubConfig = {
|
|
84
|
+
apiUrl: string;
|
|
85
|
+
projectApiKey: string;
|
|
86
|
+
signingSecret: string;
|
|
87
|
+
deliveryUrl: string;
|
|
88
|
+
oauthCallbackUrl?: string;
|
|
89
|
+
};
|
|
90
|
+
type HubConnectSessionInput = {
|
|
91
|
+
/** When omitted, the connect link covers all configured plugins. */
|
|
92
|
+
plugin?: string;
|
|
93
|
+
tenantId: string;
|
|
94
|
+
/** Inferred from hub deliveryUrl when omitted (loopback → client, else server). */
|
|
95
|
+
source?: HubConnectSource;
|
|
96
|
+
providerName?: string;
|
|
97
|
+
oauthMode?: HubOAuthMode;
|
|
98
|
+
};
|
|
99
|
+
type HubConnectSessionResult = {
|
|
100
|
+
connectUrl: string;
|
|
101
|
+
token: string;
|
|
102
|
+
projectId: string;
|
|
103
|
+
expiresAt?: string;
|
|
104
|
+
};
|
|
105
|
+
type HubPermissionSessionInput = {
|
|
106
|
+
permissionId: string;
|
|
107
|
+
permissionToken: string;
|
|
108
|
+
plugin: string;
|
|
109
|
+
endpoint: string;
|
|
110
|
+
args: unknown;
|
|
111
|
+
tenantId: string;
|
|
112
|
+
expiresAt: string;
|
|
113
|
+
};
|
|
114
|
+
type HubPermissionSessionResult = {
|
|
115
|
+
approvalUrl: string;
|
|
116
|
+
token: string;
|
|
117
|
+
projectId: string;
|
|
118
|
+
expiresAt: string;
|
|
119
|
+
};
|
|
120
|
+
|
|
110
121
|
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
|
|
111
|
-
/**
|
|
112
|
-
* Bivariance hack for function types to ensure proper type inference.
|
|
113
|
-
* This helps TypeScript correctly infer function parameters and return types.
|
|
114
|
-
* @template Args - The function arguments array
|
|
115
|
-
* @template R - The function return type
|
|
116
|
-
*/
|
|
117
122
|
type Bivariant<Args extends unknown[], R> = {
|
|
118
123
|
bivarianceHack(...args: Args): R;
|
|
119
124
|
}['bivarianceHack'];
|
|
@@ -246,4 +251,4 @@ type AccountKeyManagerFor<T extends AuthTypes, Config extends PluginAuthConfig |
|
|
|
246
251
|
get_integration_credentials: () => Promise<OAuth2IntegrationCredentials>;
|
|
247
252
|
} : {});
|
|
248
253
|
|
|
249
|
-
export { type AuthTypes as A, type BaseAuthFieldConfig as B, DEFAULT_HUB_API_URL as D, type HubConfig as H, type IntegrationKeyManagerFor as I, type OAuth2IntegrationCredentials as O, type PluginAuthConfig as P, type UnionToIntersection as U, type AccountKeyManagerFor as a, type AccountFieldNames as b, type BaseKeyManager as c, type IntegrationFieldNames as d, BASE_AUTH_FIELDS as e, type AllProviders as f, BaseProviders as g, type PickAuth as h, formatProviderDisplayName as i, ProviderDisplayNames as j, type Bivariant as k, type
|
|
254
|
+
export { type AuthTypes as A, type BaseAuthFieldConfig as B, DEFAULT_HUB_API_URL as D, type HubConfig as H, type IntegrationKeyManagerFor as I, type OAuth2IntegrationCredentials as O, type PluginAuthConfig as P, type UnionToIntersection as U, type AccountKeyManagerFor as a, type AccountFieldNames as b, type BaseKeyManager as c, type IntegrationFieldNames as d, BASE_AUTH_FIELDS as e, type AllProviders as f, BaseProviders as g, type PickAuth as h, formatProviderDisplayName as i, ProviderDisplayNames as j, type Bivariant as k, type HubOAuthMode as l, type HubConnectSource as m, type HubConfigInput as n, type HubConnectSessionInput as o, type HubConnectSessionResult as p, type HubPermissionSessionInput as q, type HubPermissionSessionResult as r, type AllErrors as s };
|
package/package.json
CHANGED
package/dist/chunk-3X6WVI5I.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as I,c as _,d as F,e as A}from"./chunk-IGGCNGU2.js";import{v7 as Z}from"uuid";function C(){return Z()}import{z as h}from"zod";import{sql as w}from"kysely";function E(e){return e.replace(/'/g,"''")}function B(e){let n=E(e);return w`data->>'${w.raw(n)}'`}function R(e){let n=E(e);return w`(data->>'${w.raw(n)}')::numeric`}function P(e){let n=E(e);return w`(data->>'${w.raw(n)}')::boolean`}function S(e){let n=E(e);return w`(data->>'${w.raw(n)}')::timestamptz`}function $(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function O(e){let n=e;for(;n;){if(n instanceof h.ZodOptional||n instanceof h.ZodNullable){n=n._def.innerType;continue}if(n instanceof h.ZodDefault){n=n._def.innerType;continue}break}return n}function U(e){let n=O(e);if(n instanceof h.ZodString)return"string";if(n instanceof h.ZodNumber)return"number";if(n instanceof h.ZodBoolean)return"boolean";if(n instanceof h.ZodDate)return"date"}function K(e){let n=O(e);if(!(n instanceof h.ZodObject))return{};let r=n.shape,t={};for(let[i,o]of Object.entries(r)){let u=U(o);u&&(t[i]=u)}return t}function M(e,n,r){if(typeof r=="string")return e.where(n,"=",r);if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let t=r;"equals"in t&&typeof t.equals=="string"&&(e=e.where(n,"=",t.equals)),"contains"in t&&typeof t.contains=="string"&&(e=e.where(n,"like",`%${t.contains}%`)),"startsWith"in t&&typeof t.startsWith=="string"&&(e=e.where(n,"like",`${t.startsWith}%`)),"endsWith"in t&&typeof t.endsWith=="string"&&(e=e.where(n,"like",`%${t.endsWith}`)),"in"in t&&Array.isArray(t.in)&&(e=e.where(n,"in",t.in))}return e}function Q(e,n,r){if(typeof r=="number")return e.where(n,"=",r);if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let t=r;typeof t.equals=="number"&&(e=e.where(n,"=",t.equals)),typeof t.gt=="number"&&(e=e.where(n,">",t.gt)),typeof t.gte=="number"&&(e=e.where(n,">=",t.gte)),typeof t.lt=="number"&&(e=e.where(n,"<",t.lt)),typeof t.lte=="number"&&(e=e.where(n,"<=",t.lte)),Array.isArray(t.in)&&(e=e.where(n,"in",t.in))}return e}function z(e,n,r){if(typeof r=="boolean")return e.where(n,"=",r);if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let t=r;typeof t.equals=="boolean"&&(e=e.where(n,"=",t.equals))}return e}function J(e,n,r){if(r instanceof Date)return e.where(n,"=",r);if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let t=r;if(t.equals instanceof Date&&(e=e.where(n,"=",t.equals)),t.before instanceof Date&&(e=e.where(n,"<",t.before)),t.after instanceof Date&&(e=e.where(n,">",t.after)),Array.isArray(t.between)&&t.between.length===2){let[i,o]=t.between;i instanceof Date&&(e=e.where(n,">=",i)),o instanceof Date&&(e=e.where(n,"<=",o))}}return e}function L(e,n,r,t){return r==="number"?Q(e,R(n),t):r==="boolean"?z(e,P(n),t):r==="date"?J(e,S(n),t):M(e,B(n),t)}function H(e,n,r){if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let t=r;return"equals"in t&&(e=e.where(n,"=",t.equals)),"contains"in t&&typeof t.contains=="string"&&(e=e.where(n,"like",`%${t.contains}%`)),"startsWith"in t&&typeof t.startsWith=="string"&&(e=e.where(n,"like",`${t.startsWith}%`)),"endsWith"in t&&typeof t.endsWith=="string"&&(e=e.where(n,"like",`%${t.endsWith}`)),"in"in t&&Array.isArray(t.in)&&(e=e.where(n,"in",t.in)),e}return e.where(n,"=",r)}function G(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function b(e,n,r){return e.selectFrom("corsair_entities").selectAll().where("account_id","=",n).where("entity_type","=",r)}function v(e,n,r,t,i){let o=K(i);function u(a){let y=$(a.data);return{...a,data:i.parse(y)}}return{findByEntityId:async a=>{let y=await n(),d=await b(e,y,r).where("entity_id","=",a).executeTakeFirst();return d?u(d):null},findById:async a=>{let y=await n(),d=await b(e,y,r).where("id","=",a).executeTakeFirst();return d?u(d):null},findManyByEntityIds:async a=>{if(a.length===0)return[];let y=await n();return(await b(e,y,r).where("entity_id","in",a).execute()).map(u)},list:async a=>{let y=await n(),d=b(e,y,r);return typeof a?.limit=="number"&&(d=d.limit(a.limit)),typeof a?.offset=="number"&&(d=d.offset(a.offset)),(await d.execute()).map(u)},search:async a=>{let y=await n(),d=b(e,y,r),c=new Set(["data","limit","offset"]);for(let[l,f]of Object.entries(a))c.has(l)||f===void 0||(d=H(d,l,f));if(a.data&&typeof a.data=="object")for(let[l,f]of Object.entries(a.data)){if(f===void 0)continue;let p=o[l]??"string";d=L(d,l,p,f)}return typeof a.limit=="number"&&(d=d.limit(a.limit)),typeof a.offset=="number"&&(d=d.offset(a.offset)),(await d.execute()).map(u)},upsertByEntityId:async(a,y)=>{let d=await n(),c=i.parse(y),s=new Date,l=await b(e,d,r).select("id").where("entity_id","=",a).executeTakeFirst();if(l?.id){await e.updateTable("corsair_entities").set({version:t,data:c,updated_at:s}).where("id","=",l.id).execute();let k=await e.selectFrom("corsair_entities").selectAll().where("id","=",l.id).executeTakeFirst();return u(k)}let f=C();await e.insertInto("corsair_entities").values({id:f,created_at:s,updated_at:s,account_id:d,entity_id:a,entity_type:r,version:t,data:c}).execute();let p=await e.selectFrom("corsair_entities").selectAll().where("id","=",f).executeTakeFirst();return u(p)},deleteById:async a=>{let y=await n(),d=await e.deleteFrom("corsair_entities").where("account_id","=",y).where("entity_type","=",r).where("id","=",a).executeTakeFirst();return Number(d.numDeletedRows)>0},deleteByEntityId:async a=>{let y=await n(),d=await e.deleteFrom("corsair_entities").where("account_id","=",y).where("entity_type","=",r).where("entity_id","=",a).executeTakeFirst();return Number(d.numDeletedRows)>0},count:async()=>{let a=await n(),y=await e.selectFrom("corsair_entities").select(d=>d.fn.countAll().as("count")).where("account_id","=",a).where("entity_type","=",r).executeTakeFirst();return G(y?.count)}}}var X={corsair_integrations:I,corsair_accounts:_,corsair_entities:F,corsair_events:A};function Y(e){return X[e]}function N(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function m(e){if(!e)throw new Error("Corsair database is not configured. Pass `database` to createCorsair(...) to enable ORM.")}function T(e){if(!e)return[];let n=[];for(let r in e){let t=r,i=e[t];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)?n.push({field:t,operator:"in",value:o.in}):"like"in o&&typeof o.like=="string"&&n.push({field:t,operator:"like",value:o.like})}else n.push({field:t,value:i})}return n}function g(e,n){if(!n?.length)return e;let r=e;for(let t of n){let i=t.operator??"=";r=r.where(t.field,i,t.value)}return r}function q(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function D(e,n){let r=Y(n),t=()=>(m(e),e),i=()=>t().db.selectFrom(n),o=()=>t().db.insertInto(n),u=()=>t().db.updateTable(n),a=()=>t().db.deleteFrom(n);function y(c){let s={};for(let[l,f]of Object.entries(c))s[l]=N(f);return r.parse(s)}function d(c){let s={};for(let[l,f]of Object.entries(c))s[l]=N(f);return r.parse(s)}return{findById:async c=>{m(e);let s=i().selectAll();s=g(s,[{field:"id",value:c}]);let l=await s.executeTakeFirst();return l?y(l):null},findOne:async c=>{m(e);let s=i().selectAll();s=g(s,T(c));let l=await s.executeTakeFirst();return l?y(l):null},findMany:async c=>{m(e);let s=i().selectAll();return s=g(s,T(c?.where)),typeof c?.limit=="number"&&(s=s.limit(c.limit)),typeof c?.offset=="number"&&(s=s.offset(c.offset)),(await s.execute()).map(f=>y(f))},create:async c=>{m(e);let s=new Date,l={id:c.id??C(),created_at:s,updated_at:s,...c},f=await o().values(l).returningAll().executeTakeFirst();return f?y(f):d(l)},update:async(c,s)=>{m(e);let l={...s,updated_at:new Date},f=u().set(l).returningAll();f=g(f,[{field:"id",value:c}]);let p=await f.executeTakeFirst();return p?y(p):null},updateMany:async(c,s)=>{m(e);let l={...s,updated_at:new Date},f=i().select("id");f=g(f,T(c));let p=await f.execute();for(let k of p){let x=u().set(l);x=g(x,[{field:"id",value:k.id}]),await x.execute()}return p.length},delete:async c=>{m(e);let s=a();s=g(s,[{field:"id",value:c}]);let l=await s.executeTakeFirst();return Number(l?.numDeletedRows??0)>0},deleteMany:async c=>{m(e);let s=a();s=g(s,T(c));let l=await s.executeTakeFirst();return Number(l?.numDeletedRows??0)},count:async c=>{m(e);let s=i().select(f=>f.fn.countAll().as("count"));s=g(s,T(c));let l=await s.executeTakeFirst();return q(l?.count)}}}function V(e){let n=D(e,"corsair_integrations");return{...n,findByName:r=>n.findOne({name:r}),upsertByName:async(r,t)=>{let i=await n.findOne({name:r});return i?await n.update(i.id,t):n.create({...t,name:r})}}}function ee(e){let n=D(e,"corsair_accounts");return{...n,findByTenantAndIntegration:async(r,t)=>{m(e);let i=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();return i?n.findOne({tenant_id:r,integration_id:i.id}):null},listByTenant:(r,t)=>n.findMany({where:{tenant_id:r},limit:t?.limit,offset:t?.offset}),upsertByTenantAndIntegration:async(r,t,i)=>{let o=await n.findOne({tenant_id:r,integration_id:t});return o?await n.update(o.id,i):n.create({...i,tenant_id:r,integration_id:t})}}}function te(e){let n=D(e,"corsair_entities");return{...n,findByEntityId:({accountId:r,entityType:t,entityId:i})=>n.findOne({account_id:r,entity_type:t,entity_id:i}),findManyByEntityIds:async({accountId:r,entityType:t,entityIds:i})=>i.length===0?[]:(m(e),await e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",r).where("entity_type","=",t).where("entity_id","in",i).execute()),listByScope:({accountId:r,entityType:t,limit:i,offset:o})=>n.findMany({where:{account_id:r,entity_type:t},limit:i,offset:o}),searchByEntityId:async({accountId:r,entityType:t,query:i,limit:o,offset:u})=>{m(e);let a=e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",r).where("entity_type","=",t).where("entity_id","like",`%${i}%`);return typeof o=="number"&&(a=a.limit(o)),typeof u=="number"&&(a=a.offset(u)),await a.execute()},upsertByEntityId:async({accountId:r,entityType:t,entityId:i,version:o,data:u})=>{let a=await n.findOne({account_id:r,entity_type:t,entity_id:i});return a?await n.update(a.id,{version:o,data:u}):n.create({account_id:r,entity_type:t,entity_id:i,version:o,data:u})},deleteByEntityId:async({accountId:r,entityType:t,entityId:i})=>{m(e);let o=await e.db.deleteFrom("corsair_entities").where("account_id","=",r).where("entity_type","=",t).where("entity_id","=",i).executeTakeFirst();return Number(o.numDeletedRows)>0}}}function ne(e){let n=D(e,"corsair_events");return{...n,listByAccount:(r,t)=>n.findMany({where:{account_id:r},limit:t?.limit,offset:t?.offset}),listByStatus:(r,t)=>{let i={status:r};return t?.accountId&&(i.account_id=t.accountId),n.findMany({where:i,limit:t?.limit,offset:t?.offset})},listPending:r=>{let t={status:"pending"};return r?.accountId&&(t.account_id=r.accountId),n.findMany({where:t,limit:r?.limit??100})},updateStatus:(r,t)=>n.update(r,{status:t})}}function W(e){return{integrations:V(e),accounts:ee(e),entities:te(e),events:ne(e)}}function re(e,n,r,t,i){let o=null;async function u(){if(o!==null)return o;m(e);let a=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n.integrationName).executeTakeFirst();if(!a)throw new Error(`Integration "${n.integrationName}" not found. Make sure to create the integration first.`);let y=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",n.tenantId).where("integration_id","=",a.id).executeTakeFirst();if(!y)throw new Error(`Account not found for tenant "${n.tenantId}" and integration "${n.integrationName}". Make sure to create the account first.`);return o=y.id,o}return m(e),v(e.db,u,r,t,i)}function j(e){let{database:n,integrationName:r,schema:t,tenantId:i}=e,o=W(n),u={tenantId:i,integrationName:r},a=null;async function y(){if(a!==null)return a;m(n);let c=await n.db.selectFrom("corsair_integrations").selectAll().where("name","=",r).executeTakeFirst();if(!c)throw new Error(`Integration "${r}" not found. Make sure to create the integration first.`);let s=await n.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",i).where("integration_id","=",c.id).executeTakeFirst();if(!s)throw new Error(`Account not found for tenant "${i}" and integration "${r}". Make sure to create the account first.`);return a=s.id,a}let d={};for(let[c,s]of Object.entries(t.entities))d[c]=re(n,u,c,t.version,s);return{...d,$orm:o,$integrationName:r,$tenantId:i,$getAccountId:y}}function pe(e,n){let r=W(e);return{$tenantId:n,$orm:r,listAccounts:t=>r.accounts.listByTenant(n,t),findAccountByIntegration:t=>r.accounts.findByTenantAndIntegration(n,t),listEntities:async t=>{m(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",n).execute();if(i.length===0)return[];let o=i.map(a=>a.id),u=e.db.selectFrom("corsair_entities").selectAll().where("account_id","in",o);return t?.entityType&&(u=u.where("entity_type","=",t.entityType)),typeof t?.limit=="number"&&(u=u.limit(t.limit)),typeof t?.offset=="number"&&(u=u.offset(t.offset)),await u.execute()},listEvents:async t=>{m(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",n).execute();if(i.length===0)return[];let o=i.map(a=>a.id),u=e.db.selectFrom("corsair_events").selectAll().where("account_id","in",o);return t?.status&&(u=u.where("status","=",t.status)),typeof t?.limit=="number"&&(u=u.limit(t.limit)),typeof t?.offset=="number"&&(u=u.offset(t.offset)),await u.execute()},forIntegration:t=>j({database:e,integrationName:t.integrationName,schema:t.schema,tenantId:n})}}function ge(e,n){return{forTenant:r=>j({database:e,integrationName:n.integrationName,schema:n.schema,tenantId:r})}}export{C as a,v as b,X as c,W as d,j as e,pe as f,ge as g};
|
package/dist/chunk-J6HIPZAR.js
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import{a as zn,b as pn,d as ve}from"./chunk-3X6WVI5I.js";import{a as Gn}from"./chunk-IGGCNGU2.js";import*as jt from"querystring";var Ie=["ahrefs","airtable","amplitude","asana","bitwarden","bluesky","box","cal","calendly","cloudflare","cursor","discord","dodopayments","dropbox","exa","figma","firecrawl","fireflies","github","gitlab","gmail","googlecalendar","googledrive","googlesheets","grafana","hackernews","hubspot","intercom","jira","linear","monday","notion","onedrive","openweathermap","oura","outlook","pagerduty","posthog","razorpay","reddit","resend","sentry","sharepoint","slack","spotify","strava","stripe","tally","tavily","teams","telegram","todoist","trello","twilio","twitter","twitterapiio","typeform","vapi","xquik","youtube","zendesk","zohomail","zoom"],Jn={ahrefs:"Ahrefs",airtable:"Airtable",amplitude:"Amplitude",asana:"Asana",bitwarden:"Bitwarden",bluesky:"Bluesky",box:"Box",cal:"Cal",calendly:"Calendly",cloudflare:"Cloudflare",cursor:"Cursor",discord:"Discord",dodopayments:"Dodo Payments",dropbox:"Dropbox",exa:"Exa",figma:"Figma",firecrawl:"Firecrawl",fireflies:"Fireflies",github:"GitHub",gitlab:"GitLab",gmail:"Gmail",googlecalendar:"Google Calendar",googledrive:"Google Drive",googlesheets:"Google Sheets",grafana:"Grafana",hackernews:"Hacker News",hubspot:"HubSpot",intercom:"Intercom",jira:"Jira",linear:"Linear",monday:"Monday",notion:"Notion",onedrive:"OneDrive",openweathermap:"OpenWeatherMap",oura:"Oura",outlook:"Outlook",pagerduty:"PagerDuty",posthog:"PostHog",razorpay:"Razorpay",reddit:"Reddit",resend:"Resend",sentry:"Sentry",sharepoint:"SharePoint",slack:"Slack",spotify:"Spotify",strava:"Strava",stripe:"Stripe",tally:"Tally",tavily:"Tavily",teams:"Teams",telegram:"Telegram",todoist:"Todoist",trello:"Trello",twilio:"Twilio",twitter:"Twitter",twitterapiio:"Twitter API IO",typeform:"Typeform",vapi:"Vapi",xquik:"XQuik",youtube:"YouTube",zendesk:"Zendesk",zohomail:"Zoho Mail",zoom:"Zoom"};function be(e){let n=Jn[e];return n||e.charAt(0).toUpperCase()+e.slice(1)}var we="https://auth.corsair.dev";var G=class extends Error{constructor(){super("Hub is not configured. Pass hub: { projectApiKey, signingSecret, deliveryUrl } to createCorsair()."),this.name="HubNotConfiguredError"}};function Gt(e){let n=e[x];if(!n)throw new Error("Invalid corsair instance");return n}function Se(e){let n=(e.apiUrl?.trim()||we).replace(/\/$/,""),t=e.projectApiKey.trim(),r=e.signingSecret.trim(),i=e.deliveryUrl.trim();if(!t||!r||!i)throw new Error("Hub config requires non-empty projectApiKey, signingSecret, and deliveryUrl");return{apiUrl:n,projectApiKey:t,signingSecret:r,deliveryUrl:i,oauthCallbackUrl:e.oauthCallbackUrl?.trim()}}function zt(e){return e.apiUrl.trim().length>0&&e.deliveryUrl.trim().length>0&&e.projectApiKey.trim().length>0&&e.signingSecret.trim().length>0}function z(e){let n=Gt(e).hub;if(!n||!zt(n))throw new G;return n}function Ee(e){return e.oauthCallbackUrl?e.oauthCallbackUrl:`${e.apiUrl.replace(/\/$/,"")}/oauth/callback`}import*as Ce from"crypto";function K(e,n){return Buffer.from(JSON.stringify({plugin:e,tenantId:n,iat:Date.now()})).toString("base64url")}function gn(e,{maxAgeMs:n}={}){try{let t=e.includes(".")?e.split(".")[0]:e,r=JSON.parse(Buffer.from(t,"base64url").toString("utf-8"));if(r!==null&&typeof r=="object"&&"plugin"in r&&"tenantId"in r&&typeof r.plugin=="string"&&typeof r.tenantId=="string"){let i=r;return n!==void 0&&typeof i.iat=="number"&&Date.now()-i.iat>n?null:i}return null}catch{return null}}function ee(e,n){let t=Ce.createHmac("sha256",n).update(e).digest("base64url");return`${e}.${t}`}var Jt=600*1e3;function _e(e,n){let t=e.lastIndexOf(".");if(t===-1)return null;let r=e.slice(0,t),i=e.slice(t+1),o=Ce.createHmac("sha256",n).update(r).digest("base64url"),s=Buffer.from(i,"base64url"),a=Buffer.from(o,"base64url");return s.length!==a.length||!Ce.timingSafeEqual(s,a)?null:gn(r,{maxAgeMs:Jt})}var Vt=new Set(["localhost","127.0.0.1","[::1]","::1"]);function ge(e){try{let{hostname:n,protocol:t}=new URL(e);return t!=="http:"&&t!=="https:"?!1:Vt.has(n)}catch{return!1}}function se(e){return ge(e)?"client":"server"}function fn(e,n){return e==="client"||ge(n)}function ae(e){if(!e.source)return null;let n=ge(e.deliveryUrl);return e.source==="server"&&n?{error:'source "server" cannot be used with a loopback delivery URL \u2014 omit source to auto-detect or use "client"',status:400}:e.oauthMode==="managed"&&e.source==="client"&&!n?{error:'managed OAuth with source "client" requires a loopback delivery URL \u2014 omit source for production server delivery',status:400}:null}function Oe(e){return typeof e=="string"&&e.length>0}function Qt(e){if(!e||typeof e!="object")throw new Error("Hub API returned an empty connect session");let n=e;if(!Oe(n.connectUrl)||!Oe(n.token)||!Oe(n.projectId))throw new Error("Hub API returned an incomplete connect session (expected connectUrl, token, and projectId)");let t={connectUrl:n.connectUrl,token:n.token,projectId:n.projectId};return Oe(n.expiresAt)&&(t.expiresAt=n.expiresAt),t}function Yt(e,n){if(n===404)return"Hub REST API not found at /connect/sessions. Check HUB_API_URL and ensure the Hub API is deployed.";if(e&&typeof e=="object"){let t=e;if(t.error)return t.error;if(t.message)return t.message}return`Hub API returned HTTP ${n}`}async function Xt(e){let n=e.headers.get("content-type")??"",t=await e.text();if(!t)return null;if(!n.includes("application/json")&&t.trimStart().startsWith("<"))throw new Error(`Hub API returned HTML instead of JSON (HTTP ${e.status}). Check HUB_API_URL and deploy the latest hub API.`);try{return JSON.parse(t)}catch{throw new Error(`Hub API returned invalid JSON (HTTP ${e.status})`)}}function er(e){let n=e[x];if(!n?.kek)throw new Error("Corsair KEK is required to create a managed connect session");return n.kek}async function He(e,n){let t=z(e),r=t.apiUrl.replace(/\/$/,""),i=n.oauthMode??"byo";if(n.source){let d=ae({source:n.source,deliveryUrl:t.deliveryUrl,oauthMode:i});if(d)throw new Error(d.error)}let o=n.providerName??be(n.plugin),s=n.source??se(t.deliveryUrl),a;if(i==="managed"){let d=er(e),u=ee(K(n.plugin,n.tenantId),d);a={plugin:n.plugin,tenantId:n.tenantId,providerName:o,state:u,deliveryUrl:t.deliveryUrl,source:s,oauthMode:"managed"}}else{let d=Ee(t),{url:u,state:g}=await yn(e,n.plugin,{tenantId:n.tenantId,redirectUri:d});a={plugin:n.plugin,tenantId:n.tenantId,providerName:o,oauthUrl:u,state:g,deliveryUrl:t.deliveryUrl,source:s,oauthMode:"byo"}}let c=await fetch(`${r}/connect/sessions`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.projectApiKey}`},body:JSON.stringify(a)}),l=await Xt(c);if(!c.ok)throw new Error(Yt(l,c.status));return Qt(l)}function nr(e){if(e==="byo"||e==="managed")return e}function tr(e){if(e==="client"||e==="server")return e}function hn(e){let n=e.plugin?.trim(),t=e.tenantId?.trim()||"default",r=tr(e.source),i=nr(e.oauthMode),o=e.providerName?.trim();if(!n)return{error:"plugin is required",status:400};if(e.source!==void 0&&e.source!==null&&String(e.source).trim()!==""&&!r)return{error:'source must be "client" or "server"',status:400};if(e.oauthMode&&!i)return{error:'oauthMode must be "byo" or "managed"',status:400};let s={plugin:n,tenantId:t,oauthMode:i};return r&&(s.source=r),o&&(s.providerName=o),s}function mn(e){let{searchParams:n}=new URL(e),t=n.get("oauthMode");return{plugin:n.get("plugin")??void 0,tenantId:n.get("tenantId")??void 0,source:n.get("source")??void 0,oauthMode:t??void 0,providerName:n.get("providerName")??void 0}}function rr(e){return{ok:!0,connectUrl:e.connectUrl,token:e.token,projectId:e.projectId,expiresAt:e.expiresAt}}async function or(e,n,t){if(t?.resolveTenantId){let r=await t.resolveTenantId(e);return r?.trim()?r.trim():{error:"Unauthorized",status:401}}return n.tenantId?.trim()||t?.defaultTenantId?.trim()||"default"}async function kn(e,n,t){let i=n.method.toUpperCase()==="GET"?mn(n.url):await n.json().catch(()=>null);if(!i)return{error:"Invalid JSON body",status:400};let o=await or(n,i,t);if(typeof o!="string")return o;let s=hn({...i,tenantId:o});if("error"in s)return s;let a=z(e);if(s.source){let d=ae({source:s.source,deliveryUrl:a.deliveryUrl,oauthMode:s.oauthMode});if(d)return d}let c={...s,source:s.source??se(a.deliveryUrl)},l=await He(e,c);return rr(l)}async function bn(e,n,t){try{let r=await kn(e,n,t);return"error"in r?Response.json({error:r.error},{status:r.status}):Response.json(r)}catch(r){if(r instanceof G)return Response.json({error:r.message},{status:503});let i=r instanceof Error?r.message:String(r);return Response.json({error:i},{status:500})}}async function De(e,n,t){let r=n.method.toUpperCase();return r!=="GET"&&r!=="POST"?Response.json({error:"Method not allowed"},{status:405}):bn(e,n,t)}import{createHmac as br,timingSafeEqual as wr}from"crypto";async function Me(e,n,t){for(let r of e){if(r.id!==n)continue;let i=r.oauthWebhookTenantLinkResolver;return i?i(t):null}return null}import{createCipheriv as Vn,createDecipheriv as Qn,randomBytes as Fe,scrypt as ir}from"crypto";import{promisify as sr}from"util";var Yn=sr(ir),Ne="aes-256-gcm",Xn=12,Ue=16,ar=16,Te=32;function D(){return Fe(Te).toString("base64")}async function M(e,n){let t=Fe(ar),r=await Yn(n,t,Te),i=Fe(Xn),o=Vn(Ne,r,i,{authTagLength:Ue}),s=Buffer.concat([o.update(e,"utf8"),o.final()]),a=o.getAuthTag();return[t.toString("base64"),i.toString("base64"),a.toString("base64"),s.toString("base64")].join(":")}async function F(e,n){let[t,r,i,o]=e.split(":");if(!t||!r||!i||!o)throw new Error("Invalid encrypted DEK format");let s=Buffer.from(t,"base64"),a=Buffer.from(r,"base64"),c=Buffer.from(i,"base64"),l=Buffer.from(o,"base64"),d=await Yn(n,s,Te),u=Qn(Ne,d,a,{authTagLength:Ue});return u.setAuthTag(c),Buffer.concat([u.update(l),u.final()]).toString("utf8")}function wn(e,n){let t=Buffer.from(n,"base64"),r=Fe(Xn),i=Vn(Ne,t,r,{authTagLength:Ue}),o=Buffer.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return[r.toString("base64"),s.toString("base64"),o.toString("base64")].join(":")}function xe(e,n){let[t,r,i]=e.split(":");if(!t||!r||!i)throw new Error("Invalid encrypted data format");let o=Buffer.from(n,"base64"),s=Buffer.from(t,"base64"),a=Buffer.from(r,"base64"),c=Buffer.from(i,"base64"),l=Qn(Ne,o,s,{authTagLength:Ue});return l.setAuthTag(a),Buffer.concat([l.update(c),l.final()]).toString("utf8")}function ne(e,n){let t={};for(let[r,i]of Object.entries(e))t[r]=wn(i,n);return t}function J(e,n){let t={};for(let[r,i]of Object.entries(e))t[r]=xe(i,n);return t}function Pe(e,n,t){let r=J(e,n);return ne(r,t)}var ce={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"]}};function et(e,n,t){let r={};for(let i of t)r[`get_${i}`]=async()=>(await e())[i]??null,r[`set_${i}`]=async o=>{let s=[null,void 0,""].includes(o)?null:o;await n({[i]:s})};return r}var Cn=e=>{if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e};function N(e){let{authType:n,integrationName:t,kek:r,database:i,extraIntegrationFields:o=[]}=e,s=[...ce[n].integration,...o],a=null,c={kek:r,integrationName:t,getIntegration:async()=>{if(a)return a;let p=await i.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!p)throw new Error(`Integration "${t}" not found. Make sure to create the integration first.`);return a={id:p.id,config:Cn(p.config),dek:p.dek??null},a},updateIntegration:async p=>{let y=await c.getIntegration();await i.db.updateTable("corsair_integrations").set({...p.config!==void 0?{config:p.config}:{},...p.dek!==void 0?{dek:p.dek}:{},updated_at:new Date}).where("id","=",y.id).execute(),a=null}},l=null,d=async()=>{if(l)return l;let p=await c.getIntegration();if(!p.dek)throw new Error(`No DEK found for integration "${t}". Initialize the integration first.`);return l=await F(p.dek,r),l},u=async()=>{let p=await c.getIntegration(),y=await d(),m=p.config;return!m||Object.keys(m).length===0?{}:J(m,y)};return{get_dek:d,issue_new_dek:async()=>{let p=await c.getIntegration(),y=D(),m={};if(p.dek){let T=await F(p.dek,r),k=p.config;k&&Object.keys(k).length>0&&(m=Pe(k,T,y))}let w=await M(y,r);return await c.updateIntegration({config:m,dek:w}),l=y,y},...et(u,async p=>{let y=await d(),m;try{m=await u()}catch(k){console.error(`[corsair] Failed to decrypt config for integration "${t}", starting fresh:`,k),m={}}let w={...m};for(let[k,h]of Object.entries(p))h===null?delete w[k]:w[k]=h;let T=ne(w,y);await c.updateIntegration({config:T})},s)}}function Z(e){let{authType:n,integrationName:t,tenantId:r,kek:i,database:o,extraAccountFields:s=[]}=e,a=[...ce[n].account,...s],c=null,l=null,d=async()=>{if(l)return l;let h=await o.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!h)throw new Error(`Integration "${t}" not found. Make sure to create the integration first.`);return l={id:h.id,config:Cn(h.config),dek:h.dek??null},l},u={kek:i,integrationName:t,tenantId:r,getIntegration:d,getAccount:async()=>{if(c)return c;let h=await d(),b=await o.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",r).where("integration_id","=",h.id).executeTakeFirst();if(!b)throw new Error(`Account not found for tenant "${r}" and integration "${t}". Make sure to create the account first.`);return c={id:b.id,config:Cn(b.config),dek:b.dek??null},c},updateAccount:async h=>{let b=await u.getAccount();await o.db.updateTable("corsair_accounts").set({...h.config!==void 0?{config:h.config}:{},...h.dek!==void 0?{dek:h.dek}:{},updated_at:new Date}).where("id","=",b.id).execute(),c=null}},g=null,f=null,p=async()=>{if(g)return g;let h=await u.getAccount();if(!h.dek)throw new Error(`No DEK found for account (tenant: "${r}", integration: "${t}"). Initialize the account first.`);return g=await F(h.dek,i),g},y=async()=>{if(f)return f;let h=await u.getIntegration();if(!h.dek)throw new Error(`No DEK found for integration "${t}". Initialize the integration first.`);return f=await F(h.dek,i),f},m=async()=>{let h=await u.getAccount(),b=await p(),C=h.config;return!C||Object.keys(C).length===0?{}:J(C,b)},w=async()=>{let h=await u.getIntegration(),b=await y(),C=h.config;return!C||Object.keys(C).length===0?{}:J(C,b)},k={get_dek:p,issue_new_dek:async()=>{let h=await u.getAccount(),b=D(),C={};if(h.dek){let S=await F(h.dek,i),E=h.config;E&&Object.keys(E).length>0&&(C=Pe(E,S,b))}let I=await M(b,i);return await u.updateAccount({config:C,dek:I}),g=b,b},...et(m,async h=>{let b=await p(),C;try{C=await m()}catch(E){console.error(`[corsair] Failed to decrypt config for account (tenant: "${r}", integration: "${t}"), starting fresh:`,E),C={}}let I={...C};for(let[E,P]of Object.entries(h))P===null?delete I[E]:I[E]=P;let S=ne(I,b);await u.updateAccount({config:S})},a)};return n==="oauth_2"&&(k.get_integration_credentials=async()=>{let h=await w();return{client_id:h.client_id||null,client_secret:h.client_secret||null,redirect_url:h.redirect_url??null}}),k}async function nt(e,n,t){let r=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!r)throw new Error(`Integration "${n}" not found.`);let i=D(),o=await M(i,t);return await e.db.updateTable("corsair_integrations").set({dek:o,updated_at:new Date}).where("id","=",r.id).execute(),i}async function tt(e,n,t,r){let i=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!i)throw new Error(`Integration "${n}" not found.`);let o=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t).where("integration_id","=",i.id).executeTakeFirst();if(!o)throw new Error(`Account not found for tenant "${t}" and integration "${n}".`);let s=D(),a=await M(s,r);return await e.db.updateTable("corsair_accounts").set({dek:a,updated_at:new Date}).where("id","=",o.id).execute(),s}var rt=e=>{if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e};async function cr(e){let n=await e.database.db.selectFrom("corsair_integrations").selectAll().where("name","=",e.pluginId).executeTakeFirst();if(!n)throw new Error(`Integration '${e.pluginId}' not found. Run setupCorsair before registering webhook tenant links.`);let t=await e.database.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",e.tenantId).where("integration_id","=",n.id).executeTakeFirst();if(!t)throw new Error(`Account not found for tenant '${e.tenantId}' and integration '${e.pluginId}'.`);return{integrationId:n.id,accountId:t.id}}async function ur(e){let n=await e.database.db.selectFrom("corsair_accounts").selectAll().where("id","=",e.accountId).executeTakeFirst();if(!n?.dek)throw new Error(`Account '${e.accountId}' has no DEK.`);let t=await F(n.dek,e.kek),r=rt(n.config),i={};Object.keys(r).length>0&&(i=J(r,t)),i[e.link.linkType]=e.link.externalId;let o=ne(i,t);await e.database.db.updateTable("corsair_accounts").set({config:o,updated_at:new Date}).where("id","=",n.id).execute()}async function fe(e){let{database:n,kek:t,pluginId:r,tenantId:i,link:o,authType:s,extraAccountFields:a=[]}=e,{accountId:c}=await cr({database:n,pluginId:r,tenantId:i}),l=!1;if(s){let d=Z({authType:s,integrationName:r,tenantId:i,kek:t,database:n,extraAccountFields:a}),u=`set_${o.linkType}`,g=d[u];typeof g=="function"&&(await g(o.externalId),l=!0)}l||await ur({database:n,kek:t,accountId:c,link:o})}async function Tn(e){let{database:n,kek:t,pluginId:r,linkType:i,externalId:o}=e,s=await n.db.selectFrom("corsair_accounts as accounts").innerJoin("corsair_integrations as integrations","integrations.id","accounts.integration_id").selectAll("accounts").where("integrations.name","=",r).execute();for(let a of s)if(a.dek)try{let c=await F(a.dek,t),d=rt(a.config)[i];if(!d)continue;if(xe(d,c)===o)return a}catch{continue}return null}async function $e(e){return(await Tn(e))?.tenant_id??null}async function ot(e){return $e({database:e.database,kek:e.kek,pluginId:e.pluginId,linkType:e.match.linkType,externalId:e.match.externalId})}var te=class extends Error{code;constructor(n,t){super(t),this.name="ManagedOAuthDeliveryError",this.code=n}};function dr(e){let n=e[x];if(!n)throw new te("invalid_corsair_instance","Invalid corsair instance");return n}function lr(e,n){let t=e.plugins.find(r=>r.id===n);if(!t)throw new te("plugin_not_found",`Plugin '${n}' not found`);return t}async function pr(e,n,t,r){let i=ve(e),o=await i.integrations.findByName(n);if(!o)throw new Error(`Integration '${n}' not found. Run setupCorsair first.`);if(await i.accounts.findOne({tenant_id:t,integration_id:o.id}))return;let a=D(),c=await M(a,r);await i.accounts.create({tenant_id:t,integration_id:o.id,config:{},dek:c})}async function ye(e,n){let{plugin:t,tenantId:r,accessToken:i,refreshToken:o,expiresIn:s,scope:a}=n;if(!i.trim())throw new te("no_access_token","Managed OAuth delivery missing access_token");let c=dr(e);if(!c.database)throw new te("no_database","No database configured on corsair instance");let l=lr(c,t);await pr(c.database,t,r,c.kek);let d=Z({authType:"managed",integrationName:t,tenantId:r,kek:c.kek,database:c.database});await d.set_access_token(i),o&&await d.set_refresh_token(o),s&&await d.set_expires_at(String(Math.floor(Date.now()/1e3)+s)),a&&await d.set_scope(a);try{let u=await Me(c.plugins,t,{access_token:i,refresh_token:o,scope:a});if(u)try{let g=l.authConfig?.managed?.account??[];await fe({database:c.database,kek:c.kek,pluginId:t,tenantId:r,link:u,authType:"managed",extraAccountFields:g})}catch(g){console.warn(`[corsair:managed-oauth] Failed to persist webhook tenant link for '${t}' tenant '${r}':`,g)}}catch(u){console.warn(`[corsair:managed-oauth] Failed to resolve webhook tenant link for '${t}' tenant '${r}':`,u)}return{plugin:t,tenantId:r}}function gr(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function it(e,n,t=[]){for(let[r,i]of Object.entries(e))if(gr(i)){if(i.match(n))return{webhook:i,path:[...t,r]}}else if(i&&typeof i=="object"){let o=it(i,n,[...t,r]);if(o)return o}return null}function fr(e){let n={};for(let[t,r]of Object.entries(e))n[t.toLowerCase()]=Array.isArray(r)?r[0]:r;return n}function yr(e){let n=e["x-goog-resource-uri"],t=e["x-goog-channel-id"];if(!n||!t)return null;let r={resourceId:e["x-goog-resource-id"]||"",resourceState:e["x-goog-resource-state"]||"",resourceUri:n,channelId:t,channelExpiration:e["x-goog-channel-expiration"]||""};return n.includes("/drive/")&&(r.kind="drive#change"),{message:{data:Buffer.from(JSON.stringify(r)).toString("base64"),messageId:e["x-goog-message-number"]||""}}}async function st(e,n,t,r){let i=fr(n),o=typeof t=="string"?JSON.parse(t):t;(!o||typeof o=="object"&&Object.keys(o).length===0)&&i["x-goog-resource-uri"]&&(o=yr(i)||o);let a={headers:i,body:o,...r?{query:r}:{}},c=r?.tenantId||"default",l=e.withTenant?e.withTenant(c):e,d=Ie;for(let u of d){let g=l[u];if(!g||!g.webhooks||g.pluginWebhookMatcher&&!g.pluginWebhookMatcher(a))continue;let f=it(g.webhooks,a);if(!f)continue;let p=f.path.join("."),y={payload:o,headers:i,rawBody:typeof t=="string"?t:JSON.stringify(t),...r?{query:r}:{}};try{let m=await f.webhook.handler(y),w=!!Object.keys(m.returnToSender||{})?.length;return{plugin:u,action:p,body:o,response:w?{...m?.returnToSender,success:!0}:{success:!0},...m.responseHeaders&&{responseHeaders:m.responseHeaders}}}catch(m){return console.error(`Error executing webhook handler for ${u}.${p}:`,m),{plugin:u,action:p,body:o,response:{success:!1,error:m instanceof Error?m.message:"Unknown error"}}}}return{plugin:null,action:null,body:null}}import{createHmac as hr,timingSafeEqual as mr}from"crypto";function Be(e){return e.deliveryMode==="permission.approve"||e.deliveryMode==="permission.deny"}function We(e){return e.deliveryMode==="oauth.tokens"||typeof e.accessToken=="string"&&e.accessToken.length>0}function at(e){let n=e.trim();return n.length>0?n:null}function kr(e,n){let t=at(n);if(!t)throw new Error("Signing secret is required for browser delivery tokens");return hr("sha256",t).update(e).digest("base64url")}function Le(e,n){let t=at(n);if(!t)return null;let r=e.split(".");if(r.length!==2)return null;let[i,o]=r;if(!i||!o)return null;let s=kr(i,t);try{if(!mr(Buffer.from(o,"utf8"),Buffer.from(s,"utf8")))return null}catch{return null}let a;try{a=JSON.parse(Buffer.from(i,"base64url").toString("utf8"))}catch{return null}return a.exp*1e3<Date.now()?null:a}function ct(e){let n=e[x];if(!n)throw new Error("Invalid corsair instance");return n}function Cr(e,n){if(e instanceof Headers)return e.get(n)??void 0;let t=e[n]??e[n.toLowerCase()];return Array.isArray(t)?t[0]:typeof t=="string"?t:void 0}function Tr(e){if(e)return e.startsWith("sha256=")?e.slice(7):e}function xr(e,n,t){if(!t.trim()||!n)return!1;let r=br("sha256",t.trim()).update(e).digest("hex");try{return wr(Buffer.from(r,"utf8"),Buffer.from(n,"utf8"))}catch{return!1}}async function Pr(e,n,t){let r=typeof t.tenantId=="string"?t.tenantId:typeof t.query?.tenantId=="string"?t.query.tenantId:void 0;return r||(!n.database||!t.plugin||!t.linkType||!t.externalId?void 0:await $e({database:n.database,kek:n.kek,pluginId:t.plugin,linkType:t.linkType,externalId:t.externalId})??void 0)}async function Ar(e,n,t){let r=await Pr(e,n,t),i={...t.query??{},...r?{tenantId:r}:{}},o=await st(e,t.headers,t.body,i);if(!o.plugin)return{status:"failed",retryable:!1,error:"No matching webhook handler found"};if(o.response&&o.response.success===!1)return{status:"failed",retryable:!1,error:typeof o.response.error=="string"?o.response.error:"Webhook handler failed"};let s=o.response?.returnToSender,a=s&&typeof s=="object"&&typeof s.validationToken=="string"&&Object.keys(s).length===1?s.validationToken:s||(o.response?.data??o.response);return{status:"ok",webhookResponse:{status:o.response?.statusCode??200,body:a,headers:o.responseHeaders}}}async function Rr(e,n){return await Ae(e,n),{status:"ok"}}async function vr(e,n){return await ye(e,{plugin:n.plugin,tenantId:n.tenantId,accessToken:n.accessToken,refreshToken:n.refreshToken,expiresIn:n.expiresIn,scope:n.scope}),{status:"ok"}}async function Pn(e,n,t){let r=await xn(e,{token:n},t);if(r.status!=="ok")throw new Error(r.error??"Permission decision failed")}async function xn(e,n,t){let r=ct(e),i=n.token?.trim();if(!i)return{status:"failed",retryable:!1,error:"Permission token is required"};if(!r.database)return{status:"failed",retryable:!1,error:"Database not configured"};let o=new Date().toISOString(),s=await r.database.db.selectFrom("corsair_permissions").selectAll().where("token","=",i).executeTakeFirst();return s?s.status!=="pending"?{status:"ok"}:s.expires_at<o?(await r.database.db.updateTable("corsair_permissions").set({status:"expired",updated_at:new Date}).where("id","=",s.id).execute(),{status:"failed",retryable:!1,error:"Permission has expired"}):(await r.database.db.updateTable("corsair_permissions").set({status:t,updated_at:new Date}).where("id","=",s.id).execute(),{status:"ok"}):{status:"failed",retryable:!1,error:"Permission not found"}}async function An(e,n,t={}){let r=ct(e),i=Tr(Cr(n.headers,"x-corsair-signature"));if(t.signingSecret?.trim()){if(!xr(n.body,i,t.signingSecret))return{status:"failed",retryable:!1,error:"Invalid tunnel signature"}}else if(!t.allowUnsignedTunnel)return{status:"failed",retryable:!1,error:"Tunnel signing secret is required"};let o;try{o=JSON.parse(n.body)}catch{return{status:"failed",retryable:!1,error:"Invalid tunnel envelope JSON"}}switch(o.type){case"webhook":return Ar(e,r,o.payload);case"oauth.callback":return Rr(e,o.payload);case"oauth.tokens":return vr(e,o.payload);case"permission.approve":return xn(e,o.payload,"approved");case"permission.deny":return xn(e,o.payload,"denied");default:return{status:"failed",retryable:!1,error:`Unsupported tunnel type: ${o.type}`}}}async function je(e,n){let t=z(e),i=new URL(n).searchParams.get("d");if(!i)return{type:"json",status:200,body:{status:"ok",message:"Corsair tunnel endpoint is active",timestamp:new Date().toISOString()}};let o=Le(i,t.signingSecret);if(!o)return{type:"json",status:400,body:{error:"Invalid or expired delivery token"}};try{if(Be(o)){if(!o.permissionToken)return{type:"json",status:400,body:{error:"Permission delivery missing permission token"}};await Pn(e,o.permissionToken,o.deliveryMode==="permission.approve"?"approved":"denied")}else if(We(o)){if(!o.accessToken)return{type:"json",status:400,body:{error:"Managed OAuth delivery missing access_token"}};await ye(e,{plugin:o.plugin,tenantId:o.tenantId,accessToken:o.accessToken,refreshToken:o.refreshToken,expiresIn:o.expiresIn,scope:o.scope})}else{if(!o.code||!o.state||!o.redirectUri)return{type:"json",status:400,body:{error:"Invalid BYO OAuth delivery token"}};await Ae(e,{code:o.code,state:o.state,redirectUri:o.redirectUri})}}catch(s){return{type:"json",status:400,body:{error:s instanceof Error?s.message:"Hub delivery failed"}}}return{type:"redirect",url:o.hubSuccessUrl}}async function Ke(e,n){let t=z(e),r=await An(e,n,{signingSecret:t.signingSecret});if(r.status!=="ok")return{type:"json",status:r.retryable===!1?400:502,body:{error:r.error??"Tunnel processing failed"}};let i=r.webhookResponse;if(!i)return{type:"json",status:200,body:{status:"ok"}};let o=i.status??200,s=i.headers;return i.body&&typeof i.body=="object"&&!(i.body instanceof ArrayBuffer)?{type:"json",status:o,body:i.body,headers:s}:{type:"text",status:o,body:typeof i.body=="string"?i.body:i.body?JSON.stringify(i.body):null,headers:s}}function Rn(e){if(e.type==="redirect")return Response.redirect(e.url,302);let n=new Headers;for(let[t,r]of Object.entries(e.headers??{}))typeof r=="string"&&n.set(t,r);return e.type==="json"?Response.json(e.body,{status:e.status,headers:n}):new Response(e.body,{status:e.status,headers:n})}async function vn(e,n){return n.method==="GET"?je(e,n.url):Ke(e,{headers:n.headers,body:n.body??""})}async function In(e,n){try{let t=await vn(e,n);return Rn(t)}catch(t){if(t instanceof G)return Response.json({error:t.message},{status:503});throw t}}async function Ze(e,n){let t=n.method.toUpperCase();return t!=="GET"&&t!=="POST"?Response.json({error:"Method not allowed"},{status:405}):In(e,{method:t,url:n.url,headers:n.headers,body:t==="POST"?await n.text():void 0})}var V=class extends Error{pluginId;authType;constructor(n,t,r){super(r??`[auth-missing:${n}:${t}]`),Object.setPrototypeOf(this,new.target.prototype),this.name="AuthMissingError",this.pluginId=n,this.authType=t}};var Ir=300;async function Sr(e){let n=await e.text();if(!n)return null;try{return JSON.parse(n)}catch{throw new Error(`Hub API returned invalid JSON (HTTP ${e.status})`)}}function Er(e,n){if(e&&typeof e=="object"){let t=e;if(t.error)return t.error;if(t.message)return t.message}return`Hub token refresh failed (HTTP ${n})`}async function Sn(e,n){let{keys:t,hub:r,plugin:i,tenantId:o}=e,s=n?.forceRefresh??!1,[a,c,l]=await Promise.all([t.get_access_token(),t.get_expires_at(),t.get_refresh_token()]);if(!a&&!l)throw new V(i,"managed");let d=Math.floor(Date.now()/1e3);if(!s&&a&&c&&Number(c)>d+Ir)return{accessToken:a,expiresAt:Number(c),refreshed:!1};if(!l&&a&&!s)return{accessToken:a,expiresAt:c?Number(c):d+3600,refreshed:!1};let u=r.apiUrl.replace(/\/$/,""),g=await fetch(`${u}/oauth/refresh`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r.projectApiKey}`},body:JSON.stringify({plugin:i,tenantId:o})}),f=await Sr(g);if(!g.ok)throw new Error(Er(f,g.status));let p=f;if(!p.access_token)throw new Error("Hub token refresh returned no access_token");let y=p.expires_in?d+p.expires_in:c?Number(c):d+3600;return await t.set_access_token(p.access_token),await t.set_expires_at(String(y)),p.refresh_token&&await t.set_refresh_token(p.refresh_token),p.scope&&await t.set_scope(p.scope),{accessToken:p.access_token,expiresAt:y,refreshed:!0}}async function ut(e,n){e._refreshAuth=async()=>(await Sn(n,{forceRefresh:!0})).accessToken}function qe(e){return typeof e=="string"&&e.length>0}function _r(e){if(!e||typeof e!="object")throw new Error("Hub API returned an empty permission session");let n=e;if(!qe(n.approvalUrl)||!qe(n.token)||!qe(n.projectId)||!qe(n.expiresAt))throw new Error("Hub API returned an incomplete permission session (expected approvalUrl, token, projectId, and expiresAt)");return{approvalUrl:n.approvalUrl,token:n.token,projectId:n.projectId,expiresAt:n.expiresAt}}function Or(e,n){if(n===404)return"Hub REST API not found at /permission/sessions. Check HUB_API_URL and ensure the Hub API is deployed.";if(e&&typeof e=="object"){let t=e;if(t.error)return t.error;if(t.message)return t.message}return`Hub API returned HTTP ${n}`}async function Hr(e){let n=e.headers.get("content-type")??"",t=await e.text();if(!t)return null;if(!n.includes("application/json")&&t.trimStart().startsWith("<"))throw new Error(`Hub API returned HTML instead of JSON (HTTP ${e.status}). Check HUB_API_URL and deploy the latest hub API.`);try{return JSON.parse(t)}catch{throw new Error(`Hub API returned invalid JSON (HTTP ${e.status})`)}}async function En(e,n){let t=e.apiUrl.replace(/\/$/,""),r=await fetch(`${t}/permission/sessions`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.projectApiKey}`},body:JSON.stringify({permissionId:n.permissionId,permissionToken:n.permissionToken,plugin:n.plugin,endpoint:n.endpoint,args:n.args,tenantId:n.tenantId,deliveryUrl:e.deliveryUrl,expiresAt:n.expiresAt})}),i=await Hr(r);if(!r.ok)throw new Error(Or(i,r.status));return _r(i)}function _n(e){return`Approval required. Visit ${e} to approve or deny, then tell the agent to retry this action.`}function dt(e,n){return{delivery:t=>Ze(e,t),createConnectSession:t=>De(e,t,n)}}function Ge(e,n){let t=[];e||t.push("database"),n||t.push("kek");let r={};return new Proxy(r,{get(i,o){let s=t.length>1;throw new Error(`corsair.keys.${String(o)}: Cannot access keys because ${t.join(" and ")} ${s?"are":"is"} not configured. Provide both 'database' and 'kek' in createCorsair() to enable key management.
|
|
2
|
-
|
|
3
|
-
To generate a KEK, run: openssl rand -base64 ${Te}`)}})}var Dr=async(e,n)=>(console.error(`[corsair:${n.pluginId}:${n.operation}]`,{error:e.message,input:n.input}),{maxRetries:0});async function lt(e,n,t,r,i){let o={pluginId:n,operation:t,input:r,originalError:e},s=Object.keys(i).find(l=>i[l]?.match(e,o));return await(i[s||"DEFAULT"]?.handler||Dr)(e,o)}import{randomBytes as Mr}from"crypto";import{v4 as Fr}from"uuid";var Nr={open:{read:"allow",write:"allow",destructive:"allow"},cautious:{read:"allow",write:"allow",destructive:"require_approval"},strict:{read:"allow",write:"require_approval",destructive:"deny"},readonly:{read:"allow",write:"deny",destructive:"deny"}};function Ur(e,n,t){return t!==void 0?t:Nr[n][e]}function On(e){let n=/(\d+)(d|h|m|s)/g,t=0,r;for(;(r=n.exec(e))!==null;){let i=parseInt(r[1],10);switch(r[2]){case"d":t+=i*864e5;break;case"h":t+=i*36e5;break;case"m":t+=i*6e4;break;case"s":t+=i*1e3;break}}return t>0?t:600*1e3}function gt(e){return{async find_by_permission_id(n){if(e)return e.db.selectFrom("corsair_permissions").selectAll().where("id","=",n).executeTakeFirst()},async find_by_token(n){if(e)return e.db.selectFrom("corsair_permissions").selectAll().where("token","=",n).executeTakeFirst()},async set_executing(n){e&&await e.db.updateTable("corsair_permissions").set({status:"executing",updated_at:new Date}).where("id","=",n).execute()},async set_completed(n){e&&await e.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",n).execute()}}}async function pt(e,n,t){let r=Date.now()+t;for(;Date.now()<r;){let i=await e.db.selectFrom("corsair_permissions").select(["id","status"]).where("id","=",n).executeTakeFirst();if(!i)return{result:"blocked",reason:"pending"};if(i.status==="approved")return{result:"allow",onComplete:async()=>{await e.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",n).execute()}};if(i.status==="denied")return{result:"blocked",reason:"denied"};if(i.status==="expired"||i.status==="failed")return{result:"blocked",reason:"timeout"};await new Promise(o=>setTimeout(o,500))}return{result:"blocked",reason:"timeout"}}async function ft(e){let n=Ur(e.riskLevel,e.mode,e.override);if(n==="allow")return{result:"allow"};let t=e.meta?.irreversible?" (irreversible)":"",r=e.meta?.description?`${e.meta.description}${t}`:`${e.pluginId}.${e.endpointPath}${t}`;if(n==="deny"||!e.db)return console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 denied by permission mode '${e.mode}'.`,`
|
|
4
|
-
Action: ${r}`,`
|
|
5
|
-
To allow this, update the permission mode or add an override in your corsair config.`),{result:"blocked",reason:"policy"};let i=JSON.stringify(e.args),o=new Date().toISOString(),s=e.tenantId??"default",a=await e.db.db.selectFrom("corsair_permissions").selectAll().where("plugin","=",e.pluginId).where("endpoint","=",e.endpointPath).where("args","=",i).where("tenant_id","=",s).where("expires_at",">",o).where("status","in",["pending","approved","executing"]).orderBy("created_at","desc").limit(1).executeTakeFirst();if(a){if(a.status==="approved"){let p=e.db,y=a.id;return{result:"allow",onComplete:async()=>{await p.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",y).execute()}}}return a.status==="executing"?{result:"allow"}:(console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval already pending.`,`
|
|
6
|
-
Action: ${r}`,`
|
|
7
|
-
Permission ID: ${a.id}`,`
|
|
8
|
-
Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?pt(e.db,a.id,e.timeoutMs??600*1e3):{result:"blocked",reason:"pending",id:a.id,token:a.token,expiresAt:a.expires_at})}let c=Fr(),l=Mr(32).toString("hex"),d=e.timeoutMs??600*1e3,u=new Date(Date.now()+d).toISOString();return await e.db.db.insertInto("corsair_permissions").values({id:c,created_at:new Date,updated_at:new Date,token:l,plugin:e.pluginId,endpoint:e.endpointPath,args:i,tenant_id:s,status:"pending",expires_at:u}).execute(),console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval required.`,`
|
|
9
|
-
Action: ${r}`,`
|
|
10
|
-
Permission ID: ${c}`,`
|
|
11
|
-
Permission token: ${l}`,`
|
|
12
|
-
Expires at: ${u}`,`
|
|
13
|
-
Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?pt(e.db,c,d):{result:"blocked",reason:"pending",id:c,token:l,expiresAt:u}}function $r(e){return typeof e=="function"}function Br(e,n,t){let r=ee(K(e,n.tenantId??t??"default"),n.kek),i=new URL(n.baseUrl);i.searchParams.set("state",r);let o=i.toString(),s=n.onAuthMissing?n.onAuthMissing({plugin:e,connectUrl:o,state:r}):`[auth-missing:${e}] Authentication required. Direct the user to connect their account: ${o}`;return new Error(s)}function Hn({endpoints:e,hooks:n,ctx:t,tree:r,pluginId:i,errorHandlers:o,currentPath:s=[],keyBuilder:a,permissionsConfig:c,endpointMeta:l,database:d,approvalConfig:u,tenantId:g,connectConfig:f,hubConfig:p}){for(let[y,m]of Object.entries(e)){let w=n?.[y];if($r(m)){let T=w,k=[...s,y].join("."),h=async(b={})=>{let C;if(c){let v=l?.[k],{result:pe,reason:L,onComplete:ke,token:j,id:X,expiresAt:H}=await ft({pluginId:i,endpointPath:k,args:b,mode:c.mode,override:c.overrides?.[k],riskLevel:v?.riskLevel??"write",meta:v,db:d,timeoutMs:u?On(u.timeout):void 0,tenantId:g,approvalMode:u?.mode});if(pe==="blocked"){let _;if(L==="denied")_=`Action '${k}' was denied by the user. Await further instructions before proceeding.`;else if(L==="policy")_=`Action '${k}' is blocked by the permission policy. Update the corsair config to allow it.`;else if(L==="timeout")_=`Action '${k}' timed out waiting for approval.`;else if(j&&X)if(u?.formatAsyncMessage)_=u.formatAsyncMessage({token:j,id:X,plugin:i,endpoint:k,args:b});else if(p)try{let ie=u?On(u.timeout):6e5,ln=await En(p,{permissionId:X,permissionToken:j,plugin:i,endpoint:k,args:b,tenantId:g??"default",expiresAt:H??new Date(Date.now()+ie).toISOString()});_=_n(ln.approvalUrl)}catch(ie){let ln=ie instanceof Error?ie.message:String(ie);_=`Action '${k}' requires user approval before it can run. Could not create approval link: ${ln}`}else _=`Action '${k}' requires user approval before it can run.`;else _=`Action '${k}' requires user approval before it can run.`;throw new Error(_)}C=ke}let I=async(v,pe,L)=>{try{return await m(pe,L)}catch(ke){if(ke instanceof Error){let j=await lt(ke,i,k,typeof L=="object"&&L!==null?L:{args:L},o);if(v<(j.maxRetries||0)){let X=v+1;console.log(`Retrying (${X} / ${j.maxRetries})...`);let H;if(j.headersRetryAfterMs)H=j.headersRetryAfterMs;else switch(j.retryStrategy){case"exponential_backoff":H=Math.pow(2,X-1)*1e3;break;case"exponential_backoff_jitter":let _=Math.pow(2,X-1)*1e3,ie=(Math.random()-.5)*1e3;H=Math.max(0,_+ie);break;case"linear_1s":H=1e3;break;case"linear_2s":H=2e3;break;case"linear_3s":H=3e3;break;case"linear_4s":H=4e3;break;default:H=1e3;break}await new Promise(_=>setTimeout(_,H)),await I(X,pe,L),console.log(`[corsair:${i}:${k}] Retry strategy:`,j)}}throw ke}},S;try{S=a?await a(t,"endpoint"):void 0}catch(v){throw f?.oauthConfig&&f.kek&&v instanceof V&&v.authType==="oauth_2"?Br(i,f,g):v}if(!T?.before&&!T?.after){let v=await I(0,{...t,key:S},b);return await C?.(),v}let E={...t,key:S},P=T.before?await T.before(E,b):{ctx:E,args:b,continue:!0,passToAfter:void 0};if(P.continue===!1)return;let le=await I(0,P.ctx,P.args);return await T.after?.(P.ctx,le,P.passToAfter),await C?.(),le};r[y]=h}else if(m&&typeof m=="object"){let T={};Hn({endpoints:m,hooks:w,ctx:t,tree:T,pluginId:i,errorHandlers:o,currentPath:[...s,y],keyBuilder:a,permissionsConfig:c,endpointMeta:l,database:d,approvalConfig:u,tenantId:g,connectConfig:f,hubConfig:p}),r[y]=T}}}function Wr(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function Dn({webhooks:e,hooks:n,ctx:t,webhooksTree:r,keyBuilder:i}){for(let[o,s]of Object.entries(e)){let a=n?.[o];if(Wr(s)){let c=a,l=async d=>{let u=(f,p)=>s.handler(f,p),g=i?await i(t,"webhook"):void 0;return!c?.before&&!c?.after?u({...t,key:g},d):(async()=>{let f={...t,key:g},p=c.before?await c.before(f,d):{ctx:f,args:d,continue:!0,passToAfter:void 0};if(p.continue===!1)return;let y=await u(p.ctx,p.args);return y?.success===!0&&await c.after?.(p.ctx,y,p.passToAfter),y})()};r[o]={match:s.match,handler:l}}else if(s&&typeof s=="object"){let c={};Dn({webhooks:s,hooks:a,ctx:t,webhooksTree:c,keyBuilder:i}),r[o]=c}}}function Lr(e,n,t){let r=null;return async()=>{if(r)return r;if(!e)throw new Error("Database not configured");let i=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!i)throw new Error(`Integration "${n}" not found. Make sure to create the integration first.`);let o=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t).where("integration_id","=",i.id).executeTakeFirst();if(!o)throw new Error(`Account not found for tenant "${t}" and integration "${n}". Make sure to create the account first.`);return r=o.id,r}}function jr(e,n,t,r,i){return e?pn(e.db,n,t,r,i):{findByEntityId:async()=>null,findById:async()=>null,findManyByEntityIds:async()=>[],list:async()=>[],search:async()=>[],upsertByEntityId:async()=>{throw new Error("Database not configured")},deleteById:async()=>!1,deleteByEntityId:async()=>!1,count:async()=>0}}function Mn(e,n){let{database:t,tenantId:r,kek:i,rootErrorHandlers:o,approvalConfig:s,connectConfig:a,hubConfig:c}=n,l={},d={};for(let u of e)l[u.id]={},d[u.id]={};for(let u of e){let g=u.schema,f=r??"default",p=Lr(t,u.id,f);if(g?.entities){let P={};for(let[le,v]of Object.entries(g.entities)){let pe=t?pn(t.db,p,le,g.version,v):jr(void 0,p,le,g.version,v);P[le]=pe}d[u.id].db=P,l[u.id].db=P}let y=u.options,m=u.authConfig,w;if(t&&i&&y?.authType){let P=m?.[y.authType]?.account??[];w=Z({authType:y.authType,integrationName:u.id,tenantId:f,kek:i,database:t,extraAccountFields:P}),l[u.id].keys=w}let T={database:t,db:d[u.id]?.db??{},$getAccountId:p,...u.options?{options:u.options}:{},...w?{keys:w,authType:y?.authType}:{},tenantId:f,...c?{hub:c}:{}},k=u.endpoints??{},h=u.hooks,b={...o,...u.errorHandlers},C={},I=u.options?.permissions;Hn({endpoints:k,hooks:h,ctx:T,tree:C,pluginId:u.id,errorHandlers:b,currentPath:[],keyBuilder:u.keyBuilder,permissionsConfig:I,endpointMeta:u.endpointMeta,database:t,approvalConfig:s,tenantId:r,connectConfig:a?{...a,oauthConfig:u.oauthConfig,kek:i,tenantId:f}:void 0,hubConfig:c}),Object.keys(C).length>0&&(l[u.id].api=C),T.endpoints=C;let S=u.webhooks??{},E=u.webhookHooks;if(Object.keys(S).length>0){let P={};Dn({webhooks:S,hooks:E,ctx:T,webhooksTree:P,keyBuilder:u.keyBuilder}),l[u.id].webhooks=P,u.pluginWebhookMatcher&&(l[u.id].pluginWebhookMatcher=u.pluginWebhookMatcher),u.pluginTenantWebhookMatcher&&(l[u.id].pluginTenantWebhookMatcher=u.pluginTenantWebhookMatcher)}}return l}function yt(e,n,t){let r={};for(let i of e){let o=i.options,s=i.authConfig;if(o?.authType){let a=s?.[o.authType]?.integration??[],c=N({authType:o.authType,integrationName:i.id,kek:t,database:n,extraIntegrationFields:a});r[i.id]=c}}return r}import*as ht from"querystring";var U=class extends Error{code;constructor(n,t){super(t),this.name="ConnectError",this.code=n}};function Kr(e){let n=e[x];if(!n)throw new U("invalid_corsair_instance","Invalid corsair instance");return n}function Zr(e,n){let t=e.plugins.find(r=>r.id===n);if(!t)throw new U("plugin_not_found",`Plugin '${n}' not found`);return t}function qr(e){let n=e.oauthConfig;if(!n)throw new U("plugin_has_no_oauth_config",`Plugin '${e.id}' has no oauthConfig`);return n}async function Fn(e,n){let t=Kr(e);if(!t.database)throw new U("no_database","No database configured on corsair instance");let r=t.connect?.redirectUri;if(!r)throw new U("no_redirect_uri","No redirectUri configured. Set connect.redirectUri in createCorsair().");let i=_e(n,t.kek);if(!i)throw new U("invalid_state","Invalid or tampered state parameter");let{plugin:o,tenantId:s}=i,a=Zr(t,o),c=qr(a),d=await N({authType:"oauth_2",integrationName:o,kek:t.kek,database:t.database}).get_client_id();if(!d)throw new U("client_id_not_configured",`client_id not configured for '${o}'`);let u={...c.authParams,client_id:d,redirect_uri:r,response_type:"code",scope:c.scopes.join(" "),state:n},g=`${c.authUrl}?${ht.stringify(u)}`;return{plugin:o,tenantId:s,providerName:c.providerName,oauthUrl:g,state:n}}var A=class extends Error{status;code;extra;constructor(n,t,r,i={}){super(r??t),this.name="ManagementApiError",this.status=n,this.code=t,this.extra=i}};function R(e,n){return new Response(JSON.stringify(n),{status:e,headers:{"content-type":"application/json"}})}function mt(e){let n={error:e.code,message:e.message,...e.extra};return R(e.status,n)}function re(e){return new A(404,"not_found",e)}function Q(e,n={}){return new A(400,"bad_request",e,n)}function kt(e,n){let t=e.plugins.find(r=>r.id===n);if(!t)throw re(`Plugin '${n}' not found`);return t}async function Nn(e,n){let t=e.options?.authType;if(!t||!n.database||!n.kek)return{configured:!1,missingFields:[]};let r=N({authType:t,integrationName:e.id,kek:n.kek,database:n.database}),i=ce[t].integration,o=r,s;try{s=await Promise.all(i.map(l=>o[`get_${l}`]()))}catch{s=i.map(()=>null)}let a=i.filter((l,d)=>s[d]==null),c;return t==="oauth_2"?c=!a.includes("client_id")&&!a.includes("client_secret"):c=a.length===0,{configured:c,missingFields:a}}async function bt(e,n){let t=e.options?.authType??null,r=e.oauthConfig,{configured:i,missingFields:o}=await Nn(e,n);return{id:e.id,authType:t,configured:i,missingFields:o,oauth:r?{providerName:r.providerName,scopes:r.scopes,requiresRegisteredRedirect:!!r.requiresRegisteredRedirect}:null}}function ze(){return{ok:!0}}async function Je(e){return Promise.all(e.plugins.map(n=>bt(n,e)))}async function Ve(e,n){let t=kt(e,n);return bt(t,e)}async function wt(e,n){return e.database?(await e.database.db.selectFrom("corsair_accounts as a").innerJoin("corsair_integrations as i","i.id","a.integration_id").select(["a.id as accountId","a.dek as dek","i.name as integrationName"]).where("a.tenant_id","=",n).execute()).map(r=>({integrationName:r.integrationName,hasCredentials:!!r.dek})):[]}async function Ct(e,n){let t=await wt(e,n),r=t.filter(i=>i.hasCredentials).map(i=>i.integrationName);return{id:n,accounts:t,connectedPlugins:r}}async function Qe(e){let n=new Map;if(n.set("default",{id:"default",accounts:[],connectedPlugins:[]}),e.database){let t=await e.database.db.selectFrom("corsair_accounts as a").innerJoin("corsair_integrations as i","i.id","a.integration_id").select(["a.tenant_id","a.dek as dek","i.name as integrationName"]).execute();for(let r of t){let i=r.tenant_id;if(!i)continue;let o=n.get(i);o||(o={id:i,accounts:[],connectedPlugins:[]},n.set(i,o));let s=!!r.dek;o.accounts.push({integrationName:r.integrationName,hasCredentials:s}),s&&o.connectedPlugins.push(r.integrationName)}}return[...n.values()]}async function Ye(e,n){if(!n)throw Q("Tenant id must be a non-empty string");return Ct(e,n)}async function Xe(e,n){let t=n?.id?.trim();if(!t)throw Q("Tenant id is required",{missingFields:["id"]});return Ct(e,t)}async function en(e,n){let t=n?.trim()||"default",r={},i=e.database?await wt(e,t):[],o=new Map(i.map(s=>[s.integrationName,s]));for(let s of e.plugins){if(!(await Nn(s,e)).configured){r[s.id]="missing_credentials";continue}let c=o.get(s.id),l;c&&c.hasCredentials?l="connected":l="not_connected",r[s.id]=l}return r}async function nn(e,n){if(!e.database)throw re(`Permission '${n}' not found`);let t=await e.database.db.selectFrom("corsair_permissions").selectAll().where("id","=",n).executeTakeFirst();if(!t)throw re(`Permission '${n}' not found`);return t}function Gr(e){if(!e.oauthConfig)throw Q(`Plugin '${e.id}' has no oauthConfig`)}function Un(e){if(!e.connect)throw new A(500,"connect_not_configured","createCorsair was not given a connect config. Set { connect: { baseUrl, redirectUri } } to enable /connect routes.");return e.connect}async function tn(e,n){let t=n?.plugin?.trim();if(!t)throw Q("Plugin id is required",{missingFields:["plugin"]});let r=n.tenantId?.trim()||"default",i=kt(e,t);Gr(i);let o=Un(e);if(!e.database||!e.kek)throw new A(500,"database_not_configured","A database and kek are required to issue connect links.");let s=await Nn(i,e);if(!s.configured)throw new A(400,"missing_credentials",`Plugin '${t}' is missing OAuth client credentials`,{missingFields:s.missingFields});let a=ee(K(t,r),e.kek),c;try{c=new URL(o.baseUrl)}catch{throw new A(500,"connect_misconfigured","connect.baseUrl is not a valid URL. Set a full URL including protocol (e.g. https://app.example.com/connect).")}return c.searchParams.set("state",a),{connectUrl:c.toString(),state:a}}async function rn(e,n,t){let r=t?.trim();if(!r)throw Q("state is required",{missingFields:["state"]});Un(n);try{return await Fn(e,r)}catch(i){if(i instanceof U)switch(i.code){case"invalid_state":throw Q("Invalid or expired state");case"client_id_not_configured":throw new A(400,"missing_credentials","OAuth client_id is not configured for this plugin",{missingFields:["client_id"]});case"no_redirect_uri":break}throw new A(500,"resolve_failed","Could not resolve connect link. Check server logs for details.")}}async function on(e,n,t){let r=t?.code?.trim(),i=t?.state?.trim(),o=[];if(r||o.push("code"),i||o.push("state"),o.length)throw Q("Missing required fields",{missingFields:o});let s=Un(n),{processOAuthCallback:a}=await import("./oauth.js");try{return await a(e,{code:r,state:i,redirectUri:s.redirectUri})}catch(c){if(c instanceof Error&&c.name==="OAuthCallbackError")switch(c.code){case"invalid_state":throw Q("Invalid or expired state");case"credentials_not_configured":throw new A(400,"missing_credentials","OAuth client credentials are not configured for this plugin",{missingFields:["client_id","client_secret"]})}throw new A(502,"oauth_callback_failed","OAuth callback did not complete. Check server logs for details.")}}async function sn(e,n){if(!e.database)throw re("Permission not found");let t=await e.database.db.selectFrom("corsair_permissions").selectAll().where("token","=",n).executeTakeFirst();if(!t)throw re("Permission not found");return t}var Tt=[{method:"GET",pattern:"/ok",handler:async()=>R(200,ze())},{method:"GET",pattern:"/tenants",handler:async({internal:e})=>R(200,await Qe(e))},{method:"POST",pattern:"/tenants",handler:async({internal:e,body:n})=>R(201,await Xe(e,n))},{method:"GET",pattern:"/tenants/:id",handler:async({internal:e,params:n})=>R(200,await Ye(e,n.id))},{method:"GET",pattern:"/plugins",handler:async({internal:e})=>R(200,await Je(e))},{method:"GET",pattern:"/plugins/:id",handler:async({internal:e,params:n})=>R(200,await Ve(e,n.id))},{method:"GET",pattern:"/connection-status",handler:async({internal:e,query:n})=>R(200,await en(e,n.tenantId))},{method:"GET",pattern:"/permissions/:id",handler:async({internal:e,params:n})=>R(200,await nn(e,n.id))},{method:"POST",pattern:"/permissions/lookup-by-token",handler:async({internal:e,body:n})=>{let t=n?.token?.trim();return t?R(200,await sn(e,t)):R(400,{error:"bad_request",message:"token is required",missingFields:["token"]})}},{method:"POST",pattern:"/connect/links",handler:async({internal:e,body:n})=>R(200,await tn(e,n))},{method:"GET",pattern:"/connect/resolve",handler:async({corsair:e,internal:n,query:t})=>R(200,await rn(e,n,t.state??""))},{method:"POST",pattern:"/connect/oauth/callback",handler:async({corsair:e,internal:n,body:t})=>R(200,await on(e,n,t))}];(()=>{let e=new Set;for(let n of Tt){let t=`${n.method} ${n.pattern}`;if(e.has(t))throw new Error(`Duplicate management route registered: ${t}`);e.add(t)}})();function zr(e,n){let t=e.split("/").filter(Boolean),r=n.split("/").filter(Boolean);if(t.length!==r.length)return null;let i={};for(let o=0;o<t.length;o++){let s=t[o],a=r[o];if(s.startsWith(":"))i[s.slice(1)]=decodeURIComponent(a);else if(s!==a)return null}return i}function Jr(e,n){if(!n)return e;let t=n.endsWith("/")?n.slice(0,-1):n;return e===t?"/":e.startsWith(`${t}/`)?e.slice(t.length):e}function Vr(e){let n=e[x];if(!n)throw new Error("managementHandler: invalid corsair instance (missing internal config)");return n}async function Qr(e){if(!(e.method==="GET"||e.method==="HEAD"||!(e.headers.get("content-type")??"").includes("application/json")))try{let t=await e.text();return t?JSON.parse(t):void 0}catch{throw new A(400,"invalid_json","Request body is not valid JSON")}}var Yr="/api/corsair";function ue(e,n={}){let t=n.basePath??Yr,r=Vr(e);return async i=>{try{let o=new URL(i.url),s=Jr(o.pathname,t),a=i.method.toUpperCase(),c=Object.fromEntries(o.searchParams);for(let l of Tt){if(l.method!==a)continue;let d=zr(l.pattern,s);if(!d)continue;let u=await Qr(i);return await l.handler({corsair:e,internal:r,req:i,params:d,query:c,body:u})}throw re(`No route for ${a} ${s}`)}catch(o){if(n.onError){let a=await n.onError(o,i);if(a)return a}if(o instanceof A)return mt(o);let s=o instanceof Error?o.message:"Internal server error";return R(500,{error:"internal_error",message:s})}}}function Xr(e){let n=e.get?.("host")??"localhost",t=e.protocol??"http",r=e.originalUrl??e.url,i=`${t}://${n}${r}`,o=new Headers;for(let[c,l]of Object.entries(e.headers))if(l!=null)if(Array.isArray(l))for(let d of l)o.append(c,d);else o.set(c,l);let s=e.method!=="GET"&&e.method!=="HEAD",a={method:e.method,headers:o};return s&&e.body!==void 0&&(a.body=typeof e.body=="string"?e.body:JSON.stringify(e.body),o.has("content-type")||o.set("content-type","application/json")),new Request(i,a)}async function eo(e,n){e.status(n.status),n.headers.forEach((r,i)=>e.setHeader(i,r));let t=Buffer.from(await n.arrayBuffer());e.send(t)}function xt(e,n){let t=ue(e,n);return async(r,i,o)=>{try{let s=await t(Xr(r));await eo(i,s)}catch(s){o(s)}}}function Pt(e,n){let t=ue(e,n);return r=>t(r.req.raw)}function At(e,n){let t=ue(e,n);return{GET:t,POST:t}}function Rt(e){let n={[x]:e};return{ok:ze,tenants:{list:()=>Qe(e),create:t=>Xe(e,t),get:t=>Ye(e,t)},plugins:{list:()=>Je(e),get:t=>Ve(e,t)},connectionStatus:{get:t=>en(e,t?.tenantId)},permissions:{get:t=>nn(e,t),getByToken:t=>sn(e,t)},connect:{createLink:t=>tn(e,t),resolve:t=>rn(n,e,t),oauthCallback:t=>on(n,e,t)}}}async function vt(e,n,t,r,i="pending"){if(!e)return null;try{let o=zn(),s=new Date;return await e.db.insertInto("corsair_events").values({id:o,created_at:s,updated_at:s,account_id:n,event_type:t,payload:r,status:i}).execute(),o}catch(o){return console.warn("Failed to log event:",o),null}}async function no(e,n,t,r="pending"){try{let i=await e.$getAccountId();return vt(e.database,i,n,t,r)}catch(i){return console.warn("Failed to log event:",i),null}}import*as It from"https";import*as St from"querystring";function an(e,n,t,r,i){let o=new URL(r.tokenUrl),s=r.tokenAuthMethod==="basic";return new Promise((a,c)=>{let l={code:e.trim(),redirect_uri:i,grant_type:"authorization_code"};s||(l.client_id=n,l.client_secret=t);let d=St.stringify(l),u={"Content-Type":"application/x-www-form-urlencoded","Content-Length":Buffer.byteLength(d).toString()};s&&(u.Authorization=`Basic ${Buffer.from(`${n}:${t}`).toString("base64")}`);let g=It.request({hostname:o.hostname,...o.port?{port:Number(o.port)}:{},path:o.pathname+o.search,method:"POST",headers:u},f=>{let p="";f.on("data",y=>{p+=y}),f.on("end",()=>{if(f.statusCode!==200){c(new Error(`Token exchange failed (${f.statusCode}): ${p}`));return}try{a(JSON.parse(p))}catch{c(new Error(`Token endpoint returned non-JSON response: ${p}`))}})});g.on("error",f=>c(new Error(`Request failed: ${f.message}`))),g.write(d),g.end()})}var Et=" ";function B(e){let n=e;return n._def??n.def??{}}function W(e){let n=e.typeName;if(n)return n;let t=e.type;if(t)return`Zod${t.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}`}function $(e){return e.innerType??e.schema??e.out??e.in}function Ot(e,n){switch(n){case"ZodPipe":return e.in??e.innerType;case"ZodEffects":return e.schema??e.innerType;case"ZodTransform":return e.schema??e.innerType??e.in;default:return $(e)}}function Ht(e){let n=e.type;return e.element??(typeof n=="string"?void 0:n)}function un(e,n){let t=n.shape??e.shape;return typeof t=="function"?t():t}function he(e){return Array.isArray(e.options)?e.options:Array.isArray(e.values)?e.values:e.entries!==null&&typeof e.entries=="object"&&!Array.isArray(e.entries)?Object.values(e.entries):[]}function Dt(e,n){return e.description??n.description}function to(e){let n=e;for(;n;){let t=B(n),r=Dt(n,t);if(r)return r;let i=W(t);if(jn(i)||i==="ZodPipe"||i==="ZodEffects"||i==="ZodTransform"){n=Ot(t,i);continue}break}}function jn(e){return e==="ZodOptional"||e==="ZodNullable"||e==="ZodDefault"||e==="ZodCatch"}function O(e){let n=B(e),t=W(n);switch(t){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodDate":return"Date";case"ZodNull":return"null";case"ZodUnknown":case"ZodAny":return"any";case"ZodLiteral":return String(n.value??he(n)[0]??"unknown");case"ZodEnum":return he(n).map(r=>String(r)).join(" | ");case"ZodOptional":{let r=$(n);return r?O(r):"unknown"}case"ZodNullable":{let r=$(n);return`${r?O(r):"unknown"} | null`}case"ZodDefault":case"ZodCatch":{let r=$(n);return r?O(r):"unknown"}case"ZodArray":{let r=Ht(n);if(!r)return"unknown[]";let i=B(r),o=W(i)==="ZodUnion",s=O(r);return`${o?`(${s})`:s}[]`}case"ZodRecord":return"{}";case"ZodObject":{let r=un(e,n),i=Object.entries(r);return i.length===0?"{}":`{ ${i.map(([s,a])=>{let c=W(B(a));return`${c==="ZodOptional"||c==="ZodNullable"?s+"?":s}: ${O(a)}`}).join(", ")} }`}case"ZodUnion":return he(n).map(r=>O(r)).join(" | ");case"ZodIntersection":return`${O(n.left)} & ${O(n.right)}`;case"ZodPipe":case"ZodTransform":case"ZodEffects":{let r=Ot(n,t);return r?O(r):"unknown"}default:return(t??"unknown").replace("Zod","").toLowerCase()}}function Y(e){let n=B(e),t=W(n),r=Dt(e,n);switch(t){case"ZodString":return{kind:"string",optional:!1,description:r};case"ZodNumber":return{kind:"number",optional:!1,description:r};case"ZodBoolean":return{kind:"boolean",optional:!1,description:r};case"ZodLiteral":{let i=n.value??he(n)[0],o=typeof i=="string"||typeof i=="number"||typeof i=="boolean"?i:String(i??"");return{kind:"literal",optional:!1,description:r,value:o}}case"ZodEnum":{let i=he(n).map(o=>String(o));return{kind:"string",optional:!1,description:r,enum:i}}case"ZodOptional":{let i=$(n),o=i?Y(i):{kind:"unknown",optional:!1};return{...o,optional:!0,description:r??o.description}}case"ZodNullable":{let i=$(n),o=i?Y(i):{kind:"unknown",optional:!1};return{...o,optional:!0,description:r??o.description}}case"ZodDefault":case"ZodCatch":{let i=$(n);return i?{...Y(i),description:r}:{kind:"unknown",optional:!1,description:r}}case"ZodArray":{let i=Ht(n);return{kind:"array",optional:!1,description:r,items:i?Y(i):{kind:"unknown",optional:!1}}}case"ZodObject":{let i=un(e,n),o={};for(let[s,a]of Object.entries(i))o[s]=Y(a);return{kind:"object",optional:!1,description:r,fields:o}}case"ZodRecord":return{kind:"unknown",optional:!1,description:r};case"ZodUnion":{let i=he(n);for(let o of i){let s=B(o);if(W(s)==="ZodObject")return{...Y(o),description:r}}return{kind:"unknown",optional:!1,description:r}}case"ZodIntersection":case"ZodPipe":case"ZodTransform":case"ZodEffects":{let i=$(n);return i?{...Y(i),description:r}:{kind:"unknown",optional:!1,description:r}}default:return{kind:"unknown",optional:!1,description:r}}}function qs(e,n){let t=n.toLowerCase(),r=t.indexOf(".");if(r===-1)return null;let i=t.slice(0,r),o=t.slice(r+1),s=e.find(d=>d.id===i);if(!s)return null;let a=o;a.startsWith("api.")&&(a=a.slice(4));let c=oe(s.endpointMeta,a),l=oe(s.endpointSchemas,a);return!c&&!l?null:{input:l?.input?Y(l.input):null,output:l?.output?Y(l.output):null,description:c?.description}}var Kn=["equals","contains","startsWith","endsWith","in"],ro=["equals","gt","gte","lt","lte","in"],oo=["equals"],io=["equals","before","after","between"];function Mt(e){let n=B(e);switch(W(n)){case"ZodOptional":case"ZodNullable":case"ZodDefault":case"ZodCatch":{let r=$(n);return r?Mt(r):null}case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodDate":return"date";default:return null}}function Zn(e){let n=B(e),t=W(n);if(jn(t)){let o=$(n);return o?Zn(o):{}}if(t!=="ZodObject")return{};let r=un(e,n),i={};for(let[o,s]of Object.entries(r)){let a=Mt(s);a==="string"?i[o]={type:"string",operators:Kn}:a==="number"?i[o]={type:"number",operators:ro}:a==="boolean"?i[o]={type:"boolean",operators:oo}:a==="date"&&(i[o]={type:"date",operators:io})}return i}function Ft(e,n){for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return[t,r]}function Bn(e,n,t){for(let[r,i]of Object.entries(e)){let o=[...n,r];typeof i=="function"?t.push(o.join(".")):i!==null&&typeof i=="object"&&Bn(i,o,t)}}function Wn(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function Ln(e,n,t){for(let[r,i]of Object.entries(e)){let o=[...n,r];Wn(i)?t.push(o.join(".")):i!==null&&typeof i=="object"&&Ln(i,o,t)}}function qn(e,n){if(n.length===0)return null;let[t,...r]=n,i=Object.entries(e).find(([a])=>a.toLowerCase()===t);if(!i)return null;let[o,s]=i;if(r.length===0)return Wn(s)?[o]:null;if(s!==null&&typeof s=="object"&&!Wn(s)){let a=qn(s,r);if(a!==null)return[o,...a]}return null}function Nt(e,n){let t=[];t.push(`${e}({`),t.push(" webhookHooks: {");for(let o=0;o<n.length;o++){let s=" ".repeat(o+2);t.push(`${s}${n[o]}: {`)}let r=" ".repeat(n.length+2),i=r+" ";t.push(`${r}before(ctx, args) {`),t.push(`${i}return { ctx, args };`),t.push(`${r}},`),t.push(`${r}after(ctx, response) {`),t.push(`${r}},`);for(let o=n.length-1;o>=0;o--){let s=" ".repeat(o+2);t.push(`${s}},`)}return t.push(" },"),t.push("})"),t.join(`
|
|
14
|
-
`)}var so=new Set(Ie);function de(e,n){let t=n?.type??"api",r=n?.plugin;if(r!==void 0){let o=e.find(a=>a.id===r);if(!o)return so.has(r)?`This plugin (${r}) is not configured. Please add it to the Corsair instance to see its associated methods.`:de(e);if(t==="webhooks"){if(!o.webhooks)return[];let a=[];return Ln(o.webhooks,[],a),a.map(c=>`${o.id}.webhooks.${c}`)}if(t==="db"){let a=o.schema?.entities;return a?Object.keys(a).map(c=>`${o.id}.db.${c}.search`):[]}if(!o.endpoints)return[];let s=[];return Bn(o.endpoints,[],s),s.map(a=>`${o.id}.api.${a}`)}let i={};if(t==="webhooks")for(let o of e){if(!o.webhooks)continue;let s=[];Ln(o.webhooks,[],s),i[o.id]=s.map(a=>`${o.id}.webhooks.${a}`)}else if(t==="db")for(let o of e){let s=o.schema?.entities;s&&(i[o.id]=Object.keys(s).map(a=>`${o.id}.db.${a}.search`))}else for(let o of e){if(!o.endpoints)continue;let s=[];Bn(o.endpoints,[],s),i[o.id]=s.map(a=>`${o.id}.api.${a}`)}return i}function oe(e,n){if(e){for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r}}function ao(e,n){let t=e.toLowerCase(),r=n.toLowerCase();if(!t.startsWith(`${r}.`)){let o=t.slice(n.length+1),s=o.startsWith(".")?o.slice(1):o;return s.startsWith("api.")&&(s=s.slice(4)),{shortPath:s,lookupKey:s}}let i=e.slice(n.length+1);return i.toLowerCase().startsWith("api.")&&(i=i.slice(4)),{shortPath:i,lookupKey:i.toLowerCase()}}function $n(e,n){return typeof e=="string"?e:Array.isArray(e)?`${n}:
|
|
15
|
-
${e.join(", ")}`:`${n}:
|
|
16
|
-
`+Object.entries(e).map(([t,r])=>` ${t}: ${r.join(", ")}`).join(`
|
|
17
|
-
`)}function Gs(e,n){let t=n.toLowerCase(),r=t.indexOf(".");if(r!==-1){let i=t.slice(0,r),o=t.slice(r+1),s=e.find(a=>a.id===i);if(s){if(o.startsWith("db.")){let d=o.slice(3),u=d.lastIndexOf(".");if(u!==-1){let g=d.slice(0,u),f=d.slice(u+1),p=s.schema?.entities;if(f==="search"&&p){let y=Ft(p,g);if(y){let[m,w]=y,T=Zn(w),k=[`Search ${i} ${m} stored in the local database.`,"Pass limit and offset as numbers for pagination.","","filters {",` entity_id: string [${Kn.join(", ")}]`];for(let[h,b]of Object.entries(T))k.push(` ${h}?: ${b.type} [${b.operators.join(", ")}]`);return k.push("}"),k.join(`
|
|
18
|
-
`)}}}return $n(de(e,{type:"db"}),"Path not found. Available db operations")}if(o.startsWith("webhooks.")){let d=o.slice(9);if(s.webhooks){let u=qn(s.webhooks,d.split("."));if(u!==null){let g=u.join("."),f=oe(s.webhookSchemas,g.toLowerCase()),p=f?.response?O(f.response):null,y=[];return f?.description&&y.push(f.description),f?.payload&&y.push(`payload ${cn(me(f.payload))}`),p&&y.push(`response: ${p}`),y.push(`usage:
|
|
19
|
-
${Nt(i,u)}`),y.join(`
|
|
20
|
-
|
|
21
|
-
`)}}return $n(de(e,{type:"webhooks"}),"Path not found. Available webhooks")}let a=o;a.startsWith("api.")&&(a=a.slice(4));let c=oe(s.endpointMeta,a),l=oe(s.endpointSchemas,a);if(c||l){let d=[],u=[c?.riskLevel?`[${c.riskLevel}]`:"",c?.irreversible?"[irreversible]":""].filter(Boolean).join(" "),g=[c?.description,u].filter(Boolean).join(" ");return g&&d.push(g),l?.input&&d.push(`input ${cn(me(l.input))}`),l?.output&&d.push(`output ${cn(me(l.output))}`),d.join(`
|
|
22
|
-
|
|
23
|
-
`)}}}return $n(de(e),"Path not found. Available operations")}function _t(e){let n=e;for(;;){let t=B(n),r=W(t);if(jn(r)){let i=$(t);if(!i)return n;n=i;continue}return n}}function me(e){if(e===void 0)return{kind:"inline",type:"unknown"};let n=_t(e),t=B(n);if(W(t)==="ZodObject"){let i=un(n,t),o=[];for(let[s,a]of Object.entries(i)){let c=B(a),l=W(c),d=l==="ZodOptional"||l==="ZodNullable",u=_t(a),g=to(a);o.push({key:s,optional:d,type:O(u),...g!==void 0?{description:g}:{}})}return{kind:"object",fields:o}}return{kind:"inline",type:O(n)}}function cn(e,n=0){if(e===void 0)return"{}";if(e.kind==="inline")return e.type;if(e.kind==="object"){if(e.fields.length===0)return"{}";let t=Et.repeat(n+1),r=Et.repeat(n);return`{
|
|
24
|
-
${e.fields.map(o=>{let s=o.optional?`${o.key}?`:o.key,a=o.description?` // ${o.description}`:"";return`${t}${s}: ${o.type}${a}`}).join(`
|
|
25
|
-
`)}
|
|
26
|
-
${r}}`}return"unknown"}function co(e,n){let t=de(e,{plugin:n,type:"api"});if(typeof t=="string")return{ok:!1,error:t};if(!Array.isArray(t))return{ok:!1,error:"list_operations did not return a path array \u2014 pass a configured plugin id."};let r=e.find(d=>d.id===n);if(!r)return{ok:!1,error:`Plugin "${n}" is not configured on this instance.`};let i=[];for(let d of t){let{shortPath:u,lookupKey:g}=ao(d,n),f=oe(r.endpointMeta,g),p=oe(r.endpointSchemas,g);!f&&!p||i.push({path:d,shortPath:u,description:f?.description,riskLevel:f?.riskLevel,irreversible:f?.irreversible,input:me(p?.input),output:me(p?.output)})}i.sort((d,u)=>d.path.localeCompare(u.path));let o=[],s=de(e,{plugin:n,type:"webhooks"});if(Array.isArray(s)&&r.webhooks)for(let d of s){let g=d.toLowerCase().slice(n.length+1),f=g.startsWith(".")?g.slice(1):g;if(!f.startsWith("webhooks."))continue;let p=f.slice(9),y=qn(r.webhooks,p.split("."));if(y===null)continue;let m=y.join("."),w=oe(r.webhookSchemas,m.toLowerCase()),T=w?.response?O(w.response):void 0;o.push({path:d,description:w?.description,payload:me(w?.payload),responseType:T,usageExample:Nt(n,y)})}o.sort((d,u)=>d.path.localeCompare(u.path));let a=[],c=de(e,{plugin:n,type:"db"}),l=r.schema?.entities;if(Array.isArray(c)&&l)for(let d of c){let g=d.toLowerCase().slice(n.length+1),f=g.startsWith(".")?g.slice(1):g;if(!f.startsWith("db."))continue;let p=f.slice(3),y=p.lastIndexOf(".");if(y===-1)continue;let m=p.slice(0,y);if(p.slice(y+1)!=="search")continue;let T=Ft(l,m);if(!T)continue;let[k,h]=T,b=Zn(h),C=Object.entries(b).map(([I,S])=>({field:I,type:S.type,operators:S.operators}));a.push({path:d,entityName:k,filters:[{field:"entity_id",type:"string",operators:Kn},...C]})}return a.sort((d,u)=>d.path.localeCompare(u.path)),{ok:!0,data:{pluginId:n,api:i,webhooks:o,db:a}}}function Ut(e,n){for(let[t,r]of Object.entries(e))if(r?.pluginWebhookMatcher&&r.pluginWebhookMatcher(n))return t;return null}function uo(e,n){let t=Ut(e,n);if(!t)return null;let r=e[t];if(!r?.pluginTenantWebhookMatcher)return null;let i=r.pluginTenantWebhookMatcher(n);return i?{plugin:t,tenantMatch:i}:null}function lo(e){let n={};for(let t of e)!t.pluginWebhookMatcher&&!t.pluginTenantWebhookMatcher||(n[t.id]={pluginWebhookMatcher:t.pluginWebhookMatcher,pluginTenantWebhookMatcher:t.pluginTenantWebhookMatcher});return n}function $t(e,n){let t=n.toLowerCase(),r=e[t]??e[n];return Array.isArray(r)?r[0]:typeof r=="string"?r:void 0}function Bt(e){if(typeof e=="string"){let n=e.trim();return n.length>0?n:void 0}if(typeof e=="number"&&Number.isFinite(e))return String(e)}function Re(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function po(e){return Re(e.body)}function Wt(e,n){let t=e.query;if(!t)return;let r=t[n]??t[n.toLowerCase()];return dn(Array.isArray(r)?r:[r])}function Lt(e){let n=e.headers??{},t=[n.validationtoken,n.validationToken,n["validation-token"],n["ms-validation-token"]];for(let c of t){let l=dn(Array.isArray(c)?c:[c]);if(l)return decodeURIComponent(l)}let r=Wt({query:e.query},"validationToken");if(r)return r;let i=["x-forwarded-uri","x-original-uri","x-rewrite-url","x-envoy-original-path","referer"];for(let c of i){let l=n[c],d=Array.isArray(l)?l[0]:l;if(!(!d||typeof d!="string"))try{let g=(d.startsWith("http")?new URL(d):new URL(`https://example.invalid${d.startsWith("/")?d:`/${d}`}`)).searchParams.get("validationToken");if(g?.trim())return g.trim()}catch{continue}}let o=e.payload!==void 0?e.payload:e.body!==void 0?e.body:void 0,s=Re(typeof o=="string"?(()=>{try{return JSON.parse(o)}catch{return o}})():o);return dn([s?.validationToken])??null}function go(e){if(Lt(e))return!0;let n=Re(e.body??e.payload);return $t(e.headers??{},"content-type")?.includes("text/plain")?!n||Object.keys(n).length===0:!1}function dn(e){for(let n of e){let t=Bt(n);if(t)return t}}function fo(e){let t=Re(e.message)?.data;if(typeof t!="string")return null;try{return JSON.parse(Buffer.from(t,"base64").toString("utf8"))}catch{return null}}var x=Symbol.for("corsair:internal");function ra(e){let n=e.database?Gn(e.database):void 0,t=n&&e.kek?yt(e.plugins,n,e.kek):Ge(!!n,!!e.kek),r={plugins:e.plugins,database:n,kek:e.kek,multiTenancy:!!e.multiTenancy,approval:e.approval,connect:e.connect,hub:e.hub?Se(e.hub):void 0},i=gt(n),o=Rt(r);if(e.multiTenancy)return Object.assign({withTenant:a=>{if(!a)throw new Error("corsair.withTenant(tenantId): tenantId must be a non-empty string");let c=Mn(e.plugins,{database:n,tenantId:a,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval,connectConfig:e.connect,hubConfig:r.hub});return Object.assign(c,{[x]:r})},keys:t,permissions:i,manage:o},{[x]:r});let s=Mn(e.plugins,{database:n,tenantId:void 0,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval,connectConfig:e.connect,hubConfig:r.hub});return Object.assign({},s,{keys:t,permissions:i,manage:o,[x]:r})}var q=class extends Error{code;constructor(n,t){super(t),this.name="OAuthCallbackError",this.code=n}};function Kt(e){let n=e[x];if(!n)throw new q("invalid_corsair_instance","Invalid corsair instance");return n}function Zt(e,n){let t=e.plugins.find(r=>r.id===n);if(!t)throw new q("plugin_not_found",`Plugin '${n}' not found`);return t}function qt(e){let n=e.oauthConfig;if(!n)throw new q("plugin_has_no_oauth_config",`Plugin '${e.id}' has no oauthConfig`);return n}async function yo(e,n,t,r){let i=ve(e),o=await i.integrations.findByName(n);if(!o)throw new Error(`Integration '${n}' not found. Run setupCorsair first.`);if(await i.accounts.findOne({tenant_id:t,integration_id:o.id}))return;let a=D(),c=await M(a,r);await i.accounts.create({tenant_id:t,integration_id:o.id,config:{},dek:c})}async function yn(e,n,t){let{tenantId:r,redirectUri:i}=t,o=Kt(e);if(!o.database)throw new Error("No database configured on corsair instance");let s=Zt(o,n),a=qt(s),l=await N({authType:"oauth_2",integrationName:n,kek:o.kek,database:o.database}).get_client_id();if(!l)throw new Error(`client_id not configured for '${n}'`);let d=ee(K(n,r),o.kek),u={...a.authParams,client_id:l,redirect_uri:i,response_type:"code",scope:a.scopes.join(" "),state:d};return{url:`${a.authUrl}?${jt.stringify(u)}`,state:d}}async function Ae(e,n){let{code:t,state:r,redirectUri:i}=n,o=Kt(e),s=_e(r,o.kek);if(!s)throw new q("invalid_state","Invalid or tampered state parameter");let{plugin:a,tenantId:c}=s;if(!o.database)throw new q("no_database","No database configured on corsair instance");let l=Zt(o,a),d=qt(l),u=N({authType:"oauth_2",integrationName:a,kek:o.kek,database:o.database}),g=await u.get_client_id(),f=await u.get_client_secret();if(!g||!f)throw new q("credentials_not_configured",`Credentials not configured for '${a}'`);await yo(o.database,a,c,o.kek);let p=await an(t,g,f,d,i);if(!p.access_token)throw new q("no_access_token",`No access_token returned from ${d.providerName}`);let y=Z({authType:"oauth_2",integrationName:a,tenantId:c,kek:o.kek,database:o.database});await y.set_access_token(p.access_token),p.refresh_token&&await y.set_refresh_token(p.refresh_token),p.expires_in&&await y.set_expires_at(String(Math.floor(Date.now()/1e3)+p.expires_in));try{let m=await Me(o.plugins,a,p);if(m)try{let w=l.authConfig?.oauth_2?.account??[];await fe({database:o.database,kek:o.kek,pluginId:a,tenantId:c,link:m,authType:"oauth_2",extraAccountFields:w})}catch(w){console.warn(`[corsair:oauth] Failed to persist webhook tenant link for '${a}' tenant '${c}':`,w)}}catch(m){console.warn(`[corsair:oauth] Failed to resolve webhook tenant link for '${a}' tenant '${c}':`,m)}return{plugin:a,tenantId:c}}export{Jn as a,be as b,we as c,G as d,Se as e,z as f,Ee as g,K as h,gn as i,D as j,M as k,F as l,wn as m,xe as n,ne as o,J as p,Pe as q,ce as r,N as s,Z as t,nt as u,tt as v,fe as w,Tn as x,$e as y,ot as z,q as A,yn as B,Ae as C,ge as D,se as E,fn as F,ae as G,He as H,hn as I,mn as J,kn as K,bn as L,De as M,te as N,ye as O,st as P,Be as Q,We as R,Le as S,Pn as T,An as U,je as V,Ke as W,Rn as X,vn as Y,In as Z,Ze as _,V as $,Sn as aa,ut as ba,dt as ca,Fn as da,ue as ea,xt as fa,Pt as ga,At as ha,vt as ia,no as ja,an as ka,qs as la,de as ma,Gs as na,cn as oa,co as pa,Ut as qa,uo as ra,lo as sa,$t as ta,Bt as ua,Re as va,po as wa,Wt as xa,Lt as ya,go as za,dn as Aa,fo as Ba,x as Ca,ra as Da};
|
package/dist/chunk-KLJBBN2T.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{Ca as v,Da as j,r as m,s as _,t as R}from"./chunk-J6HIPZAR.js";import{c as A}from"./chunk-3X6WVI5I.js";import{Kysely as F}from"kysely";import{ZodBoolean as x,ZodDate as E,ZodEnum as D,ZodNullable as K,ZodNumber as N,ZodObject as B,ZodOptional as Z,ZodRecord as L,ZodString as U,ZodType as W}from"zod";var I={slack:{channels:{list:{}},users:{list:{}}},linear:{projects:{list:{}},issues:{list:{}},users:{list:{}}},github:{issues:{list:{}},repositories:{list:{}}},discord:{guilds:{list:{}},channels:{list:{}}},hubspot:{contacts:{getMany:{}},companies:{getMany:{}},deals:{getMany:{}}},gmail:{messages:{list:{}},labels:{list:{}},drafts:{list:{}},threads:{list:{}}},googlecalendar:{events:{getMany:{}}},googledrive:{files:{list:{}},folders:{list:{}},sharedDrives:{list:{}}},notion:{databases:{getManyDatabases:{}},databasePages:{getManyDatabasePages:{}},users:{getManyUsers:{}}},airtable:{bases:{getMany:{}}},todoist:{projects:{getMany:{}},tasks:{getMany:{}}},cal:{bookings:{list:{}}},zohomail:{folders:{list:{}},messages:{list:{}}}};async function pn(n,e){let s=[],i=d=>{s.push(d),console.log(d)},a=d=>{s.push(d),console.warn(d)},t=e?.caller??"script",f=q(n);if(!f)throw new Error("setupCorsair: invalid corsair instance");if(!f.database)throw new Error("setupCorsair: a database must be configured on the corsair instance");let o=Q(n,f.plugins,e),r={...f,database:f.database},c=r.database.db;await X(c,a);let l=await nn(c,r,o.tenantId,o.provisionAccounts,i);e?.credentials&&Object.keys(e.credentials).length>0&&await sn(n,o,e.credentials,r,i,a);let y=await rn(l,o,i,t);if(e?.backfill){i("[corsair:setup] Starting backfill...");let d=j({plugins:f.plugins,database:c,kek:f.kek,multiTenancy:!0}).withTenant(o.tenantId);await on(d,f.plugins,y,i,a),i("[corsair:setup] Backfill complete.")}return s.join(`
|
|
2
|
-
`)}function w(n){return typeof n=="object"&&n!==null}function Y(n){return!w(n)||!Array.isArray(n.plugins)||typeof n.kek!="string"||typeof n.multiTenancy!="boolean"?!1:n.database===void 0?!0:w(n.database)?n.database.db instanceof F:!1}function q(n){let e=Object.getOwnPropertyDescriptor(n,v);if(e)return Y(e.value)?e.value:void 0}function z(n){return n==="oauth_2"||n==="api_key"||n==="bot_token"}function P(n){let e=n.options?.authType;return z(e)?e:void 0}function H(n){return"withTenant"in n&&typeof n.withTenant=="function"}function $(n,e,s){let i=s==="integration"?n.authConfig?.[e]?.integration??[]:n.authConfig?.[e]?.account??[];return new Set([...m[e][s],...i])}function J(n,e){if(!n)return!1;for(let[s,i]of Object.entries(n)){let a=e.find(o=>o.id===s);if(!a)continue;let t=P(a);if(!t)continue;let f=$(a,t,"account");for(let o of Object.keys(i))if(f.has(o))return!0}return!1}function Q(n,e,s){let i=H(n),a=s?.tenantId?.trim(),t=a!==void 0&&a.length>0;if(i&&s?.backfill&&!t)throw new Error("setupCorsair: tenantId is required for backfill on a multi-tenant instance");if(i&&J(s?.credentials,e)&&!t)throw new Error("setupCorsair: tenantId is required when setting account-level credentials on a multi-tenant instance");if(t&&!a)throw new Error("setupCorsair: tenantId must be a non-empty string");return{multiTenant:i,tenantIdProvided:t,tenantId:t?a:"default",provisionAccounts:!i||t}}function C(n,e){if(!w(n))return;let s=n[e];return typeof s=="function"?(...i)=>Reflect.apply(s,n,i):void 0}function O(n,e){return w(n)?e===0?!0:Object.values(n).every(s=>O(s,e-1)):!1}function V(n){return O(n,4)}var G={...A};function S(n){if(n instanceof B){let e={};for(let[s,i]of Object.entries(n.shape))e[s]=i instanceof W?S(i):"unknown";return e}return n instanceof K?`${S(n.unwrap())} | null`:n instanceof Z?`${S(n.unwrap())} | undefined`:n instanceof D?n.options.join(" | "):n instanceof U?"string":n instanceof N?"number":n instanceof x?"boolean":n instanceof E?"date":n instanceof L?"jsonb":"unknown"}async function X(n,e){let s=await n.introspection.getTables(),i=new Set(s.map(a=>a.name));for(let[a,t]of Object.entries(G))i.has(a)||e(`[corsair:setup] Table "${a}" does not exist. Run your database migrations before calling setupCorsair.
|
|
3
|
-
Schema: ${JSON.stringify(S(t),null,2)}`)}async function nn(n,e,s,i,a){let t=new Date,f=new Map;for(let o of e.plugins){let r=o.id,c=P(o),l=await n.selectFrom("corsair_integrations").selectAll().where("name","=",r).executeTakeFirst();if(!l){let u=crypto.randomUUID();await n.insertInto("corsair_integrations").values({id:u,name:r,config:{},created_at:t,updated_at:t}).execute(),l=await n.selectFrom("corsair_integrations").selectAll().where("id","=",u).executeTakeFirst(),a(`[corsair:setup] Created integration: ${r}`)}let y=c?o.authConfig?.[c]?.integration??[]:[],d=c?o.authConfig?.[c]?.account??[]:[],g=c&&l?_({authType:c,integrationName:r,kek:e.kek,database:e.database,extraIntegrationFields:y}):void 0;if(l&&!l.dek&&g&&(await g.issue_new_dek(),a(`[corsair:setup] Issued integration DEK: ${r}`)),!l||!c||!g)continue;let p;if(i){let u=await n.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",s).where("integration_id","=",l.id).executeTakeFirst();if(!u){let h=crypto.randomUUID();await n.insertInto("corsair_accounts").values({id:h,tenant_id:s,integration_id:l.id,config:{},created_at:t,updated_at:t}).execute(),u=await n.selectFrom("corsair_accounts").selectAll().where("id","=",h).executeTakeFirst(),a(`[corsair:setup] Created account: ${r}`)}p=u&&R({authType:c,integrationName:r,tenantId:s,kek:e.kek,database:e.database,extraAccountFields:d}),u&&p&&!u.dek&&(await p.issue_new_dek(),a(`[corsair:setup] Issued account DEK: ${r}`))}f.set(r,{pluginId:r,authType:c,integration:g,account:p,integrationFields:[...m[c].integration,...y],accountFields:i?[...m[c].account,...d]:[]})}return f}function en(n){if(!w(n))return;let e=n.keys;return w(e)?e:void 0}function tn(n,e){return"withTenant"in n&&typeof n.withTenant=="function"?n.withTenant(e):n}async function sn(n,e,s,i,a,t){let f=en(n),o=e.provisionAccounts?tn(n,e.tenantId):void 0;for(let[r,c]of Object.entries(s)){let l=i.plugins.find(b=>b.id===r);if(!l){t(`[corsair:setup] Unknown plugin '${r}' \u2014 skipping credentials.`);continue}let y=P(l);if(!y){t(`[corsair:setup] Plugin '${r}' has no auth type \u2014 skipping credentials.`);continue}let d=$(l,y,"integration"),g=$(l,y,"account"),p=f?.[r],u=o?.[r],h=w(u)?u.keys:void 0;for(let[b,T]of Object.entries(c))if(T){if(d.has(b)){if(e.multiTenant&&e.tenantIdProvided)throw new Error(`[corsair:setup] '${r}.${b}' is an integration-level credential shared across all tenants. You passed tenantId="${e.tenantId}", which only scopes account-level credentials. Run setup without --tenant if you intend to change this credential globally.`);let k=C(p,`set_${b}`);if(!k){t(`[corsair:setup] Cannot set integration field '${b}' for '${r}'.`);continue}await k(T),a(`[corsair:setup] Set ${r} integration.${b}`);continue}if(g.has(b)){if(e.multiTenant&&!e.tenantIdProvided)throw new Error(`setupCorsair: tenantId is required to set account-level credential '${r}.${b}' on a multi-tenant instance`);let k=C(h,`set_${b}`);if(!k){t(`[corsair:setup] Cannot set account field '${b}' for '${r}'.`);continue}await k(T),a(`[corsair:setup] Set ${r} account.${b} (tenant=${e.tenantId})`);continue}t(`[corsair:setup] Unknown credential field '${b}' for plugin '${r}'.`)}}}var M=new Set(["webhook_signature","expires_at","scope","redirect_url"]);async function an(n,e,s,i,a,t,f,o,r){let c=[],l=[];for(let d of a){if(M.has(d))continue;let g=C(s,`get_${d}`);if(!g)continue;let p=null;try{let u=await g();p=typeof u=="string"?u:null}catch{}p||c.push(d)}if(i&&t.length>0)for(let d of t){if(M.has(d))continue;let g=C(i,`get_${d}`);if(!g)continue;let p=null;try{let u=await g();p=typeof u=="string"?u:null}catch{}p||l.push(d)}let y=c.length===0&&l.length===0;if(y)o(`[corsair:setup] '${n}' (${e}) is configured \u2713`);else{let d=[...c,...l];if(r==="cli"){let g=d.map(p=>`${p}=VALUE`).join(" ");o(`[corsair:setup] '${n}' (${e}) needs credentials. Run:
|
|
4
|
-
corsair setup --${n} ${g}`)}else{let g=[`[corsair:setup] '${n}' (${e}) needs credentials. Call:`];for(let p of c)g.push(` await corsair.keys.${n}.set_${p}(value)`);for(let p of l){let u=f.provisionAccounts?f.tenantId==="default"?`corsair.${n}`:`corsair.withTenant(${JSON.stringify(f.tenantId)}).${n}`:`corsair.withTenant(<tenant>).${n}`;g.push(` await ${u}.keys.set_${p}(value)`)}o(g.join(`
|
|
5
|
-
`))}}return y}async function rn(n,e,s,i){let a=new Set;for(let t of n.values())await an(t.pluginId,t.authType,t.integration,t.account,t.integrationFields,t.accountFields,e,s,i)&&a.add(t.pluginId);return a}async function on(n,e,s,i,a){if(!V(I)){a("[corsair:setup] Backfill config is invalid - skipping backfill.");return}let t=I,f=new Set(e.map(o=>o.id));for(let[o,r]of Object.entries(t)){if(!f.has(o))continue;if(!s.has(o)){i(`[corsair:setup] Skipping backfill for '${o}' \u2014 auth not configured.`);continue}let c=w(n)?n[o]:void 0,l=w(c)?c.api:void 0;if(l)for(let[y,d]of Object.entries(r))for(let[g,p]of Object.entries(d)){i(`[corsair:setup] Backfilling ${o} \u203A ${y}.${g}...`);try{let u=w(l)?l[y]:void 0;await C(u,g)?.(p)}catch(u){a(`[corsair:setup] ${o} \u203A ${y}.${g} failed: `+(u instanceof Error?u.message:String(u)))}}}}export{pn as a,sn as b};
|