@aerostack/gateway 0.15.10 → 0.15.12
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/exec-approval-server.js +3 -3
- package/dist/index.js +12 -12
- package/package.json +1 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createServer as
|
|
2
|
-
`);if(i===-1)return;const
|
|
3
|
-
`),e.end()}catch{}}export{
|
|
1
|
+
import{createServer as y}from"node:net";import{unlink as d,mkdir as w,readFile as v,writeFile as E}from"node:fs/promises";import{timingSafeEqual as _}from"node:crypto";import{dirname as x,join as k}from"node:path";import{homedir as S}from"node:os";import{info as b,warn as m,debug as p,error as h}from"./logger.js";import{addToBatch as O}from"./hook-server.js";const g=k(S(),".openclaw","pre-authorized.json"),A=6e4;async function P(e){if(!e)return!1;try{const t=JSON.parse(await v(g,"utf-8")),a=t[e];if(a&&Date.now()-a<A)return delete t[e],await E(g,JSON.stringify(t)).catch(()=>{}),!0}catch{}return!1}function C(e){const t=e.toLowerCase();return/\brm\s+-rf?\b|\bdrop\s|\bdelete\s|\btruncate\s|\bformat\b/.test(t)?"critical":/\brm\b|\bgit\s+push\b|\bgit\s+reset\b|\bdeploy\b|\bkill\b/.test(t)?"high":/\binstall\b|\bpip\b|\bnpm\b|\bcurl\b|\bwget\b/.test(t)?"medium":"low"}function T(e){const t=e.toLowerCase();return/\brm\b|\bunlink\b|\brmdir\b/.test(t)?"file_delete":/\bgit\s+push\b|\bdeploy\b|\bwrangler\b/.test(t)?"deploy":/\binstall\b|\bpip\b|\bnpm\b|\byarn\b/.test(t)?"package_install":/\bcurl\b|\bwget\b|\bfetch\b/.test(t)?"api_call":/\bwrite\b|\btee\b|\b>\b|\bcat\s.*>/.test(t)?"file_write":"exec_command"}function j(e){let t=null,a=!1;return(async()=>{await w(x(e.socketPath),{recursive:!0}).catch(()=>{}),await d(e.socketPath).catch(()=>{}),t=y(r=>{D(r,e)}),t.on("error",r=>{r.code==="EADDRINUSE"?m("Exec approval socket in use, skipping",{path:e.socketPath}):h("Exec approval server error",{error:r.message})}),t.listen(e.socketPath,()=>{b("Exec approval server started",{path:e.socketPath})})})().catch(r=>{m("Exec approval server failed to start",{error:r instanceof Error?r.message:String(r)})}),{stop:()=>{a||(a=!0,t&&(t.close(),t=null),d(e.socketPath).catch(()=>{}))}}}function D(e,t){let a="";const n=setTimeout(()=>{p("Exec approval timeout, denying"),o(e,"deny")},14e3);e.on("data",r=>{a+=r.toString("utf-8");const i=a.indexOf(`
|
|
2
|
+
`);if(i===-1)return;const s=a.slice(0,i).trim();a=a.slice(i+1),clearTimeout(n);try{const c=JSON.parse(s),l=Buffer.from(c.token??""),f=Buffer.from(t.token);if(l.length!==f.length||!_(l,f)){p("Exec approval token mismatch"),o(e,"deny");return}L(c,e,t).catch(u=>{h("Exec approval processing error",{error:u instanceof Error?u.message:String(u)}),o(e,"deny")})}catch{o(e,"deny")}}),e.on("error",()=>{clearTimeout(n)})}async function L(e,t,a){const n=e.request.command??e.request.args?.join(" ")??"unknown",r=C(n),i=T(n),s=e.request.sessionKey??"",c=e.request.agentId??"";if(O({action:`[exec-approval] ${n}`.slice(0,500),category:i,risk_level:r,details:JSON.stringify({command:n,host:e.request.host,agent:c,session:s,security:e.request.security}).slice(0,500),agent_name:"OpenClaw"}),a.rpcCall("tools/call",{name:"aerostack__guardian_report",arguments:{action:`OpenClaw exec: ${n}`.slice(0,500),category:i,risk_level:r,details:JSON.stringify({command:n,agent:c,session:s}).slice(0,500)}}).catch(()=>{}),r==="critical"||r==="high"){if(await P(s)){b("Exec approval ALLOWED (pre-authorized by dashboard)",{command:n.slice(0,100),risk:r}),o(t,"allow-once");return}b("Exec approval DENIED (high risk)",{command:n.slice(0,100),risk:r}),a.rpcCall("tools/call",{name:"aerostack__local_guardian",arguments:{action:n.slice(0,500),category:i,risk_level:r,details:`OpenClaw agent ${c} wants to execute: ${n}`}}).catch(()=>{}),o(t,"deny")}else p("Exec approval ALLOWED",{command:n.slice(0,100),risk:r}),o(t,"allow-once")}function o(e,t){try{e.write(JSON.stringify({type:"decision",decision:t})+`
|
|
3
|
+
`),e.end()}catch{}}export{j as startExecApprovalServer};
|
package/dist/index.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
import{Server as
|
|
4
|
-
`),process.exit(1)),
|
|
5
|
-
`),process.exit(1));let
|
|
6
|
-
`),process.exit(1)}
|
|
7
|
-
`);const
|
|
8
|
-
`);let e=null;for(const
|
|
3
|
+
import{Server as k}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as P}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as C,CallToolRequestSchema as N,ListResourcesRequestSchema as I,ReadResourceRequestSchema as b,ListPromptsRequestSchema as L,GetPromptRequestSchema as U}from"@modelcontextprotocol/sdk/types.js";import{readFile as $,writeFile as K}from"node:fs/promises";import{join as D}from"node:path";import{homedir as x}from"node:os";import{resolveApproval as j}from"./resolution.js";import{startHookServer as q,installClaudeHook as H,stopHookServer as V}from"./hook-server.js";import{OpenClawConnector as M,resolveOpenClawToken as G}from"./openclaw-connector.js";import{info as i,warn as w,error as W}from"./logger.js";const g=D(x(),".openclaw","pre-authorized.json");async function Y(t){try{let s={};try{s=JSON.parse(await $(g,"utf-8"))}catch{}s[t]=Date.now(),await K(g,JSON.stringify(s))}catch{}}const R=process.env.AEROSTACK_WORKSPACE_URL,h=process.env.AEROSTACK_TOKEN;function f(t,s,r){const e=parseInt(t??String(s),10);return Number.isFinite(e)&&e>=r?e:s}const B=f(process.env.AEROSTACK_APPROVAL_POLL_MS,3e3,500),J=f(process.env.AEROSTACK_APPROVAL_TIMEOUT_MS,864e5,5e3),z=f(process.env.AEROSTACK_REQUEST_TIMEOUT_MS,3e4,1e3),F=process.env.AEROSTACK_HOOK_SERVER!=="false",Q=f(process.env.AEROSTACK_HOOK_PORT,18321,1024),X=process.env.AEROSTACK_HOOK_AUTO_INSTALL!=="false",Z=process.env.AEROSTACK_OPENCLAW_ENABLED!=="false",y=f(process.env.AEROSTACK_OPENCLAW_PORT,18789,1024),ee=process.env.AEROSTACK_OPENCLAW_TOKEN;R||(process.stderr.write(`ERROR: AEROSTACK_WORKSPACE_URL is required
|
|
4
|
+
`),process.exit(1)),h||(process.stderr.write(`ERROR: AEROSTACK_TOKEN is required
|
|
5
|
+
`),process.exit(1));let A;try{if(A=new URL(R),A.protocol!=="https:"&&A.protocol!=="http:")throw new Error("must be http or https")}catch{process.stderr.write(`ERROR: AEROSTACK_WORKSPACE_URL must be a valid HTTP(S) URL
|
|
6
|
+
`),process.exit(1)}A.protocol==="http:"&&!A.hostname.match(/^(localhost|127\.0\.0\.1)$/)&&process.stderr.write(`WARNING: Using HTTP (not HTTPS) \u2014 token will be sent in plaintext
|
|
7
|
+
`);const d=R.replace(/\/+$/,""),te=crypto.randomUUID(),se=process.env.AEROSTACK_AGENT_TYPE||"unknown";let u=null;async function c(t,s){const r={jsonrpc:"2.0",id:Date.now(),method:t,params:s??{}},e=new AbortController,o=setTimeout(()=>e.abort(),z);try{const n=await fetch(d,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`,"User-Agent":"aerostack-gateway/0.15.8","X-Agent-Id":"aerostack-gateway","X-Bridge-Id":te,"X-Agent-Type":se},body:JSON.stringify(r),signal:e.signal});if(clearTimeout(o),(n.headers.get("content-type")??"").includes("text/event-stream")){const v=await n.text();return re(v,r.id)}return await n.json()}catch(n){clearTimeout(o);const a=n instanceof Error?n.message:"Unknown error";return n instanceof Error&&n.name==="AbortError"?{jsonrpc:"2.0",id:r.id,error:{code:-32603,message:"Request timed out"}}:{jsonrpc:"2.0",id:r.id,error:{code:-32603,message:`HTTP error: ${a}`}}}}function re(t,s){const r=t.split(`
|
|
8
|
+
`);let e=null;for(const o of r)if(o.startsWith("data: "))try{e=JSON.parse(o.slice(6))}catch{}return e??{jsonrpc:"2.0",id:s,error:{code:-32603,message:"Empty SSE response"}}}const oe=new Set(["aerostack__guardian_report","aerostack__check_approval","aerostack__guardian_check"]);function ne(t,s){if(oe.has(t))return;let r="other";const e=t.toLowerCase();e.includes("exec")||e.includes("bash")||e.includes("shell")||e.includes("command")||e.includes("run")?r="exec_command":e.includes("write")||e.includes("edit")||e.includes("create")||e.includes("patch")?r="file_write":e.includes("delete")||e.includes("remove")||e.includes("trash")||e.includes("unlink")?r="file_delete":e.includes("fetch")||e.includes("http")||e.includes("request")||e.includes("api")||e.includes("get")||e.includes("post")?r="api_call":e.includes("install")||e.includes("package")||e.includes("npm")||e.includes("pip")?r="package_install":e.includes("config")||e.includes("setting")||e.includes("env")?r="config_change":e.includes("deploy")||e.includes("publish")||e.includes("release")?r="deploy":e.includes("send")||e.includes("message")||e.includes("email")||e.includes("notify")||e.includes("slack")||e.includes("telegram")?r="message_send":(e.includes("read")||e.includes("query")||e.includes("search")||e.includes("list")||e.includes("get"))&&(r="data_access");let o;try{const n=JSON.stringify(s);o=n.length>500?n.slice(0,500)+"...":n}catch{o="(unable to serialize)"}c("tools/call",{name:"aerostack__guardian_report",arguments:{action:`${t}(${Object.keys(s).join(", ")})`,category:r,risk_level:"low",details:o}}).catch(()=>{})}const ae=new Set(["aerostack__check_approval"]);async function ie(t,s){ne(t,s);const r=await c("tools/call",{name:t,arguments:s});if(r.error?.code===-32050){const n=r.error.data,a=n?.approval_id;if(!a||!/^[a-zA-Z0-9_-]{4,128}$/.test(a))return{jsonrpc:"2.0",id:r.id,error:{code:-32603,message:"Approval required but no approval_id returned"}};const l=u?.getLastActiveSession()??null;return i("Tool gate: returning pending, background resolver started",{tool:t,approvalId:a,sessionKey:l}),O({approvalId:a,toolName:t,toolArgs:s,sessionKey:l,gate:"tool_gate",wsUrl:n?.ws_url,pollUrl:n?.polling_url??`${d}/approval-status/${a}`,authToken:h}),{jsonrpc:"2.0",id:r.id,result:{content:[{type:"text",text:`This action requires workspace approval.
|
|
9
9
|
|
|
10
10
|
Tool: ${t}
|
|
11
11
|
Status: Pending review by workspace owner
|
|
12
12
|
|
|
13
|
-
The gateway will resume this task automatically once a decision is made. You may continue with other tasks in the meantime.`}]}}}const
|
|
13
|
+
The gateway will resume this task automatically once a decision is made. You may continue with other tasks in the meantime.`}]}}}const o=r.result?._meta;if(o?.approval_id&&o?.status==="pending"){const n=o.approval_id;if(!/^[a-zA-Z0-9_-]{4,128}$/.test(n))return r;const a=u?.getLastActiveSession()??null;return i("Permission gate: returning pending, background resolver started",{tool:t,approvalId:n,sessionKey:a}),O({approvalId:n,toolName:t,toolArgs:s,sessionKey:a,gate:"permission_gate",wsUrl:o.ws_url,pollUrl:o.polling_url??`${d}/approval-status/${n}`,authToken:h}),{jsonrpc:"2.0",id:r.id,result:{content:[{type:"text",text:`Permission request submitted for workspace review.
|
|
14
14
|
|
|
15
15
|
Action: ${t}
|
|
16
16
|
Status: Pending
|
|
17
17
|
|
|
18
|
-
I'll be notified when the workspace owner decides. You may continue with other tasks.`}]}}}return r}function
|
|
19
|
-
`):["[APPROVAL RECEIVED] Your request has been approved by the workspace owner.",r?`Reviewer note: "${r}"`:null,"","You may now proceed with the action you requested approval for."].filter(
|
|
18
|
+
I'll be notified when the workspace owner decides. You may continue with other tasks.`}]}}}return r}function O(t){j({approvalId:t.approvalId,wsUrl:t.wsUrl,pollUrl:t.pollUrl,pollIntervalMs:B,timeoutMs:J,token:t.authToken}).then(async s=>{i("Approval resolved",{tool:t.toolName,status:s.status,session:t.sessionKey});const r=ce(t,s),e=t.sessionKey??u?.getLastActiveSession()??null;if((s.status==="approved"||s.status==="executed")&&e&&Y(e).catch(()=>{}),e&&u){if(await u.sendToSession(e,r)){i("Agent resumed via sessions.send",{session:e,status:s.status}),_(t,s.status,!0);return}w("sessions.send failed, session may have ended",{session:e}),_(t,s.status,!1)}else w("No session key available for resume",{tool:t.toolName,approvalId:t.approvalId}),_(t,s.status,!1)}).catch(s=>{w("Background approval resolver error",{error:s instanceof Error?s.message:String(s)})})}function _(t,s,r){const e=typeof t.toolArgs.action=="string"?t.toolArgs.action:null,o=e??t.toolName.replace(/^(?:\w+__)*aerostack__/,"")??t.toolName,n=e?`${o}`:`${o}(${Object.keys(t.toolArgs).join(", ")})`,a=r?"resume sent to agent":"session unavailable \u2014 resume not delivered";let l;s==="approved"||s==="executed"?l=r?`[RESUMED] ${n} \u2014 ${a}`:`[RESUME FAILED] ${n} \u2014 ${a}`:s==="rejected"?l=`[REJECTED] ${n} \u2014 rejection sent to agent`:s==="changes_requested"?l=`[CHANGES REQUESTED] ${n} \u2014 feedback sent to agent`:l=`[EXPIRED] ${n} \u2014 approval timed out, expiry sent to agent`,c("tools/call",{name:"aerostack__guardian_report",arguments:{action:l.slice(0,500),category:"approval",risk_level:"low",details:JSON.stringify({tool:t.toolName,approvalId:t.approvalId,status:s,delivered:r,session:t.sessionKey}).slice(0,500)}}).catch(()=>{})}function ce(t,s){const r=s.reviewer_note?.trim()||null,e=`${t.toolName}(${Object.keys(t.toolArgs).join(", ")})`;switch(s.status){case"approved":case"executed":return t.gate==="tool_gate"?["[APPROVAL RECEIVED] Your pending action has been approved.","",`Action: ${e}`,r?`Reviewer note: "${r}"`:null,"",`Please now execute this action: call ${t.toolName} with the same parameters as before.`].filter(o=>o!==null).join(`
|
|
19
|
+
`):["[APPROVAL RECEIVED] Your request has been approved by the workspace owner.",r?`Reviewer note: "${r}"`:null,"","You may now proceed with the action you requested approval for."].filter(o=>o!==null).join(`
|
|
20
20
|
`);case"changes_requested":return["[CHANGES REQUESTED] The workspace owner reviewed your action and requested changes.","",`Original action: ${e}`,`Reviewer feedback: "${r??"No details provided"}"`,"","Please revise your approach based on this feedback and try again.","Do NOT proceed with the original plan."].join(`
|
|
21
21
|
`);case"rejected":return["[REJECTED] The workspace owner denied this action.","",`Action: ${e}`,r?`Reason: "${r}"`:"No reason provided.","","Do not retry this action. If you believe this was a mistake, inform the user."].join(`
|
|
22
22
|
`);case"expired":return[`[EXPIRED] The approval request for "${e}" timed out \u2014 no decision was made.`,"","You may resubmit the request if the action is still needed."].join(`
|
|
23
|
-
`);default:return`[APPROVAL UPDATE] Status for "${e}": ${s.status}.`}}const
|
|
23
|
+
`);default:return`[APPROVAL UPDATE] Status for "${e}": ${s.status}.`}}const E=`
|
|
24
24
|
=== AEROSTACK GUARDIAN POLICY (MANDATORY) ===
|
|
25
25
|
|
|
26
26
|
You are operating under Aerostack workspace monitoring. These rules apply to ALL actions:
|
|
@@ -41,6 +41,6 @@ the result once the workspace owner approves. Simply wait; do not retry or proce
|
|
|
41
41
|
These rules exist to protect the workspace owner. Violating them may result in your session
|
|
42
42
|
being terminated. Compliance is non-negotiable.
|
|
43
43
|
=== END GUARDIAN POLICY ===
|
|
44
|
-
`.trim(),
|
|
44
|
+
`.trim(),le=["delete","remove","drop","truncate","destroy","wipe","reset","deploy","publish","release","push","exec","shell","bash","run","command","terminal","install","uninstall","send","email","notify","webhook"];function ue(t,s){const r=t.toLowerCase(),e=le.some(n=>r.includes(n)),o=s??"";return e?`[REQUIRES GUARDIAN APPROVAL] ${o}`.trim():o}let T=null;async function m(){if(T)return;const t=await c("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"aerostack-gateway",version:"0.15.8"}});if(t.result){const s=t.result,r=s.instructions??"";T={protocolVersion:s.protocolVersion??"2024-11-05",instructions:r?`${r}
|
|
45
45
|
|
|
46
|
-
${
|
|
46
|
+
${E}`:E}}}const p=new k({name:"aerostack-gateway",version:"0.15.8"},{capabilities:{tools:{},resources:{},prompts:{}},instructions:E});p.setRequestHandler(C,async()=>{await m();const t=await c("tools/list");if(t.error)throw new Error(t.error.message);return{tools:(t.result.tools??[]).filter(e=>!ae.has(e.name)).map(e=>({...e,description:ue(e.name,e.description)}))}}),p.setRequestHandler(N,async t=>{await m();const{name:s,arguments:r}=t.params,e=await ie(s,r??{});return e.error?{content:[{type:"text",text:`Error: ${e.error.message}`}],isError:!0}:{content:e.result.content??[{type:"text",text:JSON.stringify(e.result)}]}});const pe={uri:"aerostack://guardian/policy",name:"Aerostack Guardian Policy",description:"Mandatory workspace monitoring policy. Read this to understand required approval workflows.",mimeType:"text/plain"};p.setRequestHandler(I,async()=>{await m();const t=await c("resources/list");if(t.error)throw new Error(t.error.message);const s=t.result;return{resources:[pe,...s.resources??[]]}}),p.setRequestHandler(b,async t=>{if(await m(),t.params.uri==="aerostack://guardian/policy")return{contents:[{uri:t.params.uri,text:E,mimeType:"text/plain"}]};const s=await c("resources/read",{uri:t.params.uri});if(s.error)throw new Error(s.error.message);return{contents:s.result.contents??[]}}),p.setRequestHandler(L,async()=>{await m();const t=await c("prompts/list");if(t.error)throw new Error(t.error.message);return{prompts:t.result.prompts??[]}}),p.setRequestHandler(U,async t=>{await m();const s=await c("prompts/get",{name:t.params.name,arguments:t.params.arguments});if(s.error)throw new Error(s.error.message);return{messages:s.result.messages??[]}});async function de(){i("Connecting to workspace",{url:d});const t=new P;if(await p.connect(t),i("Ready",{url:d}),F)try{const r=await q(async e=>{try{const o=await fetch(`${d}/guardian-batch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`,"User-Agent":"aerostack-gateway/0.15.8","X-Agent-Id":"aerostack-gateway"},body:JSON.stringify({events:e})});return o.ok?(await o.json()).config?.hook_tracking??null:null}catch{return null}},Q);X&&await H(r)&&i("Claude Code hook auto-installed",{port:r})}catch(s){w("Hook server failed to start (non-fatal)",{error:s instanceof Error?s.message:String(s)})}if(Z)try{const s=ee??await G();s?(u=new M({port:y,token:s,rpcCall:c}),await u.connect()?i("OpenClaw connector started",{port:y}):(i("OpenClaw gateway not reachable, skipping connector"),u=null)):i("OpenClaw integration skipped (no token found)")}catch(s){w("OpenClaw connector failed (non-fatal)",{error:s instanceof Error?s.message:String(s)})}}function S(){u?.stop(),V(),process.exit(0)}process.on("SIGTERM",()=>{S()}),process.on("SIGINT",()=>{S()}),de().catch(t=>{W("Fatal error",{error:t instanceof Error?t.message:String(t)}),process.exit(1)});
|