@zhama/tego-plugin-sdk 0.0.0-stage → 1.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +172 -0
- package/README.md +846 -2
- package/access-catalog.schema.json +304 -0
- package/access-fixtures/resolve.json +1359 -0
- package/bin/tego-plugin-pack.mjs +2 -0
- package/bin/tego-plugin.mjs +3 -0
- package/dist/access-drizzle.cjs +1 -0
- package/dist/access-drizzle.d.cts +726 -0
- package/dist/access-drizzle.d.ts +726 -0
- package/dist/access-drizzle.js +1 -0
- package/dist/access-hono.cjs +3 -0
- package/dist/access-hono.d.cts +108 -0
- package/dist/access-hono.d.ts +108 -0
- package/dist/access-hono.js +3 -0
- package/dist/access-implications.cjs +1 -0
- package/dist/access-implications.d.cts +25 -0
- package/dist/access-implications.d.ts +25 -0
- package/dist/access-implications.js +1 -0
- package/dist/access.cjs +26 -0
- package/dist/access.d.cts +884 -0
- package/dist/access.d.ts +884 -0
- package/dist/access.js +26 -0
- package/dist/catalog-CSSbrfEf.d.cts +361 -0
- package/dist/catalog-CSSbrfEf.d.ts +361 -0
- package/dist/chunk-3KUOBGJN.js +19 -0
- package/dist/chunk-3WA3M347.cjs +1 -0
- package/dist/chunk-5CU33JVY.js +1 -0
- package/dist/chunk-7K37PVGV.js +5 -0
- package/dist/chunk-7XHF3YSK.js +1 -0
- package/dist/chunk-AJY7ZHXK.cjs +3 -0
- package/dist/chunk-BN6TGHSB.cjs +1 -0
- package/dist/chunk-BTHXQWHT.js +1 -0
- package/dist/chunk-C2OCOPZQ.cjs +1 -0
- package/dist/chunk-IMAVYQ4U.cjs +4 -0
- package/dist/chunk-OP64Y4IN.cjs +1 -0
- package/dist/chunk-QKSPPMVN.js +1 -0
- package/dist/chunk-ROFUQLOZ.cjs +1 -0
- package/dist/chunk-SNUCO2MK.js +1 -0
- package/dist/chunk-THMWRUAT.cjs +19 -0
- package/dist/chunk-VMCGDDGP.js +3 -0
- package/dist/chunk-W7C357A6.cjs +5 -0
- package/dist/chunk-WLTASJF6.js +4 -0
- package/dist/egress.cjs +7 -0
- package/dist/egress.d.cts +9 -0
- package/dist/egress.d.ts +9 -0
- package/dist/egress.js +7 -0
- package/dist/frontend.cjs +2 -0
- package/dist/frontend.d.cts +353 -0
- package/dist/frontend.d.ts +353 -0
- package/dist/frontend.js +2 -0
- package/dist/gateway-signature.cjs +1 -0
- package/dist/gateway-signature.d.cts +112 -0
- package/dist/gateway-signature.d.ts +112 -0
- package/dist/gateway-signature.js +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +528 -0
- package/dist/index.d.ts +528 -0
- package/dist/index.js +1 -0
- package/dist/manifest-types-DQARCQJt.d.cts +627 -0
- package/dist/manifest-types-DQARCQJt.d.ts +627 -0
- package/dist/manifest.cjs +1 -0
- package/dist/manifest.d.cts +2824 -0
- package/dist/manifest.d.ts +2824 -0
- package/dist/manifest.js +1 -0
- package/dist/mcp-identity.cjs +2 -0
- package/dist/mcp-identity.d.cts +106 -0
- package/dist/mcp-identity.d.ts +106 -0
- package/dist/mcp-identity.js +2 -0
- package/dist/pack.cjs +1 -0
- package/dist/pack.d.cts +169 -0
- package/dist/pack.d.ts +169 -0
- package/dist/pack.js +1 -0
- package/dist/publish.cjs +1 -0
- package/dist/publish.d.cts +96 -0
- package/dist/publish.d.ts +96 -0
- package/dist/publish.js +1 -0
- package/dist/scaffold.cjs +523 -0
- package/dist/scaffold.d.cts +182 -0
- package/dist/scaffold.d.ts +182 -0
- package/dist/scaffold.js +523 -0
- package/dist/server-runtime.cjs +1 -0
- package/dist/server-runtime.d.cts +63 -0
- package/dist/server-runtime.d.ts +63 -0
- package/dist/server-runtime.js +1 -0
- package/dist/server.cjs +1 -0
- package/dist/server.d.cts +1808 -0
- package/dist/server.d.ts +1808 -0
- package/dist/server.js +1 -0
- package/dist/testing.cjs +2 -0
- package/dist/testing.d.cts +92 -0
- package/dist/testing.d.ts +92 -0
- package/dist/testing.js +2 -0
- package/dist/vite.cjs +1 -0
- package/dist/vite.d.cts +133 -0
- package/dist/vite.d.ts +133 -0
- package/dist/vite.js +1 -0
- package/package.json +160 -4
- package/sql/access.sql +73 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { PluginUserContext } from './frontend.js';
|
|
2
|
+
import { PluginScopedDb, PluginPublicContext, PluginBackendModule } from './server.js';
|
|
3
|
+
import 'zod';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Runs a backend part: the bridge between the container it lives in and the
|
|
7
|
+
* `fetch(request, ctx, host)` module the plugin actually wrote.
|
|
8
|
+
*
|
|
9
|
+
* The runner image starts `backend/index.js` as an ordinary Node process, so
|
|
10
|
+
* something has to open a socket, work out who is calling, and assemble the
|
|
11
|
+
* host capabilities. That is this file, and it ships in the SDK rather than in
|
|
12
|
+
* the image on purpose: it is versioned with the plugin's own `hostApiRange`,
|
|
13
|
+
* so a plugin built against one host API keeps the bridge that matches it and
|
|
14
|
+
* the image stays a dumb Node runtime.
|
|
15
|
+
*
|
|
16
|
+
* Imported only by a plugin's backend entry, never by the platform — the
|
|
17
|
+
* `node:` imports here would not resolve in a browser build.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The caller, or null when the headers are absent, malformed or unsigned.
|
|
22
|
+
*
|
|
23
|
+
* Absent means the request did not come through the gateway, which is the only
|
|
24
|
+
* way in — so it is refused rather than defaulted to an anonymous context that
|
|
25
|
+
* a plugin might mistake for a real user.
|
|
26
|
+
*
|
|
27
|
+
* The signature is what makes the rest of it worth reading. Everything here
|
|
28
|
+
* arrives as a plain header, so without checking it the backend's idea of who
|
|
29
|
+
* is calling is whatever the socket said, and the gateway's permission checks
|
|
30
|
+
* protect only the path through the gateway.
|
|
31
|
+
*/
|
|
32
|
+
declare function readUserContext(headers: Record<string, string | string[] | undefined>, verification: {
|
|
33
|
+
key: string;
|
|
34
|
+
nowMs: number;
|
|
35
|
+
}): PluginUserContext | null;
|
|
36
|
+
/** The public context, or null when any field is absent or the signature fails. */
|
|
37
|
+
declare function readPublicContext(headers: Record<string, string | string[] | undefined>, verification: {
|
|
38
|
+
key: string;
|
|
39
|
+
nowMs: number;
|
|
40
|
+
}): PluginPublicContext | null;
|
|
41
|
+
/** Exported for its tests; `serveBackend` is the only caller in production. */
|
|
42
|
+
declare function createScopedDb(databaseUrl: string): PluginScopedDb;
|
|
43
|
+
/**
|
|
44
|
+
* Serves a backend module until the container stops.
|
|
45
|
+
*
|
|
46
|
+
* A plugin's `backend/index.js` is expected to be one call to this:
|
|
47
|
+
*
|
|
48
|
+
* ```js
|
|
49
|
+
* import { serveBackend } from '@tego/plugin-sdk/server-runtime';
|
|
50
|
+
* import backend from './app.js';
|
|
51
|
+
* serveBackend(backend);
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
declare function serveBackend(module: PluginBackendModule): void;
|
|
55
|
+
/**
|
|
56
|
+
* The message to fail with, or null when the database answered.
|
|
57
|
+
*
|
|
58
|
+
* Returns the message instead of exiting so the decision to end the process
|
|
59
|
+
* stays at the one call site that owns the process.
|
|
60
|
+
*/
|
|
61
|
+
declare function checkDatabaseReachable(db: Pick<PluginScopedDb, 'query'>, databaseUrl: string): Promise<string | null>;
|
|
62
|
+
|
|
63
|
+
export { checkDatabaseReachable, createScopedDb, readPublicContext, readUserContext, serveBackend };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var H=Object.defineProperty;var n=(a,e)=>H(a,"name",{value:e,configurable:!0});import{verifyPluginContext as L,verifyPluginPublicContext as C,PLUGIN_STORAGE_POLICY_PATH as R,verifyPluginStoragePolicy as M}from"./chunk-WLTASJF6.js";import{PLUGIN_CONTEXT_HEADERS as m}from"./chunk-QKSPPMVN.js";import{createServer as D}from"http";function $(a){const e=new ArrayBuffer(a.byteLength);return new Uint8Array(e).set(a),e}n($,"toArrayBuffer");function z(a){const e=n(s=>{const c=a[s];if(!c)throw new Error(`${s} is required but was not set`);return c},"require_");return{pluginId:e("TEGO_PLUGIN_ID"),tenantId:e("TEGO_TENANT_ID"),port:Number(e("TEGO_PLUGIN_PORT")),healthPath:a.TEGO_PLUGIN_HEALTH_PATH??"/healthz",hostApiUrl:e("TEGO_PLUGIN_HOST_API_URL"),hostApiToken:e("TEGO_PLUGIN_HOST_API_TOKEN"),databaseUrl:e("DATABASE_URL"),gatewayKey:e("TEGO_PLUGIN_GATEWAY_KEY")}}n(z,"readEnv");function O(a,e){const s=n(h=>{const v=a[h],I=Array.isArray(v)?v[0]:v;return I&&I.length>0?I:null},"read"),c=s(m.userId),d=s(m.tenantId);if(!c||!d)return null;const p=s(m.signature),w=s(m.issuedAt);if(!p||!w)return null;const f=s(m.avatarId),A=s(m.roles),i=s(m.delegation),u={userId:c,tenantId:d,rolesHeader:A??"",avatarId:f??"",issuedAt:w,...i?{delegationHeader:i}:{}};if(!L({context:u,signature:p,key:e.key,nowMs:e.nowMs}))return null;let T=[];if(A)try{const h=JSON.parse(A);if(!Array.isArray(h))return null;T=h.filter(v=>typeof v=="string")}catch{return null}let b;if(i){if(!f)return null;try{const h=JSON.parse(i);if(!h||typeof h.id!="string"||!h.id||!Array.isArray(h.actions)||h.actions.some(v=>v!=="records.read"&&v!=="work.prepare"))return null;b={id:h.id,actions:h.actions}}catch{return null}}return{userId:c,tenantId:d,roles:T,...f?{avatarId:f}:{},...b?{delegation:b}:{}}}n(O,"readUserContext");function U(a,e){const s=n(T=>{const b=a[T],h=Array.isArray(b)?b[0]:b;return h&&h.length>0?h:null},"read"),c=s(m.tenantId),d=s(m.installId),p=s(m.publicRoute),w=s(m.clientIp),f=s(m.avatarId),A=s(m.issuedAt),i=s(m.signature);if(!c||!d||!p||!w||!A||!i)return null;const u={tenantId:c,installId:d,route:p,clientIp:w,...f?{avatarId:f}:{}};return C({context:{...u,issuedAt:A},signature:i,key:e.key,nowMs:e.nowMs})?u:null}n(U,"readPublicContext");function W(a){const e=n(async(t,o)=>{const r=await fetch(`${a.hostApiUrl}${t}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${a.hostApiToken}`},body:JSON.stringify(o),...t.startsWith("/knowledge/collections/")||t.startsWith("/knowledge/admin/")?{signal:AbortSignal.timeout(12e4)}:t==="/mail/send"?{signal:AbortSignal.timeout(6e4)}:t.startsWith("/directory/")||t.startsWith("/knowledge/")||t.startsWith("/delegations/")||t.startsWith("/proactive/")||t==="/mail/status"||t==="/mail/unsubscribes"||t==="/events"?{signal:AbortSignal.timeout(1e4)}:{}});if(!r.ok){const l=await r.text();let g;try{if(g=JSON.parse(l)?.error?.details,typeof g=="string")try{g=JSON.parse(g)}catch{}}catch{}throw Object.assign(new Error(`Tego host API ${t} failed: ${r.status} ${l}`),{status:r.status,details:g,retryAfter:r.headers.get("retry-after")})}return r},"call"),s={debug:n((t,o)=>void c("debug",t,o),"debug"),info:n((t,o)=>void c("info",t,o),"info"),warn:n((t,o)=>void c("warn",t,o),"warn"),error:n((t,o)=>void c("error",t,o),"error")};async function c(t,o,r){try{await e("/log",{level:t,message:o,fields:r})}catch{}}n(c,"emitLog");const d=n((t,o)=>`${a.hostApiUrl}/storage/${t}?key=${encodeURIComponent(o)}`,"storageUrl"),p={copy:n(async(t,o)=>{const l=await(await e("/storage/copy",{sourceKey:t,destinationKey:o})).json();if(!l.data)throw new Error("Tego host API returned no copied object");return l.data},"copy"),getStream:n(async t=>{const o=await fetch(d("stream",t),{headers:{authorization:`Bearer ${a.hostApiToken}`}});if(o.status===404)return null;if(!o.ok)throw new Error(`Tego storage stream failed: ${o.status}`);return o.body},"getStream"),putStream:n(async(t,o,r)=>{const l={method:"POST",duplex:"half",body:o,headers:{authorization:`Bearer ${a.hostApiToken}`,"content-length":String(r.sizeBytes),"content-type":r.contentType??"application/octet-stream"}},g=await fetch(d("stream",t),l);if(!g.ok)throw new Error(`Tego storage stream write failed: ${g.status}`)},"putStream"),put:n(async(t,o,r)=>{const l=await fetch(d("put",t),{method:"POST",headers:{authorization:`Bearer ${a.hostApiToken}`,"content-type":r??"application/octet-stream"},body:$(o)});if(!l.ok)throw new Error(`Tego storage put failed: ${l.status}`)},"put"),get:n(async(t,o)=>{const r=o?.firstBytes,l=d("get",t),g=await fetch(r===void 0?l:`${l}&bytes=${r}`,{headers:{authorization:`Bearer ${a.hostApiToken}`}});if(g.status===404)return null;if(!g.ok)throw new Error(`Tego storage get failed: ${g.status}`);return new Uint8Array(await g.arrayBuffer())},"get"),head:n(async t=>{const o=await fetch(`${a.hostApiUrl}/storage/head`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${a.hostApiToken}`},body:JSON.stringify({key:t})});if(o.status===404)return null;if(!o.ok)throw new Error(`Tego storage head failed: ${o.status}`);const r=await o.json();if(!r.data)throw new Error("Tego host API returned no object head");return r.data},"head"),delete:n(async t=>{await e("/storage/delete",{key:t})},"delete"),signedUrl:n(async(t,o)=>{const g=(await(await e("/storage/signed-url",{key:t,ttlSeconds:o})).json()).data?.url;if(!g)throw new Error("Tego host API returned no signed url");return g},"signedUrl"),signedPath:n(async(t,o)=>{const g=(await(await e("/storage/signed-url",{key:t,ttlSeconds:o})).json()).data?.path;if(!g)throw new Error("Tego host API returned no signed path");return g},"signedPath"),managedPath:n(async(t,o,r)=>{const g=await(await e("/storage/signed-url",{key:t,policy:o,ttlSeconds:r})).json();if(!g.data?.path)throw new Error("Tego host API returned no managed path");return g.data.path},"managedPath"),uploadPath:n(async(t,o)=>{const l=await(await e("/storage/upload-url",{key:t,maxBytes:o?.maxBytes,ttlSeconds:o?.ttlSeconds})).json();if(!l.data?.path)throw new Error("Tego host API returned no upload path");return l.data},"uploadPath")},w={publish:n(async(t,o)=>{await e("/events",{name:t,payload:o})},"publish")},f={send:n(async t=>{const r=await(await e("/notifications",t)).json();if(!r.data?.id)throw new Error("Tego host API returned no notification id");return{id:r.data.id}},"send")},A={async emit(t){const r=await(await e("/proactive/emit",t)).json();if(!r.data)throw new Error("Tego proactive response is missing data");return r.data}},i=n(async(t,o)=>{const l=await(await e(t,o)).json();if(!l.data)throw new Error("Tego attention response is missing data");return l.data},"attentionStatus"),u={async request(t){const r=await(await e("/attention/requests",t)).json();if(!r.data?.itemId)throw new Error("Tego host API returned no attention item");return r.data},get:n(t=>i("/attention/requests/get",{itemId:t}),"get"),cancel:n(t=>i("/attention/requests/cancel",{itemId:t}),"cancel")},T={async send(t){const r=await(await e("/mail/send",t)).json();if(!r.data)throw new Error("Tego mail response is missing data");return r.data},async status(t){const r=await(await e("/mail/status",{userId:t})).json();if(!r.data)throw new Error("Tego mail response is missing data");return r.data},async unsubscribes(t={}){const r=await(await e("/mail/unsubscribes",t)).json();if(!r.data)throw new Error("Tego mail response is missing data");return r.data}};let b={};const v={current:n(()=>b,"current"),refresh:n(async()=>{const t=await fetch(`${a.hostApiUrl}/config`,{headers:{authorization:`Bearer ${a.hostApiToken}`}});if(!t.ok)throw new Error(`Tego host API /config failed: ${t.status} ${await t.text()}`);return b=(await t.json()).data?.values??{},b},"refresh")},I={async read(t,o){return(await(await e("/sources/read",{id:t,...o})).json()).data}},P={async list(t){const r=await(await e("/delegations/list",{userId:t})).json();if(!r.data)throw new Error("Tego delegation response is missing data");return r.data}},k={async verify(t){const r=await(await e("/knowledge/verify",t)).json();if(!r.data)throw new Error("Tego knowledge response is missing data");return r.data},collections:{ensure:n(t=>y("ensure",t),"ensure"),permissions:n(t=>y("permissions",t),"permissions"),move:n(t=>y("move",t),"move"),access:n(t=>y("access",t),"access"),import:n(t=>y("import",t),"import"),importFiles:n(t=>y("import-files",t),"importFiles"),status:n(t=>y("status",t),"status"),delete:n(t=>y("delete",t),"delete"),documentsStatus:n(t=>y("documents-status",t),"documentsStatus"),documentContent:n(t=>y("document-content",t),"documentContent"),search:n(t=>y("search",t),"search"),remove:n(t=>y("remove",t),"remove")}};async function y(t,o){const l=await(await e(`/knowledge/collections/${t}`,o)).json();if(!l.data)throw new Error("Tego knowledge collection response is missing data");return l.data}n(y,"collectionCall");const N={async identity(t){const r=await(await e("/directory/identity",{userId:t})).json();if(!r.data)throw new Error("Tego directory response is missing data");return r.data},async validate(t){const r=await(await e("/directory/validate",{principals:t})).json();if(!r.data)throw new Error("Tego directory response is missing data");return r.data},async list(t){const r=await(await e("/directory/list",t)).json();if(!r.data)throw new Error("Tego directory response is missing data");return r.data},async match(t){const r=await(await e("/directory/match",t)).json();if(!r.data)throw new Error("Tego directory response is missing data");return r.data}},G={provisionUser:n(t=>E("/accounts/provision",t),"provisionUser"),resetPassword:n(t=>E("/accounts/password/reset",t),"resetPassword"),inviteUser:n(t=>E("/accounts/invite",t),"inviteUser"),getInvitation:n(t=>E("/accounts/get",{invitationId:t}),"getInvitation"),resendInvitation:n(t=>E("/accounts/resend",{invitationId:t}),"resendInvitation")};async function E(t,o){const l=await(await e(t,o)).json();if(!l.data)throw new Error("Tego account response is missing data");return l.data}return n(E,"collectionEnvelope"),{accounts:G,log:s,storage:p,diagrams:{status:n(async()=>{const o=await(await e("/diagrams/status",{})).json();if(!o.data)throw new Error("Tego host API returned no renderer status");return o.data},"status"),render:n(async t=>{const r=await(await e("/diagrams/render",t)).json();if(!r.data?.key)throw new Error("Tego host API returned no diagram artifact");return r.data},"render")},events:w,notifications:f,proactive:A,attention:u,mail:T,config:v,sources:I,directory:N,knowledge:k,knowledgeAdmin:{listManageableBases:n(t=>E("/knowledge/admin/list",t),"listManageableBases"),previewCreateBase:n(t=>E("/knowledge/admin/create-preview",t),"previewCreateBase"),createApprovedBase:n(t=>E("/knowledge/admin/create",t),"createApprovedBase"),prepareDocumentContent:n(t=>E("/knowledge/admin/prepare",t),"prepareDocumentContent"),previewDocumentBatch:n(t=>E("/knowledge/admin/preview",t),"previewDocumentBatch"),stageApprovedDocumentBatch:n(t=>E("/knowledge/admin/import",t),"stageApprovedDocumentBatch"),getTask:n(t=>E("/knowledge/admin/task",t),"getTask")},delegations:P}}n(W,"createHostClient");var K=5e3,J=15e3;function x(a){let e=null;async function s(){if(e)return e;const c=await import("pg"),d=c.default?.Pool??c.Pool;if(!d)throw new Error('The "pg" module resolved without a Pool constructor. The plugin runtime expects the driver the runner image provides.');return e=new d({connectionString:a,connectionTimeoutMillis:K}),e}return n(s,"ensurePool"),{query:n(async(c,d)=>(await(await s()).query(c,d)).rows,"query"),transaction:n(async c=>{const p=await(await s()).connect();let w=!0,f=!1;const A={query:n(async(i,u)=>{if(f)throw new Error("This transaction has already ended; its `tx` cannot be used afterwards.");return(await p.query(i,u)).rows},"query")};try{await p.query("BEGIN"),await p.query(`SET LOCAL idle_in_transaction_session_timeout = ${J}`);const i=await c(A);return await p.query("COMMIT"),i}catch(i){try{await p.query("ROLLBACK")}catch{w=!1}throw i}finally{f=!0,p.release(w?void 0:!0)}},"transaction")}}n(x,"createScopedDb");function S(a,e){const s=`http://localhost${a.url??"/"}`,c=new Headers;for(const[p,w]of Object.entries(a.headers))w!==void 0&&c.set(p,Array.isArray(w)?w.join(", "):w);const d=a.method??"GET";return new Request(s,{method:d,headers:c,...d==="GET"||d==="HEAD"?{}:{body:e}})}n(S,"toWebRequest");async function _(a,e){const s={};e.headers.forEach((c,d)=>{s[d]=c}),a.writeHead(e.status,s),a.end(Buffer.from(await e.arrayBuffer()))}n(_,"writeWebResponse");function j(a,e){return new Promise((s,c)=>{const d=[];let p=0;a.on("data",w=>{if(p+=w.length,e!==void 0&&p>e){c(new Error("Policy request body too large")),a.destroy();return}d.push(w)}),a.on("end",()=>{s($(Buffer.concat(d)))}),a.on("error",c)})}n(j,"readBody");function Y(a){const e=z(process.env),s={pluginId:e.pluginId,tenantId:e.tenantId,db:x(e.databaseUrl),...W(e)},c=D((i,u)=>{(async()=>{try{const T=(i.url??"/").split("?")[0];if(T===e.healthPath){u.writeHead(200,{"content-type":"application/json"}),u.end('{"status":"ok"}');return}if(i.headers["x-tego-plugin-storage-policy"]==="1"){const I=await j(i,16384),P=n(y=>typeof i.headers[y]=="string"?i.headers[y]:"","header"),k={installId:P("x-tego-plugin-install-id"),tenantId:P("x-tego-plugin-tenant-id"),issuedAt:P("x-tego-plugin-issued-at"),bodyHash:P("x-tego-plugin-body-hash")};if(T!==R||i.method!=="POST"||!k.installId||!k.tenantId||!M({context:k,signature:P("x-tego-plugin-signature"),key:e.gatewayKey,nowMs:Date.now(),body:Buffer.from(I).toString("utf8")})){u.writeHead(401),u.end();return}if(!a.authorizeStorage){u.writeHead(404),u.end();return}await _(u,await a.authorizeStorage(S(i,I),k,s));return}if(i.headers[m.public]==="1"){const I=U(i.headers,{key:e.gatewayKey,nowMs:Date.now()});if(!I){u.writeHead(401,{"content-type":"application/json"}),u.end('{"error":"missing or unverifiable tego plugin context"}');return}if(!a.fetchPublic){u.writeHead(404,{"content-type":"application/json"}),u.end('{"error":"not found"}');return}const P=await j(i);await _(u,await a.fetchPublic(S(i,P),I,s));return}const b=O(i.headers,{key:e.gatewayKey,nowMs:Date.now()});if(!b){u.writeHead(401,{"content-type":"application/json"}),u.end('{"error":"missing or unverifiable tego plugin context"}');return}const h=await j(i),v=await a.fetch(S(i,h),b,s);await _(u,v)}catch(T){s.log.error("Unhandled error in plugin backend",{error:T instanceof Error?T.message:String(T)}),u.headersSent?u.end():(u.writeHead(500,{"content-type":"application/json"}),u.end('{"error":"plugin backend failed"}'))}})()});let d=!1,p=!1,w;const f=n(()=>(w??=Promise.resolve().then(()=>a.stop?.()),w),"stopModule"),A=(async()=>{const i=await F(s,e);if(i)throw new Error(i);d||(p=!0,await a.start?.(s),!d&&c.listen(e.port,()=>{s.log.info(`Plugin backend listening on ${e.port}`)}))})();A.catch(async i=>{console.error("Plugin backend startup failed",i);try{p&&await f()}catch(u){console.error("Plugin backend shutdown failed",u)}process.exit(1)}),process.on("SIGTERM",()=>{d||(d=!0,Promise.all([new Promise(i=>c.close(()=>i())),A.then(async()=>{p&&await f()})]).then(()=>process.exit(0)).catch(i=>{console.error("Plugin backend shutdown failed",i),process.exit(1)}))})}n(Y,"serveBackend");async function F(a,e){const s=await B(a.db,e.databaseUrl);if(s)return s;try{await a.config.refresh()}catch(c){return`Plugin backend cannot read its configuration from the host API: ${c instanceof Error?c.message:String(c)}`}return null}n(F,"startUp");async function B(a,e){try{return await a.query("select 1"),null}catch(s){return`Plugin backend cannot reach its database at ${Q(e)}: ${s instanceof Error?s.message:String(s)}`}}n(B,"checkDatabaseReachable");function Q(a){try{const e=new URL(a);return`${e.host}${e.pathname}`}catch{return"the address in DATABASE_URL"}}n(Q,"describeDatabaseTarget");export{B as checkDatabaseReachable,x as createScopedDb,U as readPublicContext,O as readUserContext,Y as serveBackend};
|
package/dist/server.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var r=Object.defineProperty;var e=(t,n)=>r(t,"name",{value:n,configurable:!0});var chunkBN6TGHSB_cjs=require("./chunk-BN6TGHSB.cjs");Object.defineProperty(exports,"PLUGIN_COLLECTION_CONTENT_PAGE_MAX",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.PLUGIN_COLLECTION_CONTENT_PAGE_MAX},"get")}),Object.defineProperty(exports,"PLUGIN_COLLECTION_IMPORT_MAX",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.PLUGIN_COLLECTION_IMPORT_MAX},"get")}),Object.defineProperty(exports,"PLUGIN_CONTEXT_HEADERS",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.PLUGIN_CONTEXT_HEADERS},"get")}),Object.defineProperty(exports,"accountInvitationSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.accountInvitationSchema},"get")}),Object.defineProperty(exports,"accountInviteSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.accountInviteSchema},"get")}),Object.defineProperty(exports,"accountPasswordResetSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.accountPasswordResetSchema},"get")}),Object.defineProperty(exports,"accountProvisionSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.accountProvisionSchema},"get")}),Object.defineProperty(exports,"definePluginBackend",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.definePluginBackend},"get")}),Object.defineProperty(exports,"directoryIdentitySchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.directoryIdentitySchema},"get")}),Object.defineProperty(exports,"directoryListSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.directoryListSchema},"get")}),Object.defineProperty(exports,"directoryMatchSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.directoryMatchSchema},"get")}),Object.defineProperty(exports,"directoryPrincipalSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.directoryPrincipalSchema},"get")}),Object.defineProperty(exports,"directoryValidateSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.directoryValidateSchema},"get")}),Object.defineProperty(exports,"pluginAdminActionSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginAdminActionSchema},"get")}),Object.defineProperty(exports,"pluginAdminProofSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginAdminProofSchema},"get")}),Object.defineProperty(exports,"pluginApprovalDigestSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginApprovalDigestSchema},"get")}),Object.defineProperty(exports,"pluginApprovedSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginApprovedSchema},"get")}),Object.defineProperty(exports,"pluginCollectionAccessSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginCollectionAccessSchema},"get")}),Object.defineProperty(exports,"pluginCollectionDeleteSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginCollectionDeleteSchema},"get")}),Object.defineProperty(exports,"pluginCollectionDocumentContentSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginCollectionDocumentContentSchema},"get")}),Object.defineProperty(exports,"pluginCollectionDocumentsStatusSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginCollectionDocumentsStatusSchema},"get")}),Object.defineProperty(exports,"pluginCollectionEnsureSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginCollectionEnsureSchema},"get")}),Object.defineProperty(exports,"pluginCollectionImportFilesSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginCollectionImportFilesSchema},"get")}),Object.defineProperty(exports,"pluginCollectionImportSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginCollectionImportSchema},"get")}),Object.defineProperty(exports,"pluginCollectionMoveSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginCollectionMoveSchema},"get")}),Object.defineProperty(exports,"pluginCollectionPermissionsSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginCollectionPermissionsSchema},"get")}),Object.defineProperty(exports,"pluginCollectionRemoveSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginCollectionRemoveSchema},"get")}),Object.defineProperty(exports,"pluginCollectionSearchSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginCollectionSearchSchema},"get")}),Object.defineProperty(exports,"pluginCollectionStatusSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginCollectionStatusSchema},"get")}),Object.defineProperty(exports,"pluginDiagramSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginDiagramSchema},"get")}),Object.defineProperty(exports,"pluginDocumentBatchInputSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginDocumentBatchInputSchema},"get")}),Object.defineProperty(exports,"pluginDocumentBatchItemSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginDocumentBatchItemSchema},"get")}),Object.defineProperty(exports,"pluginDocumentContentInputSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginDocumentContentInputSchema},"get")}),Object.defineProperty(exports,"pluginKnowledgeBaseInputSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginKnowledgeBaseInputSchema},"get")}),Object.defineProperty(exports,"pluginKnowledgeListInputSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginKnowledgeListInputSchema},"get")}),Object.defineProperty(exports,"pluginKnowledgeReferenceSchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginKnowledgeReferenceSchema},"get")}),Object.defineProperty(exports,"pluginKnowledgeVerifySchema",{enumerable:!0,get:e(function(){return chunkBN6TGHSB_cjs.pluginKnowledgeVerifySchema},"get")});
|