corsair 0.1.96 → 0.1.97
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-FPKQA47O.js → chunk-OVJRYUB3.js} +8 -8
- package/dist/core.js +1 -1
- package/dist/hub.d.ts +2 -0
- package/dist/hub.js +1 -1
- package/dist/index.js +1 -1
- package/dist/oauth.js +1 -1
- package/dist/setup.js +1 -1
- package/dist/tunnel.js +1 -1
- package/package.json +1 -1
|
@@ -10,29 +10,29 @@ Schema: ${JSON.stringify(mn(i),null,2)}`)}async function Di(e,n,t,r,o){let i=new
|
|
|
10
10
|
window.parent.postMessage(message, targetOrigin);
|
|
11
11
|
}
|
|
12
12
|
})();
|
|
13
|
-
</script></body></html>`}var ls=[".corsair.dev"];function ds(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function ps(e){try{let{hostname:n,protocol:t}=new URL(e);return t!=="http:"&&t!=="https:"?!1:ds(n)?!0:ls.some(r=>n===r.slice(1)||n.endsWith(r))}catch{return!1}}function to(e){return!e||!ps(e)?null:{"Access-Control-Allow-Origin":e,"Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"content-type, x-corsair-signature, x-corsair-timestamp, x-corsair-project, x-corsair-nonce, access-control-request-private-network","Access-Control-Allow-Private-Network":"true","Access-Control-Max-Age":"0",Vary:"Origin"}}function ro(e,n){if(!n)return e;let t=new Headers(e.headers);for(let[r,o]of Object.entries(n))t.set(r,o);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function bt(e,n){let t=new URL(e);return n.error?(t.searchParams.set("error",n.error),t.toString()):n.connectedPlugin?(t.searchParams.set("connected",n.connectedPlugin),t.toString()):(n.status!==void 0&&t.searchParams.set("status",Buffer.from(JSON.stringify(n.status)).toString("base64url")),t.toString())}async function Ct(e,n){let t=J(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=ge(o,t.signingSecret);if(!i)return{type:"json",status:400,body:{error:"Invalid or expired delivery token"}};let a=Cn(`browser:${i.jti}`,de);if(!a.ok)return{type:"json",status:400,body:{error:a.error}};try{if(Pe(i))return i.hubSuccessUrl?i.credentials?(await kn(e,{plugin:i.plugin,tenantId:i.tenantId,credentials:i.credentials}),{type:"redirect",url:bt(i.hubSuccessUrl,{connectedPlugin:i.plugin})}):{type:"redirect",url:bt(i.hubSuccessUrl,{error:"Credential delivery missing credentials"})}:{type:"json",status:400,body:{error:"Credential delivery missing hubSuccessUrl"}};if(Je(i)){if(!i.permissionToken)return{type:"json",status:400,body:{error:"Permission delivery missing permission token"}};await ht(e,i.permissionToken,i.deliveryMode==="permission.approve"?"approved":"denied")}else if(ze(i)){if(!i.accessToken)return{type:"json",status:400,body:{error:"Managed OAuth delivery missing access_token"}};await Oe(e,{plugin:i.plugin,tenantId:i.tenantId,accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,scope:i.scope})}else{if(!In(i)||!i.code||!i.state||!i.redirectUri)return{type:"json",status:400,body:{error:"Invalid BYO OAuth delivery token"}};await Ve(e,{code:i.code,state:i.state,redirectUri:i.redirectUri})}}catch(s){let u=s instanceof Error?s.message:"Hub delivery failed";return Pe(i)&&i.hubSuccessUrl?{type:"redirect",url:bt(i.hubSuccessUrl,{error:u})}:Pe(i)&&i.hubOrigin&&i.requestId?{type:"text",status:400,headers:{"Content-Type":"text/html; charset=utf-8"},body:no({hubOrigin:i.hubOrigin,requestId:i.requestId,ok:!1,error:u})}:{type:"json",status:400,body:{error:u}}}return{type:"redirect",url:i.hubSuccessUrl}}async function wt(e,n){let t=J(e),r=await kt(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,a=o.headers;return o.body&&typeof o.body=="object"&&!(o.body instanceof ArrayBuffer)?{type:"json",status:i,body:o.body,headers:a}:{type:"text",status:i,body:typeof o.body=="string"?o.body:o.body?JSON.stringify(o.body):null,headers:a}}function Pt(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 Tt(e,n){return n.method==="GET"?Ct(e,n.url):wt(e,{headers:n.headers,body:n.body??""})}async function vt(e,n){try{let t=await Tt(e,n);return Pt(t)}catch(t){if(t instanceof ue)return Response.json({error:t.message},{status:503});throw t}}async function Te(e,n){let t=n.method.toUpperCase(),r=to(n.headers.get("origin"));if(t==="OPTIONS")return r?new Response(null,{status:204,headers:r}):Response.json({error:"Method not allowed"},{status:405});if(t!=="GET"&&t!=="POST")return Response.json({error:"Method not allowed"},{status:405});let o=await vt(e,{method:t,url:n.url,headers:n.headers,body:t==="POST"?await n.text():void 0});return ro(o,r)}var re=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 oo=300;async function At(e,n){let{keys:t,hub:r,plugin:o,tenantId:i}=e,a=n?.forceRefresh??!1,[s,u,d]=await Promise.all([t.get_access_token(),t.get_expires_at(),t.get_refresh_token()]);if(!s&&!d)throw new re(o,"managed");let l=Math.floor(Date.now()/1e3);if(!a&&s&&u&&Number(u)>l+oo)return{accessToken:s,expiresAt:Number(u),refreshed:!1};if(!d&&s&&!a){let f=u?Number(u):null;if(f===null||f>l+oo)return{accessToken:s,expiresAt:f??l+3600,refreshed:!1}}let c=await ce({hub:r,path:"/oauth/refresh",body:{plugin:o,tenantId:i},parseResponse:ln}),p=c.expires_in?l+c.expires_in:u?Number(u):l+3600;return await t.set_access_token(c.access_token),await t.set_expires_at(String(p)),c.refresh_token&&await t.set_refresh_token(c.refresh_token),c.scope&&await t.set_scope(c.scope),{accessToken:c.access_token,expiresAt:p,refreshed:!0}}async function io(e,n){e._refreshAuth=async()=>(await At(n,{forceRefresh:!0})).accessToken}async function Rn(e,n){let t=Ie(e.projectApiKey),r={permissionId:n.permissionId,permissionToken:n.permissionToken,plugin:n.plugin,endpoint:n.endpoint,args:n.args,tenantId:n.tenantId,expiresAt:n.expiresAt};return t==="development"&&(r.deliveryUrl=Re({deliveryUrl:n.deliveryUrl})),ce({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:r,parseResponse:cn})}function Sn(e){return`Approval required. Visit ${e} to approve or deny, then tell the agent to retry this action.`}function gs(e){return e==="oauth_2"||e==="managed"?"oauth":e==="bot_token"?"bot_token":"api_key"}async function
|
|
13
|
+
</script></body></html>`}var ls=[".corsair.dev"];function ds(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function ps(e){try{let{hostname:n,protocol:t}=new URL(e);return t!=="http:"&&t!=="https:"?!1:ds(n)?!0:ls.some(r=>n===r.slice(1)||n.endsWith(r))}catch{return!1}}function to(e){return!e||!ps(e)?null:{"Access-Control-Allow-Origin":e,"Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"content-type, x-corsair-signature, x-corsair-timestamp, x-corsair-project, x-corsair-nonce, access-control-request-private-network","Access-Control-Allow-Private-Network":"true","Access-Control-Max-Age":"0",Vary:"Origin"}}function ro(e,n){if(!n)return e;let t=new Headers(e.headers);for(let[r,o]of Object.entries(n))t.set(r,o);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function bt(e,n){let t=new URL(e);return n.error?(t.searchParams.set("error",n.error),t.toString()):n.connectedPlugin?(t.searchParams.set("connected",n.connectedPlugin),t.toString()):(n.status!==void 0&&t.searchParams.set("status",Buffer.from(JSON.stringify(n.status)).toString("base64url")),t.toString())}async function Ct(e,n){let t=J(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=ge(o,t.signingSecret);if(!i)return{type:"json",status:400,body:{error:"Invalid or expired delivery token"}};let a=Cn(`browser:${i.jti}`,de);if(!a.ok)return{type:"json",status:400,body:{error:a.error}};try{if(Pe(i))return i.hubSuccessUrl?i.credentials?(await kn(e,{plugin:i.plugin,tenantId:i.tenantId,credentials:i.credentials}),{type:"redirect",url:bt(i.hubSuccessUrl,{connectedPlugin:i.plugin})}):{type:"redirect",url:bt(i.hubSuccessUrl,{error:"Credential delivery missing credentials"})}:{type:"json",status:400,body:{error:"Credential delivery missing hubSuccessUrl"}};if(Je(i)){if(!i.permissionToken)return{type:"json",status:400,body:{error:"Permission delivery missing permission token"}};await ht(e,i.permissionToken,i.deliveryMode==="permission.approve"?"approved":"denied")}else if(ze(i)){if(!i.accessToken)return{type:"json",status:400,body:{error:"Managed OAuth delivery missing access_token"}};await Oe(e,{plugin:i.plugin,tenantId:i.tenantId,accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,scope:i.scope})}else{if(!In(i)||!i.code||!i.state||!i.redirectUri)return{type:"json",status:400,body:{error:"Invalid BYO OAuth delivery token"}};await Ve(e,{code:i.code,state:i.state,redirectUri:i.redirectUri})}}catch(s){let u=s instanceof Error?s.message:"Hub delivery failed";return Pe(i)&&i.hubSuccessUrl?{type:"redirect",url:bt(i.hubSuccessUrl,{error:u})}:Pe(i)&&i.hubOrigin&&i.requestId?{type:"text",status:400,headers:{"Content-Type":"text/html; charset=utf-8"},body:no({hubOrigin:i.hubOrigin,requestId:i.requestId,ok:!1,error:u})}:{type:"json",status:400,body:{error:u}}}return{type:"redirect",url:i.hubSuccessUrl}}async function wt(e,n){let t=J(e),r=await kt(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,a=o.headers;return o.body&&typeof o.body=="object"&&!(o.body instanceof ArrayBuffer)?{type:"json",status:i,body:o.body,headers:a}:{type:"text",status:i,body:typeof o.body=="string"?o.body:o.body?JSON.stringify(o.body):null,headers:a}}function Pt(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 Tt(e,n){return n.method==="GET"?Ct(e,n.url):wt(e,{headers:n.headers,body:n.body??""})}async function vt(e,n){try{let t=await Tt(e,n);return Pt(t)}catch(t){if(t instanceof ue)return Response.json({error:t.message},{status:503});throw t}}async function Te(e,n){let t=n.method.toUpperCase(),r=to(n.headers.get("origin"));if(t==="OPTIONS")return r?new Response(null,{status:204,headers:r}):Response.json({error:"Method not allowed"},{status:405});if(t!=="GET"&&t!=="POST")return Response.json({error:"Method not allowed"},{status:405});let o=await vt(e,{method:t,url:n.url,headers:n.headers,body:t==="POST"?await n.text():void 0});return ro(o,r)}var re=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 oo=300;async function At(e,n){let{keys:t,hub:r,plugin:o,tenantId:i}=e,a=n?.forceRefresh??!1,[s,u,d]=await Promise.all([t.get_access_token(),t.get_expires_at(),t.get_refresh_token()]);if(!s&&!d)throw new re(o,"managed");let l=Math.floor(Date.now()/1e3);if(!a&&s&&u&&Number(u)>l+oo)return{accessToken:s,expiresAt:Number(u),refreshed:!1};if(!d&&s&&!a){let f=u?Number(u):null;if(f===null||f>l+oo)return{accessToken:s,expiresAt:f??l+3600,refreshed:!1}}let c=await ce({hub:r,path:"/oauth/refresh",body:{plugin:o,tenantId:i},parseResponse:ln}),p=c.expires_in?l+c.expires_in:u?Number(u):l+3600;return await t.set_access_token(c.access_token),await t.set_expires_at(String(p)),c.refresh_token&&await t.set_refresh_token(c.refresh_token),c.scope&&await t.set_scope(c.scope),{accessToken:c.access_token,expiresAt:p,refreshed:!0}}async function io(e,n){e._refreshAuth=async()=>(await At(n,{forceRefresh:!0})).accessToken}async function Rn(e,n){let t=Ie(e.projectApiKey),r={permissionId:n.permissionId,permissionToken:n.permissionToken,plugin:n.plugin,endpoint:n.endpoint,args:n.args,tenantId:n.tenantId,expiresAt:n.expiresAt};return t==="development"&&(r.deliveryUrl=Re({deliveryUrl:n.deliveryUrl})),ce({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:r,parseResponse:cn})}function Sn(e){return`Approval required. Visit ${e} to approve or deny, then tell the agent to retry this action.`}function gs(e){return e==="oauth_2"||e==="managed"?"oauth":e==="bot_token"?"bot_token":"api_key"}function fs(e){return{tenantId:e.tenantId,plugin:e.plugin,authKind:gs(e.authType),authType:e.authType,status:e.status,connected:e.connected,verified:e.verified,missingFields:e.missingFields}}async function ys(e){if(!e.hub||!e.database||!e.kek)return;let n={database:e.database,kek:e.kek,plugins:e.plugins},t=x(e.plugin);if(!t)return;let r=e.tenantId?.trim()||"default",o=await _e(n,e.plugin,r);o&&so(e.hub,fs({tenantId:r,plugin:e.plugin.id,authType:t,status:o.status,connected:o.connected,verified:e.verified??o.connected,missingFields:o.missingRequiredFields}))}function so(e,n){ce({hub:e,path:"/connections/report",body:n,parseResponse:()=>({ok:!0})}).catch(()=>{})}function Ye(e){ys(e).catch(()=>{})}function ao(e){return{delivery:n=>Te(e,n),deliveryOptions:n=>Te(e,n)}}var uo=1200*1e3;function xt(){return te()}function It(){return uo}function Rt(e,n){return Ge(e,n,uo)}function St(e,n){return Y(e,n)}function _t(e){return we(e)}var co=600*1e3;function Et(){return te()}function Dt(){return co}function Ot(e,n){return Ge(e,n,co)}function Mt(e,n){return Y(e,n)}function Ht(e){return ft(e)}function Ft(e){return we(e)}function Ut(){return te()}function Bt(e,n,t){return vn(e,n,Math.floor(t.getTime()/1e3))}function Nt(e,n){return Y(e,n)}function $t(e){return we(e)}function _n(e,n){let t=[];e||t.push("database"),n||t.push("kek");let r={};return new Proxy(r,{get(o,i){let a=t.length>1;throw new Error(`corsair.keys.${String(i)}: Cannot access keys because ${t.join(" and ")} ${a?"are":"is"} not configured. Provide both 'database' and 'kek' in createCorsair() to enable key management.
|
|
14
14
|
|
|
15
|
-
To generate a KEK, run: openssl rand -base64 ${We}`)}})}function He(e){return!!(e?.baseUrl?.trim()&&e?.redirectUri?.trim())}import*as Qe from"crypto";function fe(e,n){return Buffer.from(JSON.stringify({plugin:e,tenantId:n,iat:Date.now()})).toString("base64url")}function Lt(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 Fe(e,n){let t=Qe.createHmac("sha256",n).update(e).digest("base64url");return`${e}.${t}`}var Wt=600*1e3;function En(e,n){let t=e.lastIndexOf(".");if(t===-1)return null;let r=e.slice(0,t),o=e.slice(t+1),i=Qe.createHmac("sha256",n).update(r).digest("base64url"),a=Buffer.from(o,"base64url"),s=Buffer.from(i,"base64url");return a.length!==s.length||!Qe.timingSafeEqual(a,s)?null:Lt(r,{maxAgeMs:Wt})}function jt(e,n){return`[auth-missing:${e}] Authentication required. Direct the user to connect their account: ${n}`}async function
|
|
15
|
+
To generate a KEK, run: openssl rand -base64 ${We}`)}})}function He(e){return!!(e?.baseUrl?.trim()&&e?.redirectUri?.trim())}import*as Qe from"crypto";function fe(e,n){return Buffer.from(JSON.stringify({plugin:e,tenantId:n,iat:Date.now()})).toString("base64url")}function Lt(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 Fe(e,n){let t=Qe.createHmac("sha256",n).update(e).digest("base64url");return`${e}.${t}`}var Wt=600*1e3;function En(e,n){let t=e.lastIndexOf(".");if(t===-1)return null;let r=e.slice(0,t),o=e.slice(t+1),i=Qe.createHmac("sha256",n).update(r).digest("base64url"),a=Buffer.from(o,"base64url"),s=Buffer.from(i,"base64url");return a.length!==s.length||!Qe.timingSafeEqual(a,s)?null:Lt(r,{maxAgeMs:Wt})}function jt(e,n){return`[auth-missing:${e}] Authentication required. Direct the user to connect their account: ${n}`}async function ms(e,n){let t=e.hub;if(!t||!n.database||!n.kek)return null;try{return(await rt(t,{tenantId:n.tenantId,plugin:n.plugin,database:n.database,kek:n.kek,plugins:n.plugins})).connectUrl}catch{return null}}async function hs(e){let n=e.hub;if(n&&e.database&&e.kek)try{let r=await rt(n,{tenantId:e.tenantId,plugin:e.plugin,database:e.database,kek:e.kek,plugins:e.plugins});return e.manual?.onAuthMissing?e.manual.onAuthMissing({plugin:e.pluginId,connectUrl:r.connectUrl,state:r.token}):jt(e.pluginId,r.connectUrl)}catch{return`[auth-missing:${e.pluginId}:${e.authType}] Authentication required. Could not create connect link. Check hub configuration and server logs.`}let t=await ms({manual:e.manual,hub:e.hub},{plugin:e.plugin,tenantId:e.tenantId,database:e.database,kek:e.kek,plugins:e.plugins});return t?jt(e.pluginId,t):`[auth-missing:${e.pluginId}:${e.authType}]`}function ks(e,n,t){let r=Fe(fe(e,n.tenantId??t??"default"),n.kek),o=new URL(n.baseUrl);o.searchParams.set("state",r);let i=o.toString();return n.onAuthMissing?n.onAuthMissing({plugin:e,connectUrl:i,state:r}):jt(e,i)}async function lo(e){let n=e.tenantId??"default",t=e.error.pluginId;return e.manual&&He(e.manual)&&e.manual.oauthConfig&&e.manual.kek&&e.error.authType==="oauth_2"?ks(t,{...e.manual,baseUrl:e.manual.baseUrl,kek:e.manual.kek},e.tenantId):e.hub&&e.plugin&&e.kek&&e.database&&e.plugins?hs({manual:e.manual,hub:e.hub,plugin:e.plugin,pluginId:t,tenantId:n,authType:e.error.authType,database:e.database,kek:e.kek,plugins:e.plugins}):e.error.message}var bs=async(e,n)=>(console.error(`[corsair:${n.pluginId}:${n.operation}]`,{error:e.message,input:n.input}),{maxRetries:0});async function po(e,n,t,r,o){let i={pluginId:n,operation:t,input:r,originalError:e},a=Object.keys(o).find(d=>o[d]?.match(e,i));return await(o[a||"DEFAULT"]?.handler||bs)(e,i)}import{randomBytes as ws}from"crypto";import{v4 as Ps}from"uuid";var Kt="Permission approval required. Set manual.approvalBaseUrl (or use hub for hosted approval) so an approval URL can be generated. Optionally set manual.onApprovalRequired to customize the agent message.";function Zt(e){return e?e.approvalBaseUrl!==void 0||e.onApprovalRequired!==void 0:!1}function go(e,n){return`${e.replace(/\/+$/,"")}/${n}`}function qt(e){return Sn(e)}async function Gt(e,n){if(Zt(e.manual)){let r=e.manual?.approvalBaseUrl?.trim();return r?go(r,n.token):null}let t=e.hub;if(!t)return null;try{return(await Rn(t,{permissionId:n.id,permissionToken:n.token,plugin:n.plugin,endpoint:n.endpoint,args:Cs(n.args),tenantId:n.tenant_id,expiresAt:n.expires_at})).approvalUrl}catch{return null}}function Cs(e){try{return JSON.parse(e)}catch{return e}}async function Dn(e,n){if(!(n.status==="pending"||n.status==="approved"))return{...n,approvalUrl:null};let r=await Gt(e,n);return{...n,approvalUrl:r}}async function Jt(e){let{permissionsOptions:n,manual:t,hub:r,permissionId:o,permissionToken:i,plugin:a,endpoint:s,args:u,tenantId:d,expiresAt:l,operationPath:c}=e;if(n?.formatAsyncMessage)return n.formatAsyncMessage({token:i,id:o,plugin:a,endpoint:s,args:u});let f=await Gt({manual:t,hub:r},{id:o,token:i,plugin:a,endpoint:s,args:JSON.stringify(u),tenant_id:d,expires_at:l});return Zt(t)?f?t?.onApprovalRequired?t.onApprovalRequired({approvalUrl:f}):qt(f):Kt:r?f?qt(f):`Action '${c}' requires user approval before it can run. Could not create approval link. Check hub configuration and server logs.`:Kt}var Ts={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 vs(e,n,t){return t!==void 0?t:Ts[n][e]}function zt(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 yo(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 fo(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 mo(e){let n=vs(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}'.`,`
|
|
16
16
|
Action: ${r}`,`
|
|
17
17
|
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(),a=e.tenantId??"default",s=await e.db.db.selectFrom("corsair_permissions").selectAll().where("plugin","=",e.pluginId).where("endpoint","=",e.endpointPath).where("args","=",o).where("tenant_id","=",a).where("expires_at",">",i).where("status","in",["pending","approved","executing"]).orderBy("created_at","desc").limit(1).executeTakeFirst();if(s){if(s.status==="approved"){let g=e.db,y=s.id;return{result:"allow",onComplete:async()=>{await g.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",y).execute()}}}return s.status==="executing"?{result:"allow"}:(console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval already pending.`,`
|
|
18
18
|
Action: ${r}`,`
|
|
19
19
|
Permission ID: ${s.id}`,`
|
|
20
|
-
Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?fo(e.db,s.id,e.timeoutMs??600*1e3):{result:"blocked",reason:"pending",id:s.id,token:s.token,expiresAt:s.expires_at})}let u=
|
|
20
|
+
Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?fo(e.db,s.id,e.timeoutMs??600*1e3):{result:"blocked",reason:"pending",id:s.id,token:s.token,expiresAt:s.expires_at})}let u=Ps(),d=ws(32).toString("hex"),l=e.timeoutMs??600*1e3,c=new Date(Date.now()+l).toISOString();return await e.db.db.insertInto("corsair_permissions").values({id:u,created_at:new Date,updated_at:new Date,token:d,plugin:e.pluginId,endpoint:e.endpointPath,args:o,tenant_id:a,status:"pending",expires_at:c}).execute(),console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval required.`,`
|
|
21
21
|
Action: ${r}`,`
|
|
22
22
|
Permission ID: ${u}`,`
|
|
23
23
|
Permission token: ${d}`,`
|
|
24
24
|
Expires at: ${c}`,`
|
|
25
|
-
Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?fo(e.db,u,l):{result:"blocked",reason:"pending",id:u,token:d,expiresAt:c}}function vs(e){return typeof e=="function"}function Vt({endpoints:e,hooks:n,ctx:t,tree:r,pluginId:o,errorHandlers:i,currentPath:a=[],keyBuilder:s,permissionsConfig:u,endpointMeta:d,database:l,permissionsOptions:c,tenantId:p,manualConfig:f,hubConfig:g,plugin:y,kek:m,allPlugins:h}){for(let[P,w]of Object.entries(e)){let k=n?.[P];if(vs(w)){let b=k,C=[...a,P].join("."),B=async(_={})=>{let D;if(u){let N=d?.[C],{result:nn,reason:Z,onComplete:$e,token:Q,id:be,expiresAt:$}=await mo({pluginId:o,endpointPath:C,args:_,mode:u.mode,override:u.overrides?.[C],riskLevel:N?.riskLevel??"write",meta:N,db:l,timeoutMs:c?zt(c.timeout):void 0,tenantId:p,approvalMode:c?.mode});if(nn==="blocked"){let G;throw Z==="denied"?G=`Action '${C}' was denied by the user. Await further instructions before proceeding.`:Z==="policy"?G=`Action '${C}' is blocked by the permission policy. Update the corsair config to allow it.`:Z==="timeout"?G=`Action '${C}' timed out waiting for approval.`:Q&&be?G=await Jt({permissionsOptions:c,manual:f,hub:g,permissionId:be,permissionToken:Q,plugin:o,endpoint:C,args:_,tenantId:p??"default",expiresAt:$??new Date(Date.now()+(c?zt(c.timeout):600*1e3)).toISOString(),operationPath:C}):G=`Action '${C}' requires user approval before it can run.`,new Error(G)}D=$e}let E=async(N,nn,Z)=>{try{return await w(nn,Z)}catch($e){if($e instanceof Error){let Q=await po($e,o,C,typeof Z=="object"&&Z!==null?Z:{args:Z},i);if(N<(Q.maxRetries||0)){let be=N+1;console.log(`Retrying (${be} / ${Q.maxRetries})...`);let $;if(Q.headersRetryAfterMs)$=Q.headersRetryAfterMs;else switch(Q.retryStrategy){case"exponential_backoff":$=Math.pow(2,be-1)*1e3;break;case"exponential_backoff_jitter":let G=Math.pow(2,be-1)*1e3,zo=(Math.random()-.5)*1e3;$=Math.max(0,G+zo);break;case"linear_1s":$=1e3;break;case"linear_2s":$=2e3;break;case"linear_3s":$=3e3;break;case"linear_4s":$=4e3;break;default:$=1e3;break}await new Promise(G=>setTimeout(G,$)),await E(be,nn,Z),console.log(`[corsair:${o}:${C}] Retry strategy:`,Q)}}throw $e}},he;try{he=s?await s(t,"endpoint"):void 0}catch(N){if(N instanceof re)return y&&g&&Ye({hub:g,database:l,kek:m,plugins:h??[],plugin:y,tenantId:p,verified:!1}),lo({error:N,manual:f,hub:g,plugin:y,tenantId:p,database:l,kek:m,plugins:h});throw N}if(!b?.before&&!b?.after){let N=await E(0,{...t,key:he},_);return await D?.(),y&&g&&Ye({hub:g,database:l,kek:m,plugins:h??[],plugin:y,tenantId:p,verified:!0}),N}let Ne={...t,key:he},ke=b.before?await b.before(Ne,_):{ctx:Ne,args:_,continue:!0,passToAfter:void 0};if(ke.continue===!1)return;let dr=await E(0,ke.ctx,ke.args);return await b.after?.(ke.ctx,dr,ke.passToAfter),await D?.(),y&&g&&Ye({hub:g,database:l,kek:m,plugins:h??[],plugin:y,tenantId:p,verified:!0}),dr};r[P]=B}else if(w&&typeof w=="object"){let b={};Vt({endpoints:w,hooks:k,ctx:t,tree:b,pluginId:o,errorHandlers:i,currentPath:[...a,P],keyBuilder:s,permissionsConfig:u,endpointMeta:d,database:l,permissionsOptions:c,tenantId:p,manualConfig:f,hubConfig:g,plugin:y,kek:m,allPlugins:h}),r[P]=b}}}function As(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function Yt({webhooks:e,hooks:n,ctx:t,webhooksTree:r,keyBuilder:o}){for(let[i,a]of Object.entries(e)){let s=n?.[i];if(As(a)){let u=s,d=async l=>{let c=(f,g)=>a.handler(f,g),p=o?await o(t,"webhook"):void 0;return!u?.before&&!u?.after?c({...t,key:p},l):(async()=>{let f={...t,key:p},g=u.before?await u.before(f,l):{ctx:f,args:l,continue:!0,passToAfter:void 0};if(g.continue===!1)return;let y=await c(g.ctx,g.args);return y?.success===!0&&await u.after?.(g.ctx,y,g.passToAfter),y})()};r[i]={match:a.match,handler:d}}else if(a&&typeof a=="object"){let u={};Yt({webhooks:a,hooks:s,ctx:t,webhooksTree:u,keyBuilder:o}),r[i]=u}}}function xs(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 Is(e,n,t,r,o){return e?Gn(e.db,n,t,r,o):{findByEntityId:async()=>null,existsByEntityId:async()=>!1,findIdByEntityId: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 Qt(e,n){let{database:t,tenantId:r,kek:o,rootErrorHandlers:i,permissionsOptions:a,manualConfig:s,hubConfig:u}=n,d={},l={};for(let c of e)d[c.id]={},l[c.id]={};for(let c of e){let p=c.schema,f=r??"default",g=xs(t,c.id,f);if(p?.entities){let E={};for(let[he,Ne]of Object.entries(p.entities)){let ke=t?Gn(t.db,g,he,p.version,Ne):Is(void 0,g,he,p.version,Ne);E[he]=ke}l[c.id].db=E,d[c.id].db=E}let y=c.options,m=c.authConfig,h;if(t&&o&&y?.authType){let E=m?.[y.authType]?.account??[];h=S({authType:y.authType,integrationName:c.id,tenantId:f,kek:o,database:t,extraAccountFields:E}),d[c.id].keys=h}let P={database:t,db:l[c.id]?.db??{},$getAccountId:g,...c.options?{options:c.options}:{},...h?{keys:h,authType:y?.authType}:{},tenantId:f,...u?{hub:u}:{}},w=c.endpoints??{},k=c.hooks,b={...i,...c.errorHandlers},C={},B=c.options?.permissions;Vt({endpoints:w,hooks:k,ctx:P,tree:C,pluginId:c.id,errorHandlers:b,currentPath:[],keyBuilder:c.keyBuilder,permissionsConfig:B,endpointMeta:c.endpointMeta,database:t,permissionsOptions:a,tenantId:r,manualConfig:s?{...s,oauthConfig:c.oauthConfig,kek:o,tenantId:f}:void 0,hubConfig:u,plugin:c,kek:o,allPlugins:e}),Object.keys(C).length>0&&(d[c.id].api=C),P.endpoints=C;let _=c.webhooks??{},D=c.webhookHooks;if(Object.keys(_).length>0){let E={};Yt({webhooks:_,hooks:D,ctx:P,webhooksTree:E,keyBuilder:c.keyBuilder}),d[c.id].webhooks=E,c.pluginWebhookMatcher&&(d[c.id].pluginWebhookMatcher=c.pluginWebhookMatcher),c.pluginTenantWebhookMatcher&&(d[c.id].pluginTenantWebhookMatcher=c.pluginTenantWebhookMatcher)}}return d}function ho(e,n,t){let r={};for(let o of e){let i=o.options,a=o.authConfig;if(i?.authType){let s=a?.[i.authType]?.integration??[],u=I({authType:i.authType,integrationName:o.id,kek:t,database:n,extraIntegrationFields:s});r[o.id]=u}}return r}var Rs="createCorsair({ approval: ... }) is deprecated. Rename to permissions: { timeout, onTimeout, mode }.";function ko(e){let{permissions:n,approval:t}=e;if(n&&t)throw new Error("createCorsair was given both permissions and approval config. Use permissions only \u2014 approval is deprecated.");return t?(console.warn(`[corsair] ${Rs}`),t):n}import*as bo from"querystring";function ve(e){let{oauthConfig:n,clientId:t,redirectUri:r,state:o}=e,i={...n.authParams,client_id:t,redirect_uri:r,response_type:"code",scope:n.scopes.join(" "),state:o};return`${n.authUrl}?${bo.stringify(i)}`}var W=class extends Error{code;constructor(n,t){super(t),this.name="ConnectError",this.code=n}};function Ss(e){let n=e.oauthConfig;if(!n)throw new W("plugin_has_no_oauth_config",`Plugin '${e.id}' has no oauthConfig`);return n}async function Xt(e,n){let t=T(e,()=>new W("invalid_corsair_instance","Invalid corsair instance"));if(!t.database)throw new W("no_database","No database configured on corsair instance");let r=t.manual?.redirectUri;if(!r)throw new W("no_redirect_uri","No redirectUri configured. Set manual.redirectUri in createCorsair().");let o=En(n,t.kek);if(!o)throw new W("invalid_state","Invalid or tampered state parameter");let{plugin:i,tenantId:a}=o,s=M(t,i,p=>new W("plugin_not_found",p)),u=Ss(s),l=await I({authType:"oauth_2",integrationName:i,kek:t.kek,database:t.database}).get_client_id();if(!l)throw new W("client_id_not_configured",`client_id not configured for '${i}'`);let c=ve({oauthConfig:u,clientId:l,redirectUri:r,state:n});return{plugin:i,tenantId:a,providerName:u.providerName,oauthUrl:c,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 Co(e){let n={error:e.code,message:e.message,...e.extra};return R(e.status,n)}function ye(e){return new A(404,"not_found",e)}function oe(e,n={}){return new A(400,"bad_request",e,n)}function wo(e,n){return M(e,n,t=>ye(t))}async function Po(e,n){let t=e.options?.authType;if(!t||!n.database||!n.kek)return{configured:!1,missingFields:[]};let r=I({authType:t,integrationName:e.id,kek:n.kek,database:n.database}),o=O[t].integration,i=r,a;try{a=await Promise.all(o.map(d=>i[`get_${d}`]()))}catch{a=o.map(()=>null)}let s=o.filter((d,l)=>a[l]==null),u;return t==="oauth_2"?u=!s.includes("client_id")&&!s.includes("client_secret"):u=s.length===0,{configured:u,missingFields:s}}async function To(e,n){let t=e.options?.authType??null,r=e.oauthConfig,{configured:o,missingFields:i}=await Po(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 On(){return{ok:!0}}async function Mn(e){return Promise.all(e.plugins.map(n=>To(n,e)))}async function Hn(e,n){let t=wo(e,n);return To(t,e)}async function _s(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 vo(e,n){let t=await _s(e,n),r=t.filter(o=>o.hasCredentials).map(o=>o.integrationName);return{id:n,accounts:t,connectedPlugins:r}}async function Fn(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 a=!!r.dek;i.accounts.push({integrationName:r.integrationName,hasCredentials:a}),a&&i.connectedPlugins.push(r.integrationName)}}return[...n.values()]}async function Un(e,n){if(!n)throw oe("Tenant id must be a non-empty string");return vo(e,n)}async function Bn(e,n){let t=n?.id?.trim();if(!t)throw oe("Tenant id is required",{missingFields:["id"]});return vo(e,t)}async function Nn(e,n){let t=n?.trim()||"default",r={},o=await qe(e,t);for(let i of o)r[i.plugin]=yn(i);for(let i of e.plugins)i.id in r||(!i.options?.authType||!e.database||!e.kek?r[i.id]="missing_credentials":r[i.id]="not_connected");return r}async function er(e,n){if(!e.database)throw ye(`Permission '${n}' not found`);let t=await e.database.db.selectFrom("corsair_permissions").selectAll().where("id","=",n).executeTakeFirst();if(!t)throw ye(`Permission '${n}' not found`);return Dn(e,t)}function Es(e){if(!e.oauthConfig)throw oe(`Plugin '${e.id}' has no oauthConfig`)}function Ds(e){if(!e.manual)throw new A(500,"connect_not_configured","createCorsair was not given manual config. Set { manual: { baseUrl, redirectUri } } to enable manual connect routes.");return e.manual}function nr(e){let n=Ds(e);if(!n.baseUrl?.trim()||!n.redirectUri?.trim())throw new A(500,"connect_not_configured","Manual connect requires manual.baseUrl and manual.redirectUri. Use hub for hosted connect, or set both URLs for manual OAuth.");return n}function Os(e){let n=!!e.hub,t=He(e.manual);if(!n&&!t)throw new A(500,"connect_not_configured","createCorsair was not given connect config. Set hub: { ... } for Hub mode, or manual: { baseUrl, redirectUri } for manual connect.")}function Ao(e){if(!e.database||!e.kek)throw new A(500,"database_not_configured","A database and kek are required to issue connect links.")}async function Ms(e,n){let t=n?.plugin?.trim();if(!t)throw oe("Plugin id is required",{missingFields:["plugin"]});let r=n.tenantId?.trim()||"default",o=wo(e,t);Es(o);let i=nr(e);Ao(e);let a=await Po(o,e);if(!a.configured)throw new A(400,"missing_credentials",`Plugin '${t}' is missing OAuth client credentials`,{missingFields:a.missingFields});let s=Fe(fe(t,r),e.kek),u;try{u=new URL(i.baseUrl)}catch{throw new A(500,"connect_misconfigured","manual.baseUrl is not a valid URL. Set a full URL including protocol (e.g. https://app.example.com/connect).")}return u.searchParams.set("state",s),{connectUrl:u.toString(),expiresAt:new Date(Date.now()+Wt).toISOString()}}async function Hs(e,n,t){Ao(n);let o={tenantId:t.tenantId?.trim()||"default",oauthMode:t.oauthMode},i=t.plugin?.trim();i&&(o.plugin=i);let a=t.providerName?.trim();a&&(o.providerName=a);let s=await hn(e,o);return{connectUrl:s.connectUrl,expiresAt:s.expiresAt}}async function $n(e,n,t){return Os(n),n.hub?Hs(e,n,t):Ms(n,t)}async function Ln(e,n,t){if(n.hub&&!He(n.manual))throw new A(400,"hub_mode","resolve is not used with hub config. Redirect users to connectUrl from createLink.");let r=t?.trim();if(!r)throw oe("state is required",{missingFields:["state"]});nr(n);try{return await Xt(e,r)}catch(o){if(o instanceof W)switch(o.code){case"invalid_state":throw oe("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 Wn(e,n,t){if(n.hub&&!He(n.manual))throw new A(400,"hub_mode","oauthCallback is not used with hub config. Hub delivers tokens to your deliveryUrl.");let r=t?.code?.trim(),o=t?.state?.trim(),i=[];if(r||i.push("code"),o||i.push("state"),i.length)throw oe("Missing required fields",{missingFields:i});let a=nr(n),{processOAuthCallback:s}=await import("./oauth.js");try{return await s(e,{code:r,state:o,redirectUri:a.redirectUri})}catch(u){if(u instanceof Error&&u.name==="OAuthCallbackError")switch(u.code){case"invalid_state":throw oe("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 tr(e,n){if(!e.database)throw ye("Permission not found");let t=await e.database.db.selectFrom("corsair_permissions").selectAll().where("token","=",n).executeTakeFirst();if(!t)throw ye("Permission not found");return Dn(e,t)}async function xo(e,n){return"id"in n?er(e,n.id):tr(e,n.token)}var Io=[{method:"GET",pattern:"/ok",handler:async()=>R(200,On())},{method:"GET",pattern:"/tenants",handler:async({internal:e})=>R(200,await Fn(e))},{method:"POST",pattern:"/tenants",handler:async({internal:e,body:n})=>R(201,await Bn(e,n))},{method:"GET",pattern:"/tenants/:id",handler:async({internal:e,params:n})=>R(200,await Un(e,n.id))},{method:"GET",pattern:"/plugins",handler:async({internal:e})=>R(200,await Mn(e))},{method:"GET",pattern:"/plugins/:id",handler:async({internal:e,params:n})=>R(200,await Hn(e,n.id))},{method:"GET",pattern:"/connection-status",handler:async({internal:e,query:n})=>R(200,await Nn(e,n.tenantId))},{method:"GET",pattern:"/permissions/:id",handler:async({internal:e,params:n})=>R(200,await er(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 tr(e,t)):R(400,{error:"bad_request",message:"token is required",missingFields:["token"]})}},{method:"POST",pattern:"/connect/links",handler:async({corsair:e,internal:n,body:t})=>R(200,await $n(e,n,t))},{method:"GET",pattern:"/connect/resolve",handler:async({corsair:e,internal:n,query:t})=>R(200,await Ln(e,n,t.state??""))},{method:"POST",pattern:"/connect/oauth/callback",handler:async({corsair:e,internal:n,body:t})=>R(200,await Wn(e,n,t))}];(()=>{let e=new Set;for(let n of Io){let t=`${n.method} ${n.pattern}`;if(e.has(t))throw new Error(`Duplicate management route registered: ${t}`);e.add(t)}})();function Fs(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 a=t[i],s=r[i];if(a.startsWith(":"))o[a.slice(1)]=decodeURIComponent(s);else if(a!==s)return null}return o}function Us(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 Bs(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 Ns="/api/corsair";function Ae(e,n={}){let t=n.basePath??Ns,r=T(e,()=>new Error("managementHandler: invalid corsair instance (missing internal config)"));return async o=>{try{let i=new URL(o.url),a=Us(i.pathname,t),s=o.method.toUpperCase();if(s==="OPTIONS"||a==="/"||a==="")return await Te(e,o);if(s!=="GET"&&s!=="POST")return R(405,{error:"method_not_allowed",message:`Method ${s} not allowed`});let u=Object.fromEntries(i.searchParams);for(let d of Io){if(d.method!==s)continue;let l=Fs(d.pattern,a);if(!l)continue;let c=await Bs(o);return await d.handler({corsair:e,internal:r,req:o,params:l,query:u,body:c})}throw ye(`No route for ${s} ${a}`)}catch(i){if(n.onError){let s=await n.onError(i,o);if(s)return s}if(i instanceof A)return Co(i);let a=i instanceof Error?i.message:"Internal server error";return R(500,{error:"internal_error",message:a})}}}function $s(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[u,d]of Object.entries(e.headers))if(d!=null)if(Array.isArray(d))for(let l of d)i.append(u,l);else i.set(u,d);let a=e.method!=="GET"&&e.method!=="HEAD",s={method:e.method,headers:i};return a&&e.body!==void 0&&(s.body=typeof e.body=="string"?e.body:JSON.stringify(e.body),i.has("content-type")||i.set("content-type","application/json")),new Request(o,s)}async function Ls(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 Ro(e,n){let t=Ae(e,n);return async(r,o,i)=>{try{let a=await t($s(r));await Ls(o,a)}catch(a){i(a)}}}function So(e,n){let t=Ae(e,n);return r=>t(r.req.raw)}function _o(e,n){let t=Ae(e,n);return{GET:t,POST:t,OPTIONS:t}}function Eo(e){let n={[Xe]:e};return{ok:On,tenants:{list:()=>Fn(e),create:t=>Bn(e,t),get:t=>Un(e,t)},plugins:{list:()=>Mn(e),get:t=>Hn(e,t)},connectionStatus:{get:t=>Nn(e,t?.tenantId)},permissions:{get:t=>xo(e,t)},connect:{createLink:t=>$n(n,e,t),resolve:t=>Ln(n,e,t),oauthCallback:t=>Wn(n,e,t)}}}async function Do(e,n,t,r,o="pending"){if(!e)return null;try{let i=mr(),a=new Date;return await e.db.insertInto("corsair_events").values({id:i,created_at:a,updated_at:a,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 Ws(e,n,t,r="pending"){try{let o=await e.$getAccountId();return Do(e.database,o,n,t,r)}catch(o){return console.warn("Failed to log event:",o),null}}import*as Oo from"https";import*as Mo from"querystring";function jn(e,n,t,r,o){let i=new URL(r.tokenUrl),a=r.tokenAuthMethod==="basic";return new Promise((s,u)=>{let d={code:e.trim(),redirect_uri:o,grant_type:"authorization_code"};a||(d.client_id=n,d.client_secret=t);let l=Mo.stringify(d),c={"Content-Type":"application/x-www-form-urlencoded","Content-Length":Buffer.byteLength(l).toString()};a&&(c.Authorization=`Basic ${Buffer.from(`${n}:${t}`).toString("base64")}`);let p=Oo.request({hostname:i.hostname,...i.port?{port:Number(i.port)}:{},path:i.pathname+i.search,method:"POST",headers:c},f=>{let g="";f.on("data",y=>{g+=y}),f.on("end",()=>{if(f.statusCode!==200){u(new Error(`Token exchange failed (${f.statusCode}): ${g}`));return}try{s(JSON.parse(g))}catch{u(new Error(`Token endpoint returned non-JSON response: ${g}`))}})});p.on("error",f=>u(new Error(`Request failed: ${f.message}`))),p.write(l),p.end()})}var Ho=" ";function K(e){let n=e;return n._def??n.def??{}}function q(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 Uo(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 Bo(e){let n=e.type;return e.element??(typeof n=="string"?void 0:n)}function qn(e,n){let t=n.shape??e.shape;return typeof t=="function"?t():t}function Ue(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 No(e,n){return e.description??n.description}function js(e){let n=e;for(;n;){let t=K(n),r=No(n,t);if(r)return r;let o=q(t);if(ar(o)||o==="ZodPipe"||o==="ZodEffects"||o==="ZodTransform"){n=Uo(t,o);continue}break}}function ar(e){return e==="ZodOptional"||e==="ZodNullable"||e==="ZodDefault"||e==="ZodCatch"}function H(e){let n=K(e),t=q(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??Ue(n)[0]??"unknown");case"ZodEnum":return Ue(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=Bo(n);if(!r)return"unknown[]";let o=K(r),i=q(o)==="ZodUnion",a=H(r);return`${i?`(${a})`:a}[]`}case"ZodRecord":return"{}";case"ZodObject":{let r=qn(e,n),o=Object.entries(r);return o.length===0?"{}":`{ ${o.map(([a,s])=>{let u=q(K(s));return`${u==="ZodOptional"||u==="ZodNullable"?a+"?":a}: ${H(s)}`}).join(", ")} }`}case"ZodUnion":return Ue(n).map(r=>H(r)).join(" | ");case"ZodIntersection":return`${H(n.left)} & ${H(n.right)}`;case"ZodPipe":case"ZodTransform":case"ZodEffects":{let r=Uo(n,t);return r?H(r):"unknown"}default:return(t??"unknown").replace("Zod","").toLowerCase()}}function ie(e){let n=K(e),t=q(n),r=No(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??Ue(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=Ue(n).map(i=>String(i));return{kind:"string",optional:!1,description:r,enum:o}}case"ZodOptional":{let o=j(n),i=o?ie(o):{kind:"unknown",optional:!1};return{...i,optional:!0,description:r??i.description}}case"ZodNullable":{let o=j(n),i=o?ie(o):{kind:"unknown",optional:!1};return{...i,optional:!0,description:r??i.description}}case"ZodDefault":case"ZodCatch":{let o=j(n);return o?{...ie(o),description:r}:{kind:"unknown",optional:!1,description:r}}case"ZodArray":{let o=Bo(n);return{kind:"array",optional:!1,description:r,items:o?ie(o):{kind:"unknown",optional:!1}}}case"ZodObject":{let o=qn(e,n),i={};for(let[a,s]of Object.entries(o))i[a]=ie(s);return{kind:"object",optional:!1,description:r,fields:i}}case"ZodRecord":return{kind:"unknown",optional:!1,description:r};case"ZodUnion":{let o=Ue(n);for(let i of o){let a=K(i);if(q(a)==="ZodObject")return{...ie(i),description:r}}return{kind:"unknown",optional:!1,description:r}}case"ZodIntersection":case"ZodPipe":case"ZodTransform":case"ZodEffects":{let o=j(n);return o?{...ie(o),description:r}:{kind:"unknown",optional:!1,description:r}}default:return{kind:"unknown",optional:!1,description:r}}}function qd(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),a=e.find(l=>l.id===o);if(!a)return null;let s=i;s.startsWith("api.")&&(s=s.slice(4));let u=me(a.endpointMeta,s),d=me(a.endpointSchemas,s);return!u&&!d?null:{input:d?.input?ie(d.input):null,output:d?.output?ie(d.output):null,description:u?.description}}var ur=["equals","contains","startsWith","endsWith","in"],Ks=["equals","gt","gte","lt","lte","in"],qs=["equals"],Zs=["equals","before","after","between"];function $o(e){let n=K(e);switch(q(n)){case"ZodOptional":case"ZodNullable":case"ZodDefault":case"ZodCatch":{let r=j(n);return r?$o(r):null}case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodDate":return"date";default:return null}}function cr(e){let n=K(e),t=q(n);if(ar(t)){let i=j(n);return i?cr(i):{}}if(t!=="ZodObject")return{};let r=qn(e,n),o={};for(let[i,a]of Object.entries(r)){let s=$o(a);s==="string"?o[i]={type:"string",operators:ur}:s==="number"?o[i]={type:"number",operators:Ks}:s==="boolean"?o[i]={type:"boolean",operators:qs}:s==="date"&&(o[i]={type:"date",operators:Zs})}return o}function Lo(e,n){for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return[t,r]}function or(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"&&or(o,i,t)}}function ir(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function sr(e,n,t){for(let[r,o]of Object.entries(e)){let i=[...n,r];ir(o)?t.push(i.join(".")):o!==null&&typeof o=="object"&&sr(o,i,t)}}function lr(e,n){if(n.length===0)return null;let[t,...r]=n,o=Object.entries(e).find(([s])=>s.toLowerCase()===t);if(!o)return null;let[i,a]=o;if(r.length===0)return ir(a)?[i]:null;if(a!==null&&typeof a=="object"&&!ir(a)){let s=lr(a,r);if(s!==null)return[i,...s]}return null}function Wo(e,n){let t=[];t.push(`${e}({`),t.push(" webhookHooks: {");for(let i=0;i<n.length;i++){let a=" ".repeat(i+2);t.push(`${a}${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 a=" ".repeat(i+2);t.push(`${a}},`)}return t.push(" },"),t.push("})"),t.join(`
|
|
26
|
-
`)}var
|
|
25
|
+
Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?fo(e.db,u,l):{result:"blocked",reason:"pending",id:u,token:d,expiresAt:c}}function As(e){return typeof e=="function"}function Vt({endpoints:e,hooks:n,ctx:t,tree:r,pluginId:o,errorHandlers:i,currentPath:a=[],keyBuilder:s,permissionsConfig:u,endpointMeta:d,database:l,permissionsOptions:c,tenantId:p,manualConfig:f,hubConfig:g,plugin:y,kek:m,allPlugins:h}){for(let[P,w]of Object.entries(e)){let k=n?.[P];if(As(w)){let b=k,C=[...a,P].join("."),B=async(_={})=>{let D;if(u){let N=d?.[C],{result:nn,reason:Z,onComplete:$e,token:Q,id:be,expiresAt:$}=await mo({pluginId:o,endpointPath:C,args:_,mode:u.mode,override:u.overrides?.[C],riskLevel:N?.riskLevel??"write",meta:N,db:l,timeoutMs:c?zt(c.timeout):void 0,tenantId:p,approvalMode:c?.mode});if(nn==="blocked"){let G;throw Z==="denied"?G=`Action '${C}' was denied by the user. Await further instructions before proceeding.`:Z==="policy"?G=`Action '${C}' is blocked by the permission policy. Update the corsair config to allow it.`:Z==="timeout"?G=`Action '${C}' timed out waiting for approval.`:Q&&be?G=await Jt({permissionsOptions:c,manual:f,hub:g,permissionId:be,permissionToken:Q,plugin:o,endpoint:C,args:_,tenantId:p??"default",expiresAt:$??new Date(Date.now()+(c?zt(c.timeout):600*1e3)).toISOString(),operationPath:C}):G=`Action '${C}' requires user approval before it can run.`,new Error(G)}D=$e}let E=async(N,nn,Z)=>{try{return await w(nn,Z)}catch($e){if($e instanceof Error){let Q=await po($e,o,C,typeof Z=="object"&&Z!==null?Z:{args:Z},i);if(N<(Q.maxRetries||0)){let be=N+1;console.log(`Retrying (${be} / ${Q.maxRetries})...`);let $;if(Q.headersRetryAfterMs)$=Q.headersRetryAfterMs;else switch(Q.retryStrategy){case"exponential_backoff":$=Math.pow(2,be-1)*1e3;break;case"exponential_backoff_jitter":let G=Math.pow(2,be-1)*1e3,zo=(Math.random()-.5)*1e3;$=Math.max(0,G+zo);break;case"linear_1s":$=1e3;break;case"linear_2s":$=2e3;break;case"linear_3s":$=3e3;break;case"linear_4s":$=4e3;break;default:$=1e3;break}await new Promise(G=>setTimeout(G,$)),await E(be,nn,Z),console.log(`[corsair:${o}:${C}] Retry strategy:`,Q)}}throw $e}},he;try{he=s?await s(t,"endpoint"):void 0}catch(N){if(N instanceof re)return y&&g&&Ye({hub:g,database:l,kek:m,plugins:h??[],plugin:y,tenantId:p,verified:!1}),lo({error:N,manual:f,hub:g,plugin:y,tenantId:p,database:l,kek:m,plugins:h});throw N}if(!b?.before&&!b?.after){let N=await E(0,{...t,key:he},_);return await D?.(),y&&g&&Ye({hub:g,database:l,kek:m,plugins:h??[],plugin:y,tenantId:p,verified:!0}),N}let Ne={...t,key:he},ke=b.before?await b.before(Ne,_):{ctx:Ne,args:_,continue:!0,passToAfter:void 0};if(ke.continue===!1)return;let dr=await E(0,ke.ctx,ke.args);return await b.after?.(ke.ctx,dr,ke.passToAfter),await D?.(),y&&g&&Ye({hub:g,database:l,kek:m,plugins:h??[],plugin:y,tenantId:p,verified:!0}),dr};r[P]=B}else if(w&&typeof w=="object"){let b={};Vt({endpoints:w,hooks:k,ctx:t,tree:b,pluginId:o,errorHandlers:i,currentPath:[...a,P],keyBuilder:s,permissionsConfig:u,endpointMeta:d,database:l,permissionsOptions:c,tenantId:p,manualConfig:f,hubConfig:g,plugin:y,kek:m,allPlugins:h}),r[P]=b}}}function xs(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function Yt({webhooks:e,hooks:n,ctx:t,webhooksTree:r,keyBuilder:o}){for(let[i,a]of Object.entries(e)){let s=n?.[i];if(xs(a)){let u=s,d=async l=>{let c=(f,g)=>a.handler(f,g),p=o?await o(t,"webhook"):void 0;return!u?.before&&!u?.after?c({...t,key:p},l):(async()=>{let f={...t,key:p},g=u.before?await u.before(f,l):{ctx:f,args:l,continue:!0,passToAfter:void 0};if(g.continue===!1)return;let y=await c(g.ctx,g.args);return y?.success===!0&&await u.after?.(g.ctx,y,g.passToAfter),y})()};r[i]={match:a.match,handler:d}}else if(a&&typeof a=="object"){let u={};Yt({webhooks:a,hooks:s,ctx:t,webhooksTree:u,keyBuilder:o}),r[i]=u}}}function Is(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 Rs(e,n,t,r,o){return e?Gn(e.db,n,t,r,o):{findByEntityId:async()=>null,existsByEntityId:async()=>!1,findIdByEntityId: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 Qt(e,n){let{database:t,tenantId:r,kek:o,rootErrorHandlers:i,permissionsOptions:a,manualConfig:s,hubConfig:u}=n,d={},l={};for(let c of e)d[c.id]={},l[c.id]={};for(let c of e){let p=c.schema,f=r??"default",g=Is(t,c.id,f);if(p?.entities){let E={};for(let[he,Ne]of Object.entries(p.entities)){let ke=t?Gn(t.db,g,he,p.version,Ne):Rs(void 0,g,he,p.version,Ne);E[he]=ke}l[c.id].db=E,d[c.id].db=E}let y=c.options,m=c.authConfig,h;if(t&&o&&y?.authType){let E=m?.[y.authType]?.account??[];h=S({authType:y.authType,integrationName:c.id,tenantId:f,kek:o,database:t,extraAccountFields:E}),d[c.id].keys=h}let P={database:t,db:l[c.id]?.db??{},$getAccountId:g,...c.options?{options:c.options}:{},...h?{keys:h,authType:y?.authType}:{},tenantId:f,...u?{hub:u}:{}},w=c.endpoints??{},k=c.hooks,b={...i,...c.errorHandlers},C={},B=c.options?.permissions;Vt({endpoints:w,hooks:k,ctx:P,tree:C,pluginId:c.id,errorHandlers:b,currentPath:[],keyBuilder:c.keyBuilder,permissionsConfig:B,endpointMeta:c.endpointMeta,database:t,permissionsOptions:a,tenantId:r,manualConfig:s?{...s,oauthConfig:c.oauthConfig,kek:o,tenantId:f}:void 0,hubConfig:u,plugin:c,kek:o,allPlugins:e}),Object.keys(C).length>0&&(d[c.id].api=C),P.endpoints=C;let _=c.webhooks??{},D=c.webhookHooks;if(Object.keys(_).length>0){let E={};Yt({webhooks:_,hooks:D,ctx:P,webhooksTree:E,keyBuilder:c.keyBuilder}),d[c.id].webhooks=E,c.pluginWebhookMatcher&&(d[c.id].pluginWebhookMatcher=c.pluginWebhookMatcher),c.pluginTenantWebhookMatcher&&(d[c.id].pluginTenantWebhookMatcher=c.pluginTenantWebhookMatcher)}}return d}function ho(e,n,t){let r={};for(let o of e){let i=o.options,a=o.authConfig;if(i?.authType){let s=a?.[i.authType]?.integration??[],u=I({authType:i.authType,integrationName:o.id,kek:t,database:n,extraIntegrationFields:s});r[o.id]=u}}return r}var Ss="createCorsair({ approval: ... }) is deprecated. Rename to permissions: { timeout, onTimeout, mode }.";function ko(e){let{permissions:n,approval:t}=e;if(n&&t)throw new Error("createCorsair was given both permissions and approval config. Use permissions only \u2014 approval is deprecated.");return t?(console.warn(`[corsair] ${Ss}`),t):n}import*as bo from"querystring";function ve(e){let{oauthConfig:n,clientId:t,redirectUri:r,state:o}=e,i={...n.authParams,client_id:t,redirect_uri:r,response_type:"code",scope:n.scopes.join(" "),state:o};return`${n.authUrl}?${bo.stringify(i)}`}var W=class extends Error{code;constructor(n,t){super(t),this.name="ConnectError",this.code=n}};function _s(e){let n=e.oauthConfig;if(!n)throw new W("plugin_has_no_oauth_config",`Plugin '${e.id}' has no oauthConfig`);return n}async function Xt(e,n){let t=T(e,()=>new W("invalid_corsair_instance","Invalid corsair instance"));if(!t.database)throw new W("no_database","No database configured on corsair instance");let r=t.manual?.redirectUri;if(!r)throw new W("no_redirect_uri","No redirectUri configured. Set manual.redirectUri in createCorsair().");let o=En(n,t.kek);if(!o)throw new W("invalid_state","Invalid or tampered state parameter");let{plugin:i,tenantId:a}=o,s=M(t,i,p=>new W("plugin_not_found",p)),u=_s(s),l=await I({authType:"oauth_2",integrationName:i,kek:t.kek,database:t.database}).get_client_id();if(!l)throw new W("client_id_not_configured",`client_id not configured for '${i}'`);let c=ve({oauthConfig:u,clientId:l,redirectUri:r,state:n});return{plugin:i,tenantId:a,providerName:u.providerName,oauthUrl:c,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 Co(e){let n={error:e.code,message:e.message,...e.extra};return R(e.status,n)}function ye(e){return new A(404,"not_found",e)}function oe(e,n={}){return new A(400,"bad_request",e,n)}function wo(e,n){return M(e,n,t=>ye(t))}async function Po(e,n){let t=e.options?.authType;if(!t||!n.database||!n.kek)return{configured:!1,missingFields:[]};let r=I({authType:t,integrationName:e.id,kek:n.kek,database:n.database}),o=O[t].integration,i=r,a;try{a=await Promise.all(o.map(d=>i[`get_${d}`]()))}catch{a=o.map(()=>null)}let s=o.filter((d,l)=>a[l]==null),u;return t==="oauth_2"?u=!s.includes("client_id")&&!s.includes("client_secret"):u=s.length===0,{configured:u,missingFields:s}}async function To(e,n){let t=e.options?.authType??null,r=e.oauthConfig,{configured:o,missingFields:i}=await Po(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 On(){return{ok:!0}}async function Mn(e){return Promise.all(e.plugins.map(n=>To(n,e)))}async function Hn(e,n){let t=wo(e,n);return To(t,e)}async function Es(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 vo(e,n){let t=await Es(e,n),r=t.filter(o=>o.hasCredentials).map(o=>o.integrationName);return{id:n,accounts:t,connectedPlugins:r}}async function Fn(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 a=!!r.dek;i.accounts.push({integrationName:r.integrationName,hasCredentials:a}),a&&i.connectedPlugins.push(r.integrationName)}}return[...n.values()]}async function Un(e,n){if(!n)throw oe("Tenant id must be a non-empty string");return vo(e,n)}async function Bn(e,n){let t=n?.id?.trim();if(!t)throw oe("Tenant id is required",{missingFields:["id"]});return vo(e,t)}async function Nn(e,n){let t=n?.trim()||"default",r={},o=await qe(e,t);for(let i of o)r[i.plugin]=yn(i);for(let i of e.plugins)i.id in r||(!i.options?.authType||!e.database||!e.kek?r[i.id]="missing_credentials":r[i.id]="not_connected");return r}async function er(e,n){if(!e.database)throw ye(`Permission '${n}' not found`);let t=await e.database.db.selectFrom("corsair_permissions").selectAll().where("id","=",n).executeTakeFirst();if(!t)throw ye(`Permission '${n}' not found`);return Dn(e,t)}function Ds(e){if(!e.oauthConfig)throw oe(`Plugin '${e.id}' has no oauthConfig`)}function Os(e){if(!e.manual)throw new A(500,"connect_not_configured","createCorsair was not given manual config. Set { manual: { baseUrl, redirectUri } } to enable manual connect routes.");return e.manual}function nr(e){let n=Os(e);if(!n.baseUrl?.trim()||!n.redirectUri?.trim())throw new A(500,"connect_not_configured","Manual connect requires manual.baseUrl and manual.redirectUri. Use hub for hosted connect, or set both URLs for manual OAuth.");return n}function Ms(e){let n=!!e.hub,t=He(e.manual);if(!n&&!t)throw new A(500,"connect_not_configured","createCorsair was not given connect config. Set hub: { ... } for Hub mode, or manual: { baseUrl, redirectUri } for manual connect.")}function Ao(e){if(!e.database||!e.kek)throw new A(500,"database_not_configured","A database and kek are required to issue connect links.")}async function Hs(e,n){let t=n?.plugin?.trim();if(!t)throw oe("Plugin id is required",{missingFields:["plugin"]});let r=n.tenantId?.trim()||"default",o=wo(e,t);Ds(o);let i=nr(e);Ao(e);let a=await Po(o,e);if(!a.configured)throw new A(400,"missing_credentials",`Plugin '${t}' is missing OAuth client credentials`,{missingFields:a.missingFields});let s=Fe(fe(t,r),e.kek),u;try{u=new URL(i.baseUrl)}catch{throw new A(500,"connect_misconfigured","manual.baseUrl is not a valid URL. Set a full URL including protocol (e.g. https://app.example.com/connect).")}return u.searchParams.set("state",s),{connectUrl:u.toString(),expiresAt:new Date(Date.now()+Wt).toISOString()}}async function Fs(e,n,t){Ao(n);let o={tenantId:t.tenantId?.trim()||"default",oauthMode:t.oauthMode},i=t.plugin?.trim();i&&(o.plugin=i);let a=t.providerName?.trim();a&&(o.providerName=a);let s=await hn(e,o);return{connectUrl:s.connectUrl,expiresAt:s.expiresAt}}async function $n(e,n,t){return Ms(n),n.hub?Fs(e,n,t):Hs(n,t)}async function Ln(e,n,t){if(n.hub&&!He(n.manual))throw new A(400,"hub_mode","resolve is not used with hub config. Redirect users to connectUrl from createLink.");let r=t?.trim();if(!r)throw oe("state is required",{missingFields:["state"]});nr(n);try{return await Xt(e,r)}catch(o){if(o instanceof W)switch(o.code){case"invalid_state":throw oe("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 Wn(e,n,t){if(n.hub&&!He(n.manual))throw new A(400,"hub_mode","oauthCallback is not used with hub config. Hub delivers tokens to your deliveryUrl.");let r=t?.code?.trim(),o=t?.state?.trim(),i=[];if(r||i.push("code"),o||i.push("state"),i.length)throw oe("Missing required fields",{missingFields:i});let a=nr(n),{processOAuthCallback:s}=await import("./oauth.js");try{return await s(e,{code:r,state:o,redirectUri:a.redirectUri})}catch(u){if(u instanceof Error&&u.name==="OAuthCallbackError")switch(u.code){case"invalid_state":throw oe("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 tr(e,n){if(!e.database)throw ye("Permission not found");let t=await e.database.db.selectFrom("corsair_permissions").selectAll().where("token","=",n).executeTakeFirst();if(!t)throw ye("Permission not found");return Dn(e,t)}async function xo(e,n){return"id"in n?er(e,n.id):tr(e,n.token)}var Io=[{method:"GET",pattern:"/ok",handler:async()=>R(200,On())},{method:"GET",pattern:"/tenants",handler:async({internal:e})=>R(200,await Fn(e))},{method:"POST",pattern:"/tenants",handler:async({internal:e,body:n})=>R(201,await Bn(e,n))},{method:"GET",pattern:"/tenants/:id",handler:async({internal:e,params:n})=>R(200,await Un(e,n.id))},{method:"GET",pattern:"/plugins",handler:async({internal:e})=>R(200,await Mn(e))},{method:"GET",pattern:"/plugins/:id",handler:async({internal:e,params:n})=>R(200,await Hn(e,n.id))},{method:"GET",pattern:"/connection-status",handler:async({internal:e,query:n})=>R(200,await Nn(e,n.tenantId))},{method:"GET",pattern:"/permissions/:id",handler:async({internal:e,params:n})=>R(200,await er(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 tr(e,t)):R(400,{error:"bad_request",message:"token is required",missingFields:["token"]})}},{method:"POST",pattern:"/connect/links",handler:async({corsair:e,internal:n,body:t})=>R(200,await $n(e,n,t))},{method:"GET",pattern:"/connect/resolve",handler:async({corsair:e,internal:n,query:t})=>R(200,await Ln(e,n,t.state??""))},{method:"POST",pattern:"/connect/oauth/callback",handler:async({corsair:e,internal:n,body:t})=>R(200,await Wn(e,n,t))}];(()=>{let e=new Set;for(let n of Io){let t=`${n.method} ${n.pattern}`;if(e.has(t))throw new Error(`Duplicate management route registered: ${t}`);e.add(t)}})();function Us(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 a=t[i],s=r[i];if(a.startsWith(":"))o[a.slice(1)]=decodeURIComponent(s);else if(a!==s)return null}return o}function Bs(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 Ns(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 $s="/api/corsair";function Ae(e,n={}){let t=n.basePath??$s,r=T(e,()=>new Error("managementHandler: invalid corsair instance (missing internal config)"));return async o=>{try{let i=new URL(o.url),a=Bs(i.pathname,t),s=o.method.toUpperCase();if(s==="OPTIONS"||a==="/"||a==="")return await Te(e,o);if(s!=="GET"&&s!=="POST")return R(405,{error:"method_not_allowed",message:`Method ${s} not allowed`});let u=Object.fromEntries(i.searchParams);for(let d of Io){if(d.method!==s)continue;let l=Us(d.pattern,a);if(!l)continue;let c=await Ns(o);return await d.handler({corsair:e,internal:r,req:o,params:l,query:u,body:c})}throw ye(`No route for ${s} ${a}`)}catch(i){if(n.onError){let s=await n.onError(i,o);if(s)return s}if(i instanceof A)return Co(i);let a=i instanceof Error?i.message:"Internal server error";return R(500,{error:"internal_error",message:a})}}}function Ls(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[u,d]of Object.entries(e.headers))if(d!=null)if(Array.isArray(d))for(let l of d)i.append(u,l);else i.set(u,d);let a=e.method!=="GET"&&e.method!=="HEAD",s={method:e.method,headers:i};return a&&e.body!==void 0&&(s.body=typeof e.body=="string"?e.body:JSON.stringify(e.body),i.has("content-type")||i.set("content-type","application/json")),new Request(o,s)}async function Ws(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 Ro(e,n){let t=Ae(e,n);return async(r,o,i)=>{try{let a=await t(Ls(r));await Ws(o,a)}catch(a){i(a)}}}function So(e,n){let t=Ae(e,n);return r=>t(r.req.raw)}function _o(e,n){let t=Ae(e,n);return{GET:t,POST:t,OPTIONS:t}}function Eo(e){let n={[Xe]:e};return{ok:On,tenants:{list:()=>Fn(e),create:t=>Bn(e,t),get:t=>Un(e,t)},plugins:{list:()=>Mn(e),get:t=>Hn(e,t)},connectionStatus:{get:t=>Nn(e,t?.tenantId)},permissions:{get:t=>xo(e,t)},connect:{createLink:t=>$n(n,e,t),resolve:t=>Ln(n,e,t),oauthCallback:t=>Wn(n,e,t)}}}async function Do(e,n,t,r,o="pending"){if(!e)return null;try{let i=mr(),a=new Date;return await e.db.insertInto("corsair_events").values({id:i,created_at:a,updated_at:a,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 js(e,n,t,r="pending"){try{let o=await e.$getAccountId();return Do(e.database,o,n,t,r)}catch(o){return console.warn("Failed to log event:",o),null}}import*as Oo from"https";import*as Mo from"querystring";function jn(e,n,t,r,o){let i=new URL(r.tokenUrl),a=r.tokenAuthMethod==="basic";return new Promise((s,u)=>{let d={code:e.trim(),redirect_uri:o,grant_type:"authorization_code"};a||(d.client_id=n,d.client_secret=t);let l=Mo.stringify(d),c={"Content-Type":"application/x-www-form-urlencoded","Content-Length":Buffer.byteLength(l).toString()};a&&(c.Authorization=`Basic ${Buffer.from(`${n}:${t}`).toString("base64")}`);let p=Oo.request({hostname:i.hostname,...i.port?{port:Number(i.port)}:{},path:i.pathname+i.search,method:"POST",headers:c},f=>{let g="";f.on("data",y=>{g+=y}),f.on("end",()=>{if(f.statusCode!==200){u(new Error(`Token exchange failed (${f.statusCode}): ${g}`));return}try{s(JSON.parse(g))}catch{u(new Error(`Token endpoint returned non-JSON response: ${g}`))}})});p.on("error",f=>u(new Error(`Request failed: ${f.message}`))),p.write(l),p.end()})}var Ho=" ";function K(e){let n=e;return n._def??n.def??{}}function q(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 Uo(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 Bo(e){let n=e.type;return e.element??(typeof n=="string"?void 0:n)}function qn(e,n){let t=n.shape??e.shape;return typeof t=="function"?t():t}function Ue(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 No(e,n){return e.description??n.description}function Ks(e){let n=e;for(;n;){let t=K(n),r=No(n,t);if(r)return r;let o=q(t);if(ar(o)||o==="ZodPipe"||o==="ZodEffects"||o==="ZodTransform"){n=Uo(t,o);continue}break}}function ar(e){return e==="ZodOptional"||e==="ZodNullable"||e==="ZodDefault"||e==="ZodCatch"}function H(e){let n=K(e),t=q(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??Ue(n)[0]??"unknown");case"ZodEnum":return Ue(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=Bo(n);if(!r)return"unknown[]";let o=K(r),i=q(o)==="ZodUnion",a=H(r);return`${i?`(${a})`:a}[]`}case"ZodRecord":return"{}";case"ZodObject":{let r=qn(e,n),o=Object.entries(r);return o.length===0?"{}":`{ ${o.map(([a,s])=>{let u=q(K(s));return`${u==="ZodOptional"||u==="ZodNullable"?a+"?":a}: ${H(s)}`}).join(", ")} }`}case"ZodUnion":return Ue(n).map(r=>H(r)).join(" | ");case"ZodIntersection":return`${H(n.left)} & ${H(n.right)}`;case"ZodPipe":case"ZodTransform":case"ZodEffects":{let r=Uo(n,t);return r?H(r):"unknown"}default:return(t??"unknown").replace("Zod","").toLowerCase()}}function ie(e){let n=K(e),t=q(n),r=No(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??Ue(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=Ue(n).map(i=>String(i));return{kind:"string",optional:!1,description:r,enum:o}}case"ZodOptional":{let o=j(n),i=o?ie(o):{kind:"unknown",optional:!1};return{...i,optional:!0,description:r??i.description}}case"ZodNullable":{let o=j(n),i=o?ie(o):{kind:"unknown",optional:!1};return{...i,optional:!0,description:r??i.description}}case"ZodDefault":case"ZodCatch":{let o=j(n);return o?{...ie(o),description:r}:{kind:"unknown",optional:!1,description:r}}case"ZodArray":{let o=Bo(n);return{kind:"array",optional:!1,description:r,items:o?ie(o):{kind:"unknown",optional:!1}}}case"ZodObject":{let o=qn(e,n),i={};for(let[a,s]of Object.entries(o))i[a]=ie(s);return{kind:"object",optional:!1,description:r,fields:i}}case"ZodRecord":return{kind:"unknown",optional:!1,description:r};case"ZodUnion":{let o=Ue(n);for(let i of o){let a=K(i);if(q(a)==="ZodObject")return{...ie(i),description:r}}return{kind:"unknown",optional:!1,description:r}}case"ZodIntersection":case"ZodPipe":case"ZodTransform":case"ZodEffects":{let o=j(n);return o?{...ie(o),description:r}:{kind:"unknown",optional:!1,description:r}}default:return{kind:"unknown",optional:!1,description:r}}}function Zd(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),a=e.find(l=>l.id===o);if(!a)return null;let s=i;s.startsWith("api.")&&(s=s.slice(4));let u=me(a.endpointMeta,s),d=me(a.endpointSchemas,s);return!u&&!d?null:{input:d?.input?ie(d.input):null,output:d?.output?ie(d.output):null,description:u?.description}}var ur=["equals","contains","startsWith","endsWith","in"],qs=["equals","gt","gte","lt","lte","in"],Zs=["equals"],Gs=["equals","before","after","between"];function $o(e){let n=K(e);switch(q(n)){case"ZodOptional":case"ZodNullable":case"ZodDefault":case"ZodCatch":{let r=j(n);return r?$o(r):null}case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodDate":return"date";default:return null}}function cr(e){let n=K(e),t=q(n);if(ar(t)){let i=j(n);return i?cr(i):{}}if(t!=="ZodObject")return{};let r=qn(e,n),o={};for(let[i,a]of Object.entries(r)){let s=$o(a);s==="string"?o[i]={type:"string",operators:ur}:s==="number"?o[i]={type:"number",operators:qs}:s==="boolean"?o[i]={type:"boolean",operators:Zs}:s==="date"&&(o[i]={type:"date",operators:Gs})}return o}function Lo(e,n){for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return[t,r]}function or(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"&&or(o,i,t)}}function ir(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function sr(e,n,t){for(let[r,o]of Object.entries(e)){let i=[...n,r];ir(o)?t.push(i.join(".")):o!==null&&typeof o=="object"&&sr(o,i,t)}}function lr(e,n){if(n.length===0)return null;let[t,...r]=n,o=Object.entries(e).find(([s])=>s.toLowerCase()===t);if(!o)return null;let[i,a]=o;if(r.length===0)return ir(a)?[i]:null;if(a!==null&&typeof a=="object"&&!ir(a)){let s=lr(a,r);if(s!==null)return[i,...s]}return null}function Wo(e,n){let t=[];t.push(`${e}({`),t.push(" webhookHooks: {");for(let i=0;i<n.length;i++){let a=" ".repeat(i+2);t.push(`${a}${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 a=" ".repeat(i+2);t.push(`${a}},`)}return t.push(" },"),t.push("})"),t.join(`
|
|
26
|
+
`)}var Js=new Set(rn);function xe(e,n){let t=n?.type??"api",r=n?.plugin;if(r!==void 0){let i=e.find(s=>s.id===r);if(!i)return Js.has(r)?`This plugin (${r}) is not configured. Please add it to the Corsair instance to see its associated methods.`:xe(e);if(t==="webhooks"){if(!i.webhooks)return[];let s=[];return sr(i.webhooks,[],s),s.map(u=>`${i.id}.webhooks.${u}`)}if(t==="db"){let s=i.schema?.entities;return s?Object.keys(s).map(u=>`${i.id}.db.${u}.search`):[]}if(!i.endpoints)return[];let a=[];return or(i.endpoints,[],a),a.map(s=>`${i.id}.api.${s}`)}let o={};if(t==="webhooks")for(let i of e){if(!i.webhooks)continue;let a=[];sr(i.webhooks,[],a),o[i.id]=a.map(s=>`${i.id}.webhooks.${s}`)}else if(t==="db")for(let i of e){let a=i.schema?.entities;a&&(o[i.id]=Object.keys(a).map(s=>`${i.id}.db.${s}.search`))}else for(let i of e){if(!i.endpoints)continue;let a=[];or(i.endpoints,[],a),o[i.id]=a.map(s=>`${i.id}.api.${s}`)}return o}function me(e,n){if(e){for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r}}function zs(e,n){let t=e.toLowerCase(),r=n.toLowerCase();if(!t.startsWith(`${r}.`)){let i=t.slice(n.length+1),a=i.startsWith(".")?i.slice(1):i;return a.startsWith("api.")&&(a=a.slice(4)),{shortPath:a,lookupKey:a}}let o=e.slice(n.length+1);return o.toLowerCase().startsWith("api.")&&(o=o.slice(4)),{shortPath:o,lookupKey:o.toLowerCase()}}function rr(e,n){return typeof e=="string"?e:Array.isArray(e)?`${n}:
|
|
27
27
|
${e.join(", ")}`:`${n}:
|
|
28
28
|
`+Object.entries(e).map(([t,r])=>` ${t}: ${r.join(", ")}`).join(`
|
|
29
|
-
`)}function
|
|
29
|
+
`)}function Gd(e,n){let t=n.toLowerCase(),r=t.indexOf(".");if(r!==-1){let o=t.slice(0,r),i=t.slice(r+1),a=e.find(s=>s.id===o);if(a){if(i.startsWith("db.")){let l=i.slice(3),c=l.lastIndexOf(".");if(c!==-1){let p=l.slice(0,c),f=l.slice(c+1),g=a.schema?.entities;if(f==="search"&&g){let y=Lo(g,p);if(y){let[m,h]=y,P=cr(h),w=[`Search ${o} ${m} stored in the local database.`,"Pass limit and offset as numbers for pagination.","","filters {",` entity_id: string [${ur.join(", ")}]`];for(let[k,b]of Object.entries(P))w.push(` ${k}?: ${b.type} [${b.operators.join(", ")}]`);return w.push("}"),w.join(`
|
|
30
30
|
`)}}}return rr(xe(e,{type:"db"}),"Path not found. Available db operations")}if(i.startsWith("webhooks.")){let l=i.slice(9);if(a.webhooks){let c=lr(a.webhooks,l.split("."));if(c!==null){let p=c.join("."),f=me(a.webhookSchemas,p.toLowerCase()),g=f?.response?H(f.response):null,y=[];return f?.description&&y.push(f.description),f?.payload&&y.push(`payload ${Kn(Be(f.payload))}`),g&&y.push(`response: ${g}`),y.push(`usage:
|
|
31
31
|
${Wo(o,c)}`),y.join(`
|
|
32
32
|
|
|
33
33
|
`)}}return rr(xe(e,{type:"webhooks"}),"Path not found. Available webhooks")}let s=i;s.startsWith("api.")&&(s=s.slice(4));let u=me(a.endpointMeta,s),d=me(a.endpointSchemas,s);if(u||d){let l=[],c=[u?.riskLevel?`[${u.riskLevel}]`:"",u?.irreversible?"[irreversible]":""].filter(Boolean).join(" "),p=[u?.description,c].filter(Boolean).join(" ");return p&&l.push(p),d?.input&&l.push(`input ${Kn(Be(d.input))}`),d?.output&&l.push(`output ${Kn(Be(d.output))}`),l.join(`
|
|
34
34
|
|
|
35
|
-
`)}}}return rr(xe(e),"Path not found. Available operations")}function Fo(e){let n=e;for(;;){let t=K(n),r=q(t);if(ar(r)){let o=j(t);if(!o)return n;n=o;continue}return n}}function Be(e){if(e===void 0)return{kind:"inline",type:"unknown"};let n=Fo(e),t=K(n);if(q(t)==="ZodObject"){let o=qn(n,t),i=[];for(let[a,s]of Object.entries(o)){let u=K(s),d=q(u),l=d==="ZodOptional"||d==="ZodNullable",c=Fo(s),p=
|
|
35
|
+
`)}}}return rr(xe(e),"Path not found. Available operations")}function Fo(e){let n=e;for(;;){let t=K(n),r=q(t);if(ar(r)){let o=j(t);if(!o)return n;n=o;continue}return n}}function Be(e){if(e===void 0)return{kind:"inline",type:"unknown"};let n=Fo(e),t=K(n);if(q(t)==="ZodObject"){let o=qn(n,t),i=[];for(let[a,s]of Object.entries(o)){let u=K(s),d=q(u),l=d==="ZodOptional"||d==="ZodNullable",c=Fo(s),p=Ks(s);i.push({key:a,optional:l,type:H(c),...p!==void 0?{description:p}:{}})}return{kind:"object",fields:i}}return{kind:"inline",type:H(n)}}function Kn(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=Ho.repeat(n+1),r=Ho.repeat(n);return`{
|
|
36
36
|
${e.fields.map(i=>{let a=i.optional?`${i.key}?`:i.key,s=i.description?` // ${i.description}`:"";return`${t}${a}: ${i.type}${s}`}).join(`
|
|
37
37
|
`)}
|
|
38
|
-
${r}}`}return"unknown"}function
|
|
38
|
+
${r}}`}return"unknown"}function Vs(e,n){let t=xe(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:c,lookupKey:p}=zs(l,n),f=me(r.endpointMeta,p),g=me(r.endpointSchemas,p);!f&&!g||o.push({path:l,shortPath:c,description:f?.description,riskLevel:f?.riskLevel,irreversible:f?.irreversible,input:Be(g?.input),output:Be(g?.output)})}o.sort((l,c)=>l.path.localeCompare(c.path));let i=[],a=xe(e,{plugin:n,type:"webhooks"});if(Array.isArray(a)&&r.webhooks)for(let l of a){let p=l.toLowerCase().slice(n.length+1),f=p.startsWith(".")?p.slice(1):p;if(!f.startsWith("webhooks."))continue;let g=f.slice(9),y=lr(r.webhooks,g.split("."));if(y===null)continue;let m=y.join("."),h=me(r.webhookSchemas,m.toLowerCase()),P=h?.response?H(h.response):void 0;i.push({path:l,description:h?.description,payload:Be(h?.payload),responseType:P,usageExample:Wo(n,y)})}i.sort((l,c)=>l.path.localeCompare(c.path));let s=[],u=xe(e,{plugin:n,type:"db"}),d=r.schema?.entities;if(Array.isArray(u)&&d)for(let l of u){let p=l.toLowerCase().slice(n.length+1),f=p.startsWith(".")?p.slice(1):p;if(!f.startsWith("db."))continue;let g=f.slice(3),y=g.lastIndexOf(".");if(y===-1)continue;let m=g.slice(0,y);if(g.slice(y+1)!=="search")continue;let P=Lo(d,m);if(!P)continue;let[w,k]=P,b=cr(k),C=Object.entries(b).map(([B,_])=>({field:B,type:_.type,operators:_.operators}));s.push({path:l,entityName:w,filters:[{field:"entity_id",type:"string",operators:ur},...C]})}return s.sort((l,c)=>l.path.localeCompare(c.path)),{ok:!0,data:{pluginId:n,api:o,webhooks:i,db:s}}}function jo(e,n){for(let[t,r]of Object.entries(e))if(r?.pluginWebhookMatcher&&r.pluginWebhookMatcher(n))return t;return null}function Ys(e,n){let t=jo(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 Qs(e){let n={};for(let t of e)!t.pluginWebhookMatcher&&!t.pluginTenantWebhookMatcher||(n[t.id]={pluginWebhookMatcher:t.pluginWebhookMatcher,pluginTenantWebhookMatcher:t.pluginTenantWebhookMatcher});return n}function Ko(e,n){let t=n.toLowerCase(),r=e[t]??e[n];return Array.isArray(r)?r[0]:typeof r=="string"?r:void 0}function qo(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 en(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Xs(e){return en(e.body)}function Zo(e,n){let t=e.query;if(!t)return;let r=t[n]??t[n.toLowerCase()];return Zn(Array.isArray(r)?r:[r])}function Go(e){let n=e.headers??{},t=[n.validationtoken,n.validationToken,n["validation-token"],n["ms-validation-token"]];for(let u of t){let d=Zn(Array.isArray(u)?u:[u]);if(d)return decodeURIComponent(d)}let r=Zo({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 u of o){let d=n[u],l=Array.isArray(d)?d[0]:d;if(!(!l||typeof l!="string"))try{let p=(l.startsWith("http")?new URL(l):new URL(`https://example.invalid${l.startsWith("/")?l:`/${l}`}`)).searchParams.get("validationToken");if(p?.trim())return p.trim()}catch{continue}}let i=e.payload!==void 0?e.payload:e.body!==void 0?e.body:void 0,a=en(typeof i=="string"?(()=>{try{return JSON.parse(i)}catch{return i}})():i);return Zn([a?.validationToken])??null}function ea(e){if(Go(e))return!0;let n=en(e.body??e.payload);return Ko(e.headers??{},"content-type")?.includes("text/plain")?!n||Object.keys(n).length===0:!1}function Zn(e){for(let n of e){let t=qo(n);if(t)return t}}function na(e){let t=en(e.message)?.data;if(typeof t!="string")return null;try{return JSON.parse(Buffer.from(t,"base64").toString("utf8"))}catch{return null}}var Xe=Symbol.for("corsair:internal");function Ur(e){let n=e.database?pr(e.database):void 0,t=n&&e.kek?ho(e.plugins,n,e.kek):_n(!!n,!!e.kek),r=ko(e),o={plugins:e.plugins,database:n,kek:e.kek,multiTenancy:!!e.multiTenancy,permissions:r,manual:e.manual,hub:e.hub?on(e.hub):void 0},i=yo(n),a=Eo(o);if(e.multiTenancy)return Object.assign({withTenant:u=>{if(!u)throw new Error("corsair.withTenant(tenantId): tenantId must be a non-empty string");let d=Qt(e.plugins,{database:n,tenantId:u,kek:e.kek,rootErrorHandlers:e.errorHandlers,permissionsOptions:r,manualConfig:e.manual,hubConfig:o.hub});return Object.assign(d,{[Xe]:o})},keys:t,permissions:i,manage:a},{[Xe]:o});let s=Qt(e.plugins,{database:n,tenantId:void 0,kek:e.kek,rootErrorHandlers:e.errorHandlers,permissionsOptions:r,manualConfig:e.manual,hubConfig:o.hub});return Object.assign({},s,{keys:t,permissions:i,manage:a,[Xe]:o})}var U=class extends Error{code;constructor(n,t){super(t),this.name="OAuthCallbackError",this.code=n}};function Jo(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 ta(e,n,t,r){let o=kr(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 s=X(),u=await ee(s,r);await o.accounts.create({tenant_id:t,integration_id:i.id,config:{},dek:u})}async function et(e,n,t){let{tenantId:r,redirectUri:o,hubConnect:i=!1}=t,a=T(e,()=>new U("invalid_corsair_instance","Invalid corsair instance"));if(!a.database)throw new Error("No database configured on corsair instance");let s=M(a,n,p=>new U("plugin_not_found",p)),u=Jo(s),l=await I({authType:"oauth_2",integrationName:n,kek:a.kek,database:a.database}).get_client_id();if(!l)throw new Error(`client_id not configured for '${n}'`);if(i){let p=new URL(ve({oauthConfig:u,clientId:l,redirectUri:o,state:""}));return p.searchParams.delete("state"),{url:p.toString(),state:""}}let c=Fe(fe(n,r),a.kek);return{url:ve({oauthConfig:u,clientId:l,redirectUri:o,state:c}),state:c}}async function Ve(e,n){let{code:t,state:r,redirectUri:o}=n,i=T(e,()=>new U("invalid_corsair_instance","Invalid corsair instance")),a=En(r,i.kek);if(!a)throw new U("invalid_state","Invalid or tampered state parameter");let{plugin:s,tenantId:u}=a;if(!i.database)throw new U("no_database","No database configured on corsair instance");let d=M(i,s,m=>new U("plugin_not_found",m)),l=Jo(d),c=I({authType:"oauth_2",integrationName:s,kek:i.kek,database:i.database}),p=await c.get_client_id(),f=await c.get_client_secret();if(!p||!f)throw new U("credentials_not_configured",`Credentials not configured for '${s}'`);await ta(i.database,s,u,i.kek);let g=await jn(t,p,f,l,o);if(!g.access_token)throw new U("no_access_token",`No access_token returned from ${l.providerName}`);let y=S({authType:"oauth_2",integrationName:s,tenantId:u,kek:i.kek,database:i.database});await y.set_access_token(g.access_token),g.refresh_token&&await y.set_refresh_token(g.refresh_token),g.expires_in&&await y.set_expires_at(String(Math.floor(Date.now()/1e3)+g.expires_in));try{let m=await wn(i.plugins,s,g);if(m)try{let h=d.authConfig?.oauth_2?.account??[];await De({database:i.database,kek:i.kek,pluginId:s,tenantId:u,link:m,authType:"oauth_2",extraAccountFields:h})}catch(h){console.warn(`[corsair:oauth] Failed to persist webhook tenant link for '${s}' tenant '${u}':`,h)}}catch(m){console.warn(`[corsair:oauth] Failed to resolve webhook tenant link for '${s}' tenant '${u}':`,m)}return{plugin:s,tenantId:u}}export{br as a,ae as b,Le as c,ue as d,on as e,J as f,sn as g,Ie as h,an as i,un as j,cn as k,ln as l,wr as m,dn as n,Re as o,X as p,ee as q,L as r,zn as s,je as t,le as u,ne as v,Ke as w,I as x,S as y,Dr as z,Or as A,fe as B,Lt as C,De as D,at as E,Pn as F,zr as G,ve as H,U as I,et as J,Ve as K,Xn as L,Hi as M,hn as N,jr as O,Kr as P,ot as Q,it as R,qr as S,Zr as T,de as U,Ce as V,pe as W,Oe as X,Tn as Y,ct as Z,Me as _,lt as $,dt as aa,pt as ba,gt as ca,Xr as da,te as ea,An as fa,xn as ga,ge as ha,Pe as ia,Je as ja,ze as ka,In as la,ht as ma,kt as na,Ct as oa,wt as pa,Pt as qa,Tt as ra,vt as sa,Te as ta,re as ua,At as va,io as wa,Rn as xa,Sn as ya,ao as za,xt as Aa,It as Ba,Rt as Ca,St as Da,_t as Ea,Et as Fa,Dt as Ga,Ot as Ha,Mt as Ia,Ht as Ja,Ft as Ka,Ut as La,Bt as Ma,Nt as Na,$t as Oa,Xt as Pa,Ae as Qa,Ro as Ra,So as Sa,_o as Ta,Do as Ua,js as Va,jn as Wa,Zd as Xa,xe as Ya,Gd as Za,Kn as _a,Vs as $a,jo as ab,Ys as bb,Qs as cb,Ko as db,qo as eb,en as fb,Xs as gb,Zo as hb,Go as ib,ea as jb,Zn as kb,na as lb,Xe as mb,Ur as nb};
|
package/dist/core.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$a as v,A as o,Pa as q,Ua as r,Va as s,Wa as t,_a as u,a,ab as w,b,bb as x,cb as y,db as z,eb as A,fb as B,gb as C,hb as D,ib as E,jb as F,kb as G,lb as H,mb as I,nb as J,p as d,q as e,r as f,s as g,t as h,u as i,ua as p,v as j,w as k,x as l,y as m,z as n}from"./chunk-
|
|
1
|
+
import{$a as v,A as o,Pa as q,Ua as r,Va as s,Wa as t,_a as u,a,ab as w,b,bb as x,cb as y,db as z,eb as A,fb as B,gb as C,hb as D,ib as E,jb as F,kb as G,lb as H,mb as I,nb as J,p as d,q as e,r as f,s as g,t as h,u as i,ua as p,v as j,w as k,x as l,y as m,z as n}from"./chunk-OVJRYUB3.js";import{g as c}from"./chunk-67EXGXPK.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,3 +1,4 @@
|
|
|
1
|
+
import { A as AuthTypes } from './constants-DnSLjl7e.js';
|
|
1
2
|
export { f as formatProviderDisplayName } from './constants-DnSLjl7e.js';
|
|
2
3
|
import { g as HubOAuthMode, h as HubConnectSessionResult, i as HubPermissionSessionResult, H as HubConfig, f as HubConfigInput, j as HubConnectSessionInput, k as HubListProjectConnectionsInput, A as AccountKeyManagerFor, l as HubPermissionSessionInput } from './types-BZ-KI4kd.js';
|
|
3
4
|
export { D as DEFAULT_HUB_API_URL, m as HubEnvironmentSlug } from './types-BZ-KI4kd.js';
|
|
@@ -20,6 +21,7 @@ type HubProjectConnection = {
|
|
|
20
21
|
tenantId: string;
|
|
21
22
|
plugin: string;
|
|
22
23
|
authKind: ConnectAuthKind;
|
|
24
|
+
authType?: AuthTypes;
|
|
23
25
|
status: ConnectAuthStatusLevel;
|
|
24
26
|
connected: boolean;
|
|
25
27
|
verified: boolean;
|
package/dist/hub.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as C,Aa as V,Ba as W,Ca as X,Da as Y,Ea as Z,Fa as _,Ga as $,Ha as aa,Ia as ba,Ja as ca,Ka as da,La as ea,Ma as fa,N as o,Na as ga,O as p,Oa as ha,P as q,Q as r,R as s,S as t,T as u,U as v,V as w,W as x,X as y,Y as z,Z as A,_ as B,aa as D,b as a,ba as E,c as b,ca as F,d as c,e as d,ea as G,f as e,fa as H,g as f,ga as I,h as g,ha as J,i as h,j as i,k as j,l as k,m as l,n as m,o as n,oa as K,pa as L,qa as M,ra as N,sa as O,ta as P,va as Q,wa as R,xa as S,ya as T,za as U}from"./chunk-
|
|
1
|
+
import{$ as C,Aa as V,Ba as W,Ca as X,Da as Y,Ea as Z,Fa as _,Ga as $,Ha as aa,Ia as ba,Ja as ca,Ka as da,La as ea,Ma as fa,N as o,Na as ga,O as p,Oa as ha,P as q,Q as r,R as s,S as t,T as u,U as v,V as w,W as x,X as y,Y as z,Z as A,_ as B,aa as D,b as a,ba as E,c as b,ca as F,d as c,e as d,ea as G,f as e,fa as H,g as f,ga as I,h as g,ha as J,i as h,j as i,k as j,l as k,m as l,n as m,o as n,oa as K,pa as L,qa as M,ra as N,sa as O,ta as P,va as Q,wa as R,xa as S,ya as T,za as U}from"./chunk-OVJRYUB3.js";import"./chunk-67EXGXPK.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";export{v as BROWSER_DELIVERY_TTL_MS,b as DEFAULT_HUB_API_URL,c as HubNotConfiguredError,x as ManagedOAuthDeliveryError,w as SIGNED_TUNNEL_REPLAY_WINDOW_MS,R as attachManagedRefreshAuth,H as buildBrowserDeliveryRedirectUrl,V as createConnectSessionJti,_ as createConnectTokenJti,o as createHubConnectSession,S as createHubPermissionSession,U as createHubRouteHandlers,ea as createPermissionSessionJti,G as createSignedTokenJti,Z as decodeConnectSessionTokenFromPath,da as decodeConnectTokenFromPath,ha as decodePermissionTokenFromPath,F as deliverSignedEnvelope,ca as encodeConnectTokenForPath,T as formatHubApprovalMessage,a as formatProviderDisplayName,E as formatServerDeliveryError,W as getConnectSessionExpiryMs,p as getConnectStatusForTenant,$ as getConnectTokenExpiryMs,e as getHubConfig,Q as getManagedAccessToken,K as handleHubDeliveryGet,L as handleHubDeliveryPost,N as handleHubDeliveryRequest,M as hubDeliveryToResponse,g as inferHubEnvironmentSlug,r as isLoopbackUrl,D as isServerDeliveryAckSuccessful,q as listHubProjectConnections,d as normalizeHubConfig,h as parseConnectSessionResponse,l as parseConnectStatusResponse,m as parseHubApiErrorBody,k as parseOAuthRefreshResponse,j as parsePermissionSessionResponse,i as parseProjectConnectionsResponse,C as parseServerDeliveryAckBody,y as processManagedOAuthDelivery,s as resolveDeliveryTransport,n as resolveHubDeliveryUrl,f as resolveHubOAuthCallbackUrl,O as respondToHubDelivery,P as respondToHubDeliveryFromRequest,I as signBrowserDeliveryToken,X as signConnectSessionToken,aa as signConnectToken,z as signDeliveryEnvelope,fa as signPermissionToken,t as usesBrowserDelivery,u as validateProductionDeliveryUrl,J as verifyBrowserDeliveryToken,Y as verifyConnectSessionToken,ba as verifyConnectToken,A as verifyDeliveryEnvelope,ga as verifyPermissionToken,B as verifySignedTunnelDelivery};
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as N,b as j}from"./chunk-XLNT2UI2.js";import{D as y,E as h,F as k,G as x,L as P,Pa as I,Qa as O,Ra as R,Sa as T,Ta as A,Xa as l,Ya as c,Za as d,_a as m,ab as L,bb as W,cb as F,da as b,db as v,eb as E,fb as _,gb as $,kb as M,lb as D,mb as g,na as S,nb as H,ua as w}from"./chunk-
|
|
1
|
+
import{a as N,b as j}from"./chunk-XLNT2UI2.js";import{D as y,E as h,F as k,G as x,L as P,Pa as I,Qa as O,Ra as R,Sa as T,Ta as A,Xa as l,Ya as c,Za as d,_a as m,ab as L,bb as W,cb as F,da as b,db as v,eb as E,fb as _,gb as $,kb as M,lb as D,mb as g,na as S,nb as H,ua as w}from"./chunk-OVJRYUB3.js";import"./chunk-67EXGXPK.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";function s(n){let t=n[g];if(!t)throw new Error("listOperations / getSchema: invalid corsair instance. Pass the value returned by createCorsair() or corsair.withTenant().");return t.plugins}function B(n,t){let r=c(s(n),t);return typeof r=="string"?r:Array.isArray(r)?r.join(`
|
|
2
2
|
`):Object.values(r).flat().join(`
|
|
3
3
|
`)}function J(n,t){return d(s(n),t)}function q(n,t){return l(s(n),t)}var Y=Symbol.for("corsair:internal");function z(n,t){let r=n;for(let e of t){if(!r||typeof r!="object")return null;r=r[e]}return typeof r=="function"?r:null}function C(n){return n[Y]?.database}async function G(n,t){let r=new Date().toISOString(),e=await n.permissions.find_by_token(t);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<r){let o=C(n);return o&&await o.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 f=e.tenant_id??"default",a=(n.withTenant?n.withTenant(f):n)[e.plugin];if(!a?.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 p=z(a.api,e.endpoint.split("."));if(!p)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 o=typeof e.args=="string"?JSON.parse(e.args):e.args,i=await p(o);return await n.permissions.set_completed(e.id),{plugin:e.plugin,endpoint:e.endpoint,result:i}}catch(o){let i=o instanceof Error?o.message:String(o),u=C(n);return u&&await u.db.updateTable("corsair_permissions").set({status:"failed",error:i,updated_at:new Date}).where("id","=",e.id).execute(),{plugin:e.plugin,endpoint:e.endpoint,result:null,error:i}}}export{w as AuthMissingError,N as CorsairClientError,_ as asRecord,F as collectPluginWebhookMatchers,H as createCorsair,j as createCorsairClient,D as decodePubSubData,G as executePermission,M as firstString,m as formatDocSchemaShape,v as getHeader,J as getSchema,q as getStructuredSchema,B as listOperations,O as managementHandler,L as matchWebhookPlugin,W as matchWebhookPluginAndTenant,S as processCorsair,b as processWebhook,$ as readBodyRecord,h as resolveAccountFromWebhookLink,I as resolveConnectLink,x as resolveTenantFromWebhookLink,k as resolveTenantIdFromWebhookLink,y as setWebhookTenantLink,P as setupCorsair,R as toExpressHandler,E as toExternalId,T as toHonoHandler,A as toNextJsHandler};
|
package/dist/oauth.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as a,C as b,H as c,I as d,J as e,K as f}from"./chunk-
|
|
1
|
+
import{B as a,C as b,H as c,I as d,J as e,K as f}from"./chunk-OVJRYUB3.js";import"./chunk-67EXGXPK.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";export{d as OAuthCallbackError,c as buildOAuthAuthorizeUrl,b as decodeOAuthState,a as encodeOAuthState,e as generateOAuthUrl,f as processOAuthCallback};
|
package/dist/setup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{L as a,M as b}from"./chunk-
|
|
1
|
+
import{L as a,M as b}from"./chunk-OVJRYUB3.js";import"./chunk-67EXGXPK.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";export{b as applySetupCredentials,a as setupCorsair};
|
package/dist/tunnel.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{D as a,E as b,F as c,G as d,ha as e,ia as f,ja as g,ka as h,la as i,ma as j,na as k}from"./chunk-
|
|
1
|
+
import{D as a,E as b,F as c,G as d,ha as e,ia as f,ja as g,ka as h,la as i,ma as j,na as k}from"./chunk-OVJRYUB3.js";import"./chunk-67EXGXPK.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";export{j as applyPermissionDecision,f as isAuthCredentialsBrowserDelivery,i as isByoOAuthBrowserDelivery,h as isManagedBrowserDelivery,g as isPermissionBrowserDelivery,k as processCorsair,b as resolveAccountFromWebhookLink,d as resolveTenantFromWebhookLink,c as resolveTenantIdFromWebhookLink,a as setWebhookTenantLink,e as verifyBrowserDeliveryToken};
|