@chatpanel/bridge 0.44.2 → 0.46.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/package.json +1 -1
- package/scripts/sync-events.mjs +2 -2
- package/src/access-gate.js +1 -0
- package/src/aws-credentials.js +4 -0
- package/src/cli-errors.js +6 -5
- package/src/engines/claude-warm.js +3 -3
- package/src/engines/claude.js +6 -6
- package/src/engines/codex-appserver.js +5 -5
- package/src/env.js +2 -2
- package/src/events/access-request.js +1 -0
- package/src/events/agent-permission.js +2 -2
- package/src/events/harness-cards.js +1 -1
- package/src/events/policy.js +1 -0
- package/src/events/runtime-host.js +1 -0
- package/src/events/sandbox-choice.js +1 -0
- package/src/events/sandbox-grant.js +1 -1
- package/src/events/sandbox-policy.js +1 -1
- package/src/pii/pii-detect.js +2 -2
- package/src/pii/tool-harness.js +1 -1
- package/src/sandbox-command.js +1 -0
- package/src/sandbox-host.js +1 -1
- package/src/sandbox-srt.js +1 -1
- package/src/sandbox.js +1 -1
- package/src/server.js +12 -9
- package/src/warm-pool.js +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventError as a}from"./event.js";const l=Object.freeze({claude:{label:"Claude Code",vendor:"Anthropic",hosts:["api.anthropic.com"],repoint:"limited",how:"ANTHROPIC_BASE_URL (+ ANTHROPIC_AUTH_TOKEN) to an Anthropic-compatible endpoint — this gateway’s /v1/messages qualifies",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud",session:{resume:["--resume","{id}"],off:["--no-session-persistence"],name:["--name","{name}"]}},codex:{label:"Codex",vendor:"OpenAI",hosts:["api.openai.com","chatgpt.com"],repoint:"limited",how:"OPENAI_BASE_URL, or a model_provider in ~/.codex/config.toml pointing at an OpenAI-compatible endpoint",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud",ownSandbox:"computer use (controlling the browser and other apps)",session:{resume:["resume","{id}"],off:["--ephemeral"]}},antigravity:{label:"Antigravity",vendor:"Google",hosts:["*.googleapis.com"],repoint:"no",how:"",dirs:null,defaultModel:"cloud"},kiro:{label:"Kiro",vendor:"AWS",hosts:["*.amazonaws.com"],repoint:"no",how:"",dirs:null,defaultModel:"cloud"},copilot:{label:"GitHub Copilot",vendor:"GitHub",hosts:["api.githubcopilot.com","*.github.com"],repoint:"no",how:"",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud",session:{resume:["--session-id","{id}"],off:null,name:["--name","{name}"]}},deepseek:{label:"DeepSeek Harness",vendor:"DeepSeek",hosts:["api.deepseek.com"],repoint:"limited",how:"its base URL setting, to an OpenAI-compatible endpoint",dirs:null,defaultModel:"cloud"},opencode:{label:"OpenCode",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — any OpenAI-compatible endpoint, Ollama, LM Studio, or this gateway",dirs:null,defaultModel:"configurable",session:{resume:["--session","{id}"],off:null,name:["--title","{name}"]}},pi:{label:"Pi",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — any OpenAI-compatible endpoint, or this gateway",dirs:null,defaultModel:"configurable"},hermes:{label:"Hermes",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — a local model is a first-class choice",dirs:null,defaultModel:"configurable"}}),p=
|
|
1
|
+
import{EventError as a}from"./event.js";const l=Object.freeze({claude:{label:"Claude Code",vendor:"Anthropic",hosts:["api.anthropic.com"],repoint:"limited",how:"ANTHROPIC_BASE_URL (+ ANTHROPIC_AUTH_TOKEN) to an Anthropic-compatible endpoint — this gateway’s /v1/messages qualifies",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud",session:{resume:["--resume","{id}"],off:["--no-session-persistence"],name:["--name","{name}"]},envFrom:["~/.claude/settings.json","/etc/claude-code/managed-settings.json","/Library/Application Support/ClaudeCode/managed-settings.json"]},codex:{label:"Codex",vendor:"OpenAI",hosts:["api.openai.com","chatgpt.com"],repoint:"limited",how:"OPENAI_BASE_URL, or a model_provider in ~/.codex/config.toml pointing at an OpenAI-compatible endpoint",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud",ownSandbox:"computer use (controlling the browser and other apps)",session:{resume:["resume","{id}"],off:["--ephemeral"]}},antigravity:{label:"Antigravity",vendor:"Google",hosts:["*.googleapis.com"],repoint:"no",how:"",dirs:null,defaultModel:"cloud"},kiro:{label:"Kiro",vendor:"AWS",hosts:["*.amazonaws.com"],repoint:"no",how:"",dirs:null,defaultModel:"cloud"},copilot:{label:"GitHub Copilot",vendor:"GitHub",hosts:["api.githubcopilot.com","*.github.com"],repoint:"no",how:"",dirs:{flag:"--add-dir",repeat:!0},defaultModel:"cloud",session:{resume:["--session-id","{id}"],off:null,name:["--name","{name}"]}},deepseek:{label:"DeepSeek Harness",vendor:"DeepSeek",hosts:["api.deepseek.com"],repoint:"limited",how:"its base URL setting, to an OpenAI-compatible endpoint",dirs:null,defaultModel:"cloud"},opencode:{label:"OpenCode",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — any OpenAI-compatible endpoint, Ollama, LM Studio, or this gateway",dirs:null,defaultModel:"configurable",session:{resume:["--session","{id}"],off:null,name:["--title","{name}"]}},pi:{label:"Pi",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — any OpenAI-compatible endpoint, or this gateway",dirs:null,defaultModel:"configurable"},hermes:{label:"Hermes",vendor:null,hosts:[],repoint:"yes",how:"a provider in its config — a local model is a first-class choice",dirs:null,defaultModel:"configurable"}}),p=o=>String(o||"").toLowerCase().replace(/[^a-z]/g,""),d={claudecode:"claude",githubcopilot:"copilot",copilotcli:"copilot",deepseekharness:"deepseek",gemini:"antigravity",geminicli:"antigravity"};function s(o){const n=p(o);if(l[n])return{id:n,...l[n]};if(d[n])return{id:d[n],...l[d[n]]};const e=Object.entries(l).find(([i,t])=>n.includes(i)||n.includes(p(t.label)));return e?{id:e[0],...e[1]}:null}function m(o,{repointed:n=null}={}){const e=s(o);return e?n?{egress:"configurable",where:`a coding agent · model at ${n}`,note:`Re-pointed by you; ${e.how||"its own setting"}.`}:e.repoint==="yes"?{egress:"configurable",where:"a coding agent · model of your choosing",note:`Its model is a setting of its own — ${e.how}. Until you set one, whatever it defaults to.`}:e.repoint==="limited"?{egress:"internet",where:`a coding agent · model at ${e.vendor}`,note:`The conversation goes to ${e.vendor} with your own login. It can be re-pointed: ${e.how}.`}:{egress:"internet",where:`a coding agent · model at ${e.vendor}`,note:`The conversation goes to ${e.vendor} with your own login; this agent cannot be pointed elsewhere.`}:{egress:"internet",where:"a coding agent · its own model, elsewhere",note:"No card for this agent — assume its model is a vendor’s until you know otherwise."}}function u(o){if(o==null)return null;if(typeof o=="string")return u({flag:o,repeat:!0});if(typeof o!="object"||Array.isArray(o))throw new a("SHAPE","dirs: must be { flag, repeat } or { flag, separator }");const n=String(o.flag||"").trim();if(!/^--?[A-Za-z][\w-]*$/.test(n))throw new a("SHAPE",`dirs: not a flag: ${JSON.stringify(o.flag)}`);const e=o.separator==null?null:String(o.separator);if(e!=null&&(e.length===0||/\s/.test(e)))throw new a("SHAPE","dirs: separator must be a non-empty run of non-space characters");return e!=null?{flag:n,separator:e}:{flag:n,repeat:!0}}function h({harness:o,roots:n=[],dirs:e}={}){const i=(Array.isArray(n)?n:[]).map(r=>String(r||"").trim()).filter(Boolean);if(!i.length)return[];const t=u(e!==void 0?e:s(o)?.dirs??null);return t?t.separator?[t.flag,i.join(t.separator)]:i.flatMap(r=>[t.flag,r]):[]}function w(o,n){try{return!!u(n!==void 0?n:s(o)?.dirs??null)}catch{return!1}}const f=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;function A({harness:o,mode:n,id:e="",name:i=""}={}){const t=s(o)?.session;if(!t)return[];if(n==="off")return Array.isArray(t.off)?[...t.off]:[];if(n==="name"){const r=String(i??"").replace(/\s+/g," ").trim().slice(0,120);return!r||r.startsWith("-")||!Array.isArray(t.name)?[]:t.name.map(c=>c==="{name}"?r:c)}if(n!=="resume"||!Array.isArray(t.resume))return[];if(!f.test(String(e)))throw new a("SHAPE",`harness session: ${JSON.stringify(String(e).slice(0,40))} is not a session id`);return t.resume.map(r=>r==="{id}"?String(e):r)}const y=o=>Array.isArray(s(o)?.session?.resume);export{l as HARNESS_CARDS,s as harnessCard,h as harnessDirArgs,m as harnessEgress,y as harnessResumes,A as harnessSessionArgs,w as harnessTakesDirs,u as normalizeDirsSpec};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SANDBOX_RUNTIMES as A,SANDBOX_READ_MODES as $,parseWrapperTemplate as R}from"./sandbox-choice.js";class l extends Error{constructor(r){super(r),this.name="PolicyError"}}const O=1,z="policy",w=Object.freeze(["off","basic","full"]),k=Object.freeze({off:0,basic:1,full:2}),E=Object.freeze(["gateway","endpoints","redaction","features","agents"]),S=Object.freeze(["webllm","meetings","channels","agents"]),m=Object.freeze(["plan","default","acceptEdits","bypassPermissions"]),U=Object.freeze({plan:0,default:1,acceptEdits:2,bypassPermissions:3}),L=Object.freeze(["api.chatpanel.net","dl.chatpanel.net","huggingface.co","registry.npmjs.org","api.github.com"]),f=e=>typeof e=="string"?e.trim():"",c=e=>Array.isArray(e)?e.map(f).filter(Boolean):[];function b(e){const r=f(e).toLowerCase().replace(/^https?:\/\//,"").replace(/\/.*$/,"");if(!r)return"";if(!/^(\*\.)?[a-z0-9.-]+(:\d{1,5})?$/.test(r)&&!/^\[[0-9a-f:]+\](:\d{1,5})?$/.test(r)&&r!=="*")throw new l(`invalid host pattern "${e}"`);return r}function y(e){if(e==null)return y({});if(typeof e!="object"||Array.isArray(e))throw new l("policy must be an object");const r=e.v==null?O:Number(e.v);if(r!==O)throw new l(`unsupported policy version ${e.v}`);const n={v:r};if(e.org!=null){const t=f(e.org.id);if(!t||!/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(t))throw new l("org.id must be a short identifier");n.org={id:t,name:f(e.org.name)||t}}const o=(t,s)=>{if(t==null)return;if(typeof t!="object")throw new l(`${s} must be an object`);const u={};return t.allow!=null&&(u.allow=c(t.allow).map(b).filter(Boolean)),t.deny!=null&&(u.deny=c(t.deny).map(b).filter(Boolean)),u},a=o(e.endpoints,"endpoints");a&&(n.endpoints=a);const i=o(e.egress,"egress");if(i&&(n.egress=i),e.models!=null){if(typeof e.models!="object")throw new l("models must be an object");n.models={},e.models.allow!=null&&(n.models.allow=c(e.models.allow)),e.models.deny!=null&&(n.models.deny=c(e.models.deny))}if(e.agents!=null){if(typeof e.agents!="object")throw new l("agents must be an object");const t={};if(e.agents.allow!=null&&(t.allow=c(e.agents.allow).map(s=>s.toLowerCase())),e.agents.deny!=null&&(t.deny=c(e.agents.deny).map(s=>s.toLowerCase())),e.agents.permissionModeCap!=null){const s=f(e.agents.permissionModeCap);if(!m.includes(s))throw new l(`agents.permissionModeCap must be one of ${m.join(", ")}`);t.permissionModeCap=s}n.agents=t}if(e.routing!=null){if(typeof e.routing!="object")throw new l("routing must be an object");const t=Array.isArray(e.routing.rules)?e.routing.rules:[];n.routing={rules:t.map((s,u)=>{if(!s||typeof s!="object")throw new l(`routing.rules[${u}] must be an object`);const p=c(s.models),j=c(s.endpoints).map(b).filter(Boolean);if(!p.length)throw new l(`routing.rules[${u}] needs at least one model pattern`);if(!j.length)throw new l(`routing.rules[${u}] needs at least one endpoint`);return{models:p,endpoints:j}})}}if(e.redaction!=null){if(typeof e.redaction!="object")throw new l("redaction must be an object");const t={};if(e.redaction.floor!=null){const s=f(e.redaction.floor).toLowerCase();if(!w.includes(s))throw new l(`redaction.floor must be one of ${w.join(", ")}`);t.floor=s}e.redaction.dictionary!=null&&(t.dictionary=c(e.redaction.dictionary)),e.redaction.requireBeforeCloud!=null&&(t.requireBeforeCloud=!!e.redaction.requireBeforeCloud),n.redaction=t}if(e.client!=null){if(typeof e.client!="object")throw new l("client must be an object");const t={};if(e.client.gatewayUrl!=null){const s=f(e.client.gatewayUrl);if(s&&!/^https?:\/\/[^\s/]+(\/.*)?$/.test(s))throw new l("client.gatewayUrl must be an http(s) URL");t.gatewayUrl=s.replace(/\/+$/,"")}if(e.client.managedRequired!=null&&(t.managedRequired=!!e.client.managedRequired),e.client.lock!=null){const s=c(e.client.lock);for(const u of s)if(!E.includes(u))throw new l(`client.lock: unknown setting "${u}" (one of ${E.join(", ")})`);t.lock=[...new Set(s)]}if(e.client.features!=null){if(typeof e.client.features!="object")throw new l("client.features must be an object");t.features={};for(const[s,u]of Object.entries(e.client.features)){if(!S.includes(s))throw new l(`client.features: unknown feature "${s}" (one of ${S.join(", ")})`);t.features[s]=!!u}}n.client=t}if(e.sandbox!=null){if(typeof e.sandbox!="object"||Array.isArray(e.sandbox))throw new l("sandbox must be an object");const t={};if(e.sandbox.required!=null&&(t.required=!!e.sandbox.required),e.sandbox.runtime!=null){const s=f(e.sandbox.runtime);if(!A.includes(s))throw new l(`sandbox.runtime must be one of ${A.join(", ")}`);t.runtime=s}if(e.sandbox.command!=null)try{t.command=R(e.sandbox.command)}catch(s){throw new l(s.message)}if(e.sandbox.image!=null){const s=f(e.sandbox.image);if(!/^[A-Za-z0-9][A-Za-z0-9._\/:@-]{0,254}$/.test(s))throw new l("sandbox.image must be an image reference");t.image=s}if(e.sandbox.reads!=null){const s=f(e.sandbox.reads);if(!$.includes(s))throw new l(`sandbox.reads must be one of ${$.join(", ")}`);t.reads=s}if(e.sandbox.mode!=null){const s=f(e.sandbox.mode);if(!["open","allowlist"].includes(s))throw new l("sandbox.mode must be open or allowlist (an org that sandboxes agents itself sets runtime: managed)");t.mode=s}if(t.runtime==="command"&&!t.command)throw new l("sandbox.runtime command needs sandbox.command");if(t.runtime==="container"&&!t.image)throw new l("sandbox.runtime container needs sandbox.image");Object.keys(t).length&&(n.sandbox=t)}if(e.gateway!=null){if(typeof e.gateway!="object"||Array.isArray(e.gateway))throw new l("gateway must be an object");e.gateway.confined!=null&&(n.gateway={confined:!!e.gateway.confined})}if(e.access!=null){if(typeof e.access!="object"||Array.isArray(e.access))throw new l("access must be an object");const t={};if(e.access.delegation!=null){const s=f(e.access.delegation);if(!C.includes(s))throw new l(`access.delegation must be one of ${C.join(", ")}`);t.delegation=s}for(const s of["deny","allow"]){if(e.access[s]==null)continue;const u=c(e.access[s]).map(p=>String(p).trim()).filter(Boolean);for(const p of u)if(p.length>1024||p.includes("\0"))throw new l(`access.${s}: not a path`);t[s]=u}Object.keys(t).length&&(n.access=t)}return n}function I(e={},r=null){const n=r?.sandbox||{},o={...e},a=[];for(const i of["runtime","command","image","reads","mode"])n[i]!==void 0&&(o[i]=n[i],a.push(i));return n.required!==void 0&&(o.required=n.required?"policy":!1,a.push("required")),{sandbox:o,locked:a}}const C=Object.freeze(["allowed","never"]);function D(e){return e?.access?.delegation==="never"?"never":"allowed"}function d(e){const r=f(e).toLowerCase();if(!r)return{host:"",port:""};try{const n=new URL(/^[a-z][a-z0-9+.-]*:\/\//.test(r)?r:`http://${r}`);return{host:n.hostname.replace(/^\[|\]$/g,""),port:n.port||(n.protocol==="https:"?"443":n.protocol==="http:"?"80":"")}}catch{return{host:r.split(":")[0],port:""}}}function P(e,r,n){if(e==="*")return!0;const[o,a]=e.startsWith("[")?[e.replace(/^\[([^\]]+)\].*$/,"$1"),e.replace(/^\[[^\]]+\]:?/,"")]:(()=>{const i=e.lastIndexOf(":");return i>0?[e.slice(0,i),e.slice(i+1)]:[e,""]})();if(a&&a!==n)return!1;if(o.startsWith("*.")){const i=o.slice(1);return r.endsWith(i)&&r.length>i.length}return r===o}function g(e,r,n){return(e||[]).some(o=>P(o,r,n))}function h(e){return new RegExp(`^${String(e).split("*").map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*")}$`,"i")}function T(e,r){const n=e?.endpoints;if(!n)return!0;const{host:o,port:a}=d(r);return!o||g(n.deny,o,a)?!1:n.allow&&n.allow.length?g(n.allow,o,a):!0}function M(e,r){const n=e?.models;if(!n)return!0;const o=f(r);return(n.deny||[]).some(a=>h(a).test(o))?!1:n.allow&&n.allow.length?n.allow.some(a=>h(a).test(o)):!0}function _(e,r){const n=e?.agents;if(!n)return!0;const o=f(r).toLowerCase();return(n.deny||[]).includes(o)?!1:n.allow&&n.allow.length?n.allow.includes(o):!0}function v(e,r){const n=e?.agents?.permissionModeCap,o=m.includes(r)?r:"default";return n?U[o]<=U[n]?o:n:o}function H(e,{model:r="",endpoint:n=""}={}){if(!e)return{ok:!0,reason:""};if(r&&!M(e,r))return{ok:!1,reason:`model "${r}" is not allowed by your organisation's policy`};if(n&&!T(e,n))return{ok:!1,reason:`endpoint ${d(n).host} is not allowed by your organisation's policy`};const o=e.routing?.rules||[];if(r&&n&&o.length){const a=o.find(i=>i.models.some(t=>h(t).test(r)));if(a){const{host:i,port:t}=d(n);if(!g(a.endpoints,i,t))return{ok:!1,reason:`model "${r}" may only be sent to ${a.endpoints.join(", ")} under your organisation's policy`}}}return{ok:!0,reason:""}}function q(e,r){const n=e?.redaction?.floor,o=w.includes(r)?r:"basic";return n?k[o]>=k[n]?o:n:o}function W(e,r,{local:n=!1}={}){const o=e?.egress;if(!o)return!0;const{host:a,port:i}=d(r);return!a||g(o.deny,a,i)?!1:n||L.includes(a)||e.endpoints?.allow?.length&&g(e.endpoints.allow,a,i)&&!g(e.endpoints?.deny,a,i)?!0:g(o.allow,a,i)}function K(e,r){return!!e?.client?.lock?.includes(r)}function N(e,r){const n=e?.client?.features;return!n||n[r]==null?!0:!!n[r]}function Y(e,r){const n={...r||{}},o=[];if(!e)return{settings:n,changed:o};const a=e.client||{};if(a.gatewayUrl&&n.gatewayUrl!==a.gatewayUrl&&(n.gatewayUrl=a.gatewayUrl,o.push("gatewayUrl")),Array.isArray(n.endpoints)&&e.endpoints){const i=n.endpoints.filter(t=>!t||typeof t!="object"?!1:!t.baseUrl||a.gatewayUrl&&d(t.baseUrl).host===d(a.gatewayUrl).host&&d(t.baseUrl).port===d(a.gatewayUrl).port?!0:T(e,t.baseUrl));i.length!==n.endpoints.length&&(n.endpoints=i,o.push("endpoints"))}if(Array.isArray(n.endpoints)&&e.agents){const i=n.endpoints.filter(t=>t?.kind!=="bridge"||_(e,t.bridgeAgent||t.agent||t.id));i.length!==n.endpoints.length&&(n.endpoints=i,o.push("agents"))}if(Array.isArray(n.endpoints)&&!N(e,"webllm")){const i=n.endpoints.filter(t=>t?.kind!=="webllm");i.length!==n.endpoints.length&&(n.endpoints=i,o.push("webllm"))}if(e.redaction?.floor&&(n.redaction?.tier!=null||n.redactionTier!=null)){const i=n.redaction?.tier!=null?n.redaction.tier:n.redactionTier,t=q(e,i);t!==i&&(n.redaction?.tier!=null?n.redaction={...n.redaction,tier:t}:n.redactionTier=t,o.push("redaction"))}return{settings:n,changed:o}}function J(e){const r=e?.org?.name||e?.org?.id;return r?`Managed by ${r}`:"Managed"}function x(e){return Array.isArray(e)?`[${e.map(x).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${x(e[r])}`).join(",")}}`:JSON.stringify(e)}async function X(e,{subtle:r=null}={}){const n=r||globalThis.crypto?.subtle;if(!n)throw new l("no WebCrypto available on this runtime");const o=new TextEncoder().encode(x(y(e))),a=await n.digest("SHA-256",o);return[...new Uint8Array(a)].map(i=>i.toString(16).padStart(2,"0")).join("")}async function Z(e,{verify:r,...n}={}){if(typeof r!="function")throw new l("verifyPolicyToken needs a verify function (entitlement.js verifySignedToken)");const o=await r(e,{...n,typ:z});if(!o||!o.policy)return null;try{return y(o.policy)}catch{return null}}export{C as ACCESS_DELEGATION,S as FEATURES,E as LOCKABLE,m as PERMISSION_MODES,z as POLICY_TOKEN_TYPE,O as POLICY_VERSION,L as PRODUCT_HOSTS,l as PolicyError,w as REDACTION_TIERS,D as accessDelegation,_ as agentAllowed,Y as applyPolicyToSettings,W as egressAllowed,T as endpointAllowed,N as featureEnabled,h as globToRegExp,M as modelAllowed,y as normalizeOrgPolicy,v as permissionMode,X as policyHash,J as policyLabel,q as redactionTier,H as routeAllowed,I as sandboxUnderPolicy,K as settingLocked,Z as verifyPolicyToken};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function r({bunMain:t="",versions:e={},execPath:i=""}={}){if(e.electron)return!1;const n=String(t||"");if(n)return n.startsWith("/$bunfs/")||/^[A-Za-z]:[\\/]~BUN[\\/]/.test(n);const s=String(i||"").split(/[\\/]/).pop().toLowerCase();return e.bun?!1:!(s.startsWith("node")||s.startsWith("bun"))}function o(){const t=globalThis.process;return{bunMain:typeof globalThis.Bun<"u"?String(globalThis.Bun.main||""):"",versions:t?.versions||{},execPath:t?.execPath||""}}export{o as hostFacts,r as isCompiledBinary};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=(o,e)=>{if(!o)throw Object.assign(new Error(e),{code:"SHAPE"})},c=Object.freeze(["enumerated","inverted"]),h=Object.freeze(["srt","container","command","managed"]);function u(o){const e=Array.isArray(o)?null:String(o??"").trim();let n;if(Array.isArray(o))n=o.map(String);else if(e.startsWith("[")){try{n=JSON.parse(e)}catch{r(!1,"sandbox command: not a JSON array")}r(Array.isArray(n)&&n.every(t=>typeof t=="string"),"sandbox command: a JSON array of strings")}else n=e.split(/\s+/).filter(Boolean);return r(n.length>0&&n.length<=128,"sandbox command: 1–128 words"),r(n.every(t=>t.length<=1024&&!t.includes("\0")),"sandbox command: a word too long or with a NUL"),r(!n[0].includes("{"),"sandbox command: the first word is the wrapper program, not a placeholder"),r(n.filter(t=>t==="{cmd}").length===1,"sandbox command: exactly one {cmd} word, where the command goes"),n}function m(o,{bin:e,argv:n=[],workdir:t="",home:i="",hosts:d=[],mode:a=""}={}){const l=s=>s.replaceAll("{workdir}",t).replaceAll("{home}",i).replaceAll("{hosts}",d.join(",")).replaceAll("{mode}",a);return o.flatMap(s=>s==="{cmd}"?[e,...n]:[l(s)])}function p(o){if(!o?.ok)return{cls:"off",text:"The local runtime (bridge) is not running — nothing is sandboxed because nothing is running."};const e=o.sandbox;if(!e)return{cls:"warn",text:`This bridge (v${o.version||"?"}) predates the sandbox — update the gateway.`};const n=e.required==="policy"?" Your organisation requires it: anything it cannot be applied to is refused, and nothing runs outside it.":e.required?" Required: anything it cannot be applied to is refused rather than run as you.":"";if(e.enabled===!1)return e.required?{cls:"bad",text:`The sandbox is required but switched off, so nothing runs.${n}`}:{cls:"warn",text:"Sandbox off — agents, MCP servers and workers run as you, with your files and your network."};if(!e.runtime){const a=`${e.reason||"no runtime"}${e.install?` (${e.install})`:""}`;return e.required?{cls:"bad",text:`Nothing runs — the sandbox is required and cannot be applied here: ${a}.`}:{cls:"warn",text:`Not sandboxed — ${a}`}}const t=String(e.runtime);if(t==="managed")return{cls:"ok",text:`Managed by your organisation — your agents run inside its sandbox, so ChatPanel does not add one of its own.${n}`};if(t.startsWith("command:"))return{cls:"ok",text:`Sandboxed by your own command (${t.slice(8)}) — it decides what each process may touch; ChatPanel hands it the working folder and the hosts each one is allowed.${n}`};if(t.startsWith("container:"))return{cls:"ok",text:`Sandboxed in containers (${t.slice(10)}) — each process sees only its working folder, with no capabilities${e.mode==="none"?" and no network":""}.${n}`};const i=e.mode==="allowlist"?"only its own service, the developer hosts and what you allow":e.mode==="none"?"nothing":"any public host through the sandbox proxy — never your machine, your network or a cloud metadata address",d=e.mode==="allowlist"?e.ownSessions?" A process granted hosts of its own gets a session of its own.":" Hosts granted on a card need a session of their own, which is not available here, so they share the allow list.":"";return{cls:"ok",text:`Sandboxed (${t}, ${e.platform||""}): the working directory writable, your secrets unreadable, the network ${i}.${d}${n}`}}export{c as SANDBOX_READ_MODES,h as SANDBOX_RUNTIMES,m as expandWrapper,u as parseWrapperTemplate,p as sandboxStatus};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventError as
|
|
1
|
+
import{EventError as p}from"./event.js";const c=t=>!!t&&typeof t=="object"&&!Array.isArray(t),n=t=>[...new Set(t)],i=(t,s)=>{if(!t)throw new p("SHAPE",s)},l=/^(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d{1,5})?$/i,u=Object.freeze({aws:"AWS",oci:"Oracle Cloud",gcloud:"Google Cloud",azure:"Azure"}),a=Object.freeze(Object.keys(u));function y(t){return n(String(t||"").split(/[\s,;]+/).map(s=>s.trim().toLowerCase()).filter(Boolean))}function f(t){if(t==null)return{hosts:[],write:[]};i(c(t),"grant: must be an object");const s=Array.isArray(t.hosts)?t.hosts:typeof t.hosts=="string"?y(t.hosts):[],o=Array.isArray(t.write)?t.write:typeof t.write=="string"?t.write.split(/[\n,]+/).map(e=>e.trim()).filter(Boolean):[];for(const e of s)i(typeof e=="string"&&e!=="*"&&l.test(e),`grant: not a host pattern: ${JSON.stringify(e)}`);for(const e of o)i(typeof e=="string"&&e.length>0&&e.length<1024&&!e.includes("\0"),`grant: not a path: ${JSON.stringify(e)}`);const r=(Array.isArray(t.signIn)?t.signIn:typeof t.signIn=="string"?t.signIn.split(/[\s,;]+/):[]).map(e=>typeof e=="string"?e.trim().toLowerCase():e).filter(e=>e!=="");for(const e of r)i(a.includes(e),`grant: not a sign-in (${a.join(", ")}): ${JSON.stringify(e)}`);return{hosts:n(s.map(e=>e.toLowerCase())),write:n(o),...t.outside===!0?{outside:!0}:{},...r.length?{signIn:n(r)}:{}}}function h(...t){const s=t.map(f);return{hosts:n(s.flatMap(o=>o.hosts)),write:n(s.flatMap(o=>o.write))}}function w(...t){const s=t.map(f),o=n(s.flatMap(r=>r.signIn||[]));return{...h(...s),...s.some(r=>r.outside)?{outside:!0}:{},...o.length?{signIn:o}:{}}}export{u as SIGN_IN_LABELS,a as SIGN_IN_NAMES,h as mergeGrants,w as mergePersonGrants,f as normalizeGrant,y as parseHostList};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EventError as L}from"./event.js";import{normalizeGrant as S}from"./sandbox-grant.js";import{SECRET_DIR_NAMES as P,SECRET_DIR_PAIRS as v}from"./secret-names.js";const R=Object.freeze(["none","process","container","kubernetes"]),$=Object.freeze(["open","allowlist","none","gateway"]),_=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),g=e=>{let t=String(e||"").trim();for(;t.length>1&&(t.endsWith("/")||t.endsWith("\\"));)t=t.slice(0,-1);return t},x=(e,t)=>t&&(e==="~"||e.startsWith("~/")||e.startsWith("~\\"))?t+e.slice(1):e,m=e=>String(e||"").replace(/\\/g,"/"),b=(e,t)=>{const n=m(g(e)),r=m(g(t));return!!n&&!!r&&(n===r||n.startsWith(`${r}/`))},N=_.map(e=>m(g(e)).replace(/^~\//,"").split("/").filter(Boolean));function I(e,t=""){const n=m(g(x(g(e),t)));if(!n)return!1;for(const o of _)if(b(n,o)||t&&b(n,x(o,t)))return!0;const r=n.split("/").filter(Boolean).map(o=>o.toLowerCase());return N.some(o=>{for(let s=0;s+o.length<=r.length;s+=1)if(o.every((a,l)=>a.toLowerCase()===r[s+l]))return!0;return!1})}const W=Object.freeze([...[...P].map(e=>`~/**/${e}`),...v.map(([e,t])=>`~/**/${e}/${t}`),...[".env",".netrc","_netrc",".git-credentials",".pgpass",".my.cnf",".npmrc",".pypirc",".htpasswd",".terraformrc",".vault-token","credentials","credentials.toml","id_rsa","id_dsa","id_ecdsa","id_ed25519","*.pem","*.p12","*.pfx","*.jks","*.keystore","*.kdbx","*.ppk"].map(e=>`~/**/${e}`)]);function ee(e,{home:t="",globs:n=[..._,...W]}={}){const r=m(g(x(g(e),t)));if(!r)return null;const o=r.split("/").filter(Boolean),s=m(g(t));for(const a of n){const l=m(g(a));if(l){if(l.startsWith("~/**/")){if(s&&!b(r,s))continue;const c=l.slice(5).split("/").filter(Boolean).map(z);for(let i=0;i+c.length<=o.length;i+=1)if(c.every((d,u)=>d.test(o[i+u])))return a;continue}if(b(r,x(l,t)))return a}}return null}function z(e){return new RegExp(`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*")}$`,"i")}const D=".cache/chatpanel/ca-bundle.crt",te=".cache/chatpanel/ca-bundle.pem";function ne(e=""){const t=m(g(e));return t?`${t}/${D}`:`~/${D}`}const H=Object.freeze(["~/.npm","~/.cache","~/.local","~/Library/Caches","~/.nvm","~/.volta","~/.asdf","~/.nodenv","~/.bun","~/.deno","~/.pyenv","~/.rye","~/.pdm","~/.cargo","~/.rustup","~/go","~/.goenv","~/.m2","~/.gradle","~/.sdkman","~/.jenv","~/.gem","~/.rbenv","~/.bundle","~/.composer","~/.nuget","~/.dotnet","~/.stack","~/.ghcup","~/.opam","~/.pub-cache","~/.gitconfig","~/.config/git"]),k=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),C=Object.freeze({codex:Object.freeze({hosts:["api.openai.com","chatgpt.com","auth.openai.com","*.openai.com"],write:["~/.codex"]}),claude:Object.freeze({hosts:["api.anthropic.com","*.anthropic.com","claude.ai","statsig.anthropic.com"],write:["~/.claude","~/.claude.json"],keychain:!0,sockets:["/tmp/cc-socks","/private/tmp/cc-socks"]}),antigravity:Object.freeze({hosts:["*.googleapis.com","*.google.com","oauth2.googleapis.com"],write:["~/.gemini","~/.antigravity","~/.config/antigravity"]}),custom:Object.freeze({hosts:[],write:[]}),mcp:Object.freeze({hosts:[],write:[]}),extract:Object.freeze({hosts:[],write:[]}),"model-server":Object.freeze({hosts:["huggingface.co","*.huggingface.co","*.hf.co","cdn-lfs.huggingface.co","cas-bridge.xethub.hf.co","dl.chatpanel.net"],write:[]})}),T="~/Library/Keychains",K=/(^|\/)Keychains\/?$/,Y=Object.freeze(["github.com","*.github.com","*.githubusercontent.com","gitlab.com","bitbucket.org","registry.npmjs.org","pypi.org","files.pythonhosted.org","crates.io","static.crates.io","proxy.golang.org","sum.golang.org","huggingface.co","*.huggingface.co"]),h=e=>!!e&&typeof e=="object"&&!Array.isArray(e),y=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0),f=(e,t)=>{if(!e)throw new L("SHAPE",t)},p=e=>[...new Set(e)];function j(e){f(h(e),"kit: must be an object"),f(typeof e.id=="string"&&e.id.length>0,"kit: id required"),f(h(e.network)&&$.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${$.join(", ")}`),f(y(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),f(y(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),f(h(e.filesystem),`kit ${e.id}: filesystem required`);for(const t of["allowWrite","denyWrite","allowRead","denyRead"])f(y(e.filesystem[t]||[]),`kit ${e.id}: filesystem.${t} must be string[]`);return f(y(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),f(y(e.network.unixSockets||[])&&(e.network.unixSockets||[]).every(t=>t.startsWith("/")&&t.replace(/\/+$/,"")!==""),`kit ${e.id}: network.unixSockets must be absolute folders, never /`),e.image!=null&&f(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&f(Array.isArray(e.credentials)&&e.credentials.every(t=>h(t)&&typeof t.name=="string"&&typeof t.forHost=="string"),`kit ${e.id}: credentials must be [{ name, forHost }]`),{id:e.id,kind:e.kind||"process",image:e.image||null,network:{mode:e.network.mode,allowedDomains:p(e.network.allowedDomains||[]),deniedDomains:p(e.network.deniedDomains||[]),...(e.network.unixSockets||[]).length?{unixSockets:p(e.network.unixSockets)}:{}},filesystem:{allowWrite:p(e.filesystem.allowWrite),denyWrite:p(e.filesystem.denyWrite||[]),allowRead:p(e.filesystem.allowRead||[]),denyRead:p(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:h(e.limits)?{...e.limits}:{}}}import{normalizeGrant as ge,mergeGrants as me,parseHostList as we}from"./sandbox-grant.js";const U=e=>String(e).replace(/([\\/])\*$/,"$1**");function oe({engine:e="custom",cwd:t,mode:n="open",extraHosts:r=[],extraWrite:o=[],extraDenyRead:s=[],grant:a=null,home:l="",reads:c="enumerated",readOnly:i=!1,peers:d=!0}={}){const u=C[e]||C.custom;f(typeof t=="string"&&t.length>0,"kit: cwd required");const O=S(a);return j({id:`${e}:${n}`,kind:"process",network:{mode:n,allowedDomains:n==="open"?["*"]:n==="none"?[]:p([...u.hosts,...Y,...r,...O.hosts]),deniedDomains:[],unixSockets:d?[...u.sockets||[]]:[]},filesystem:{allowWrite:p(i?[...k,...u.write]:[t,...k,...u.write,...[...o,...O.write].filter(A=>!I(A,l)).map(U)]),denyWrite:[],allowRead:c==="inverted"?p([t,...H,...u.write,...u.keychain?[T]:[],...G({grant:O,extraWrite:o,cwd:t,home:l})]):[t],denyRead:p([...c==="inverted"?["~",...l?[l]:[]]:[],...[..._,...W].filter(A=>!(u.keychain&&K.test(A))),...s])}})}function B(e){if(!/[*?[{]/.test(e))return e;const t=e.split(/[\\/]/),n=t.findIndex(s=>/[*?[{]/.test(s)),r=e.includes("\\")&&!e.includes("/")?"\\":"/",o=t.slice(0,n).join(r);return o&&o!=="~"?o:""}function G({grant:e=null,extraWrite:t=[],cwd:n="",home:r=""}={}){const o=i=>r&&(i==="~"||i.startsWith("~/")||i.startsWith("~\\"))?r+i.slice(1):i,s=i=>{let d=String(i||"").trim();for(;d.length>1&&(d.endsWith("/")||d.endsWith("\\"));)d=d.slice(0,-1);return d},a=(i,d)=>i===d||i.startsWith(`${d}/`)||i.startsWith(`${d}\\`),l=s(o(n)),c=[];for(const i of[...S(e).write,...Array.isArray(t)?t:[]]){const d=B(s(o(s(i))));if(d&&!I(d,r)&&!(l&&a(d,l))&&!c.some(u=>a(d,u))){for(let u=c.length-1;u>=0;u--)a(c[u],d)&&c.splice(u,1);c.push(d)}}return c}function re(e,{loopback:t=[],home:n="",platform:r="darwin"}={}){const o=j(e),s=l=>n&&l.startsWith("~")?n+l.slice(1):l,a=o.network.mode==="none"?[]:t.map(l=>`127.0.0.1:${l}`);return{network:{allowedDomains:p([...o.network.allowedDomains,...a]),deniedDomains:o.network.deniedDomains,allowLocalBinding:r==="darwin"&&a.length>0,...r==="darwin"&&o.network.unixSockets?.length?{allowUnixSockets:o.network.unixSockets}:{}},filesystem:{denyRead:o.filesystem.denyRead.map(s),allowRead:o.filesystem.allowRead.map(s),allowWrite:o.filesystem.allowWrite.map(s),denyWrite:o.filesystem.denyWrite.map(s)}}}function se({layer:e="none",runtime:t=null,kitId:n=null,mode:r=null,reason:o=null,hosts:s=null}={}){return f(R.includes(e),`sandbox record: layer must be one of ${R.join(", ")}`),{layer:e,runtime:t,kit:n,mode:r,...e==="none"&&o?{reason:o}:{},...Array.isArray(s)&&s.length?{hosts:p(s)}:{}}}function M(e,{platform:t="darwin"}={}){const n=String(e);if(t==="win32"){f(!/[\r\n]/.test(n),"win32 command line: an argument holds a newline, which cmd.exe cannot carry");let r=n;if(n===""||/[ \t\v"]/.test(n)){r='"';for(let o=0;o<n.length;o++){let s=0;for(;o<n.length&&n[o]==="\\";)s++,o++;if(o===n.length){r+="\\".repeat(s*2);break}n[o]==='"'?r+="\\".repeat(s*2+1)+'"':r+="\\".repeat(s)+n[o]}r+='"'}return r.replace(/[()%!^"<>&|]/g,"^$&")}return n===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}const q=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function ie(e={},{platform:t="darwin",caBundle:n=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(n)for(const o of q)e[o]||(r[o]=n);if(t==="linux")for(const o of["no_proxy","NO_PROXY"])typeof e[o]=="string"&&(r[o]=e[o].split(",").map(s=>s.trim()).filter(s=>s&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(s)).join(","));return r}function ce(e,t=[],{platform:n="darwin"}={}){return[e,...t].map(r=>M(r,{platform:n})).join(" ")}const ae=/[\\/]+/,w=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),F=e=>/^[a-z]:$/i.test(w(e))||w(e)==="";function E(e,t){const n=w(e),r=w(t);return!!r&&n!==r&&n.startsWith(r+"\\")}function X(e){const t=String(e||"").replace(/\//g,"\\").split("\\");if(t.length<2)return"";const n=t.findIndex(r=>r.toLowerCase()==="node_modules");return(n>0?t.slice(0,n):t.slice(0,-1)).join("\\")}function le({kit:e,files:t=[],home:n}){f(typeof n=="string"&&n.length>0,"windows grants: home required");const r=c=>(c.startsWith("~")?n+c.slice(1):c).replace(/\//g,"\\"),o=[];for(const c of e?.filesystem?.allowWrite||[]){const i=r(c);!/^[a-z]:\\/i.test(i)&&!i.startsWith("\\\\")||(f(!F(i)&&w(i)!==w(n),`windows grants: a write on ${i} would hand the sandbox account the whole profile`),E(i,n)&&o.push(i))}const s=(c,i)=>i.some(d=>w(c)===w(d)||E(c,d)),a=[];for(const c of t){const i=X(c);i&&E(i,n)&&a.push(i)}for(const c of e?.filesystem?.allowRead||[]){const i=r(c);E(i,n)&&a.push(i)}const l=p(a).filter(c=>!s(c,o));return{read:l.filter(c=>!l.some(i=>i!==c&&E(c,i))),write:p(o)}}const V=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","CLAUDE_CONFIG_DIR","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","CODEX_HOME","GEMINI_API_KEY","GOOGLE_API_KEY","DEEPSEEK_API_KEY","DSH_HOME","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"]);function de({engine:e="custom",home:t,env:n={},base:r={},carry:o=V}={}){f(typeof t=="string"&&t.length>0,"windows env: home required");const s=t.replace(/\//g,"\\"),a=/^[a-z]:/i.test(s)?s.slice(0,2):"",l={USERPROFILE:s,...a?{HOMEDRIVE:a,HOMEPATH:s.slice(2)}:{}};for(const[c,i]of Object.entries(n))typeof i=="string"&&(r[c]!==i||o.includes(c))&&(l[c]=i);return e==="codex"&&!l.CODEX_HOME&&(l.CODEX_HOME=s+"\\.codex"),l}function fe(e,t){f(Array.isArray(e),"srt-win argv: must be an array");const n=e.indexOf("exec"),r=n>=0?e.indexOf("--",n+1):-1;f(n>=0&&r>n,"srt-win argv: expected `exec … -- <shell> <command>`");const o=new Set;for(let a=n+1;a<r;a++)e[a]==="--env"&&typeof e[a+1]=="string"&&o.add(e[a+1].split("=")[0].toUpperCase());const s=[];for(const[a,l]of Object.entries(t||{}))f(/^[A-Za-z_][A-Za-z0-9_]*$/.test(a),`srt-win env: bad key ${a}`),f(!/[\r\n]/.test(l),`srt-win env: ${a} holds a newline`),o.has(a.toUpperCase())||s.push("--env",`${a}=${l}`);return[...e.slice(0,r),...s,...e.slice(r)]}export{D as CA_BUNDLE_RELPATH,te as CA_BUNDLE_RELPATH_LEGACY,k as COMMON_WRITE,Y as DEVELOPER_HOSTS,C as ENGINE_KITS,$ as NETWORK_MODES,R as SANDBOX_LAYERS,_ as SECRET_PATHS,W as SECRET_READ_GLOBS,H as TOOLCHAIN_READ,V as WINDOWS_CARRY_KEYS,ne as caBundlePath,I as isSecretWritePath,oe as kitFor,me as mergeGrants,ge as normalizeGrant,we as parseHostList,ee as readDenialFor,ie as sandboxEnvOverlay,se as sandboxRecord,ce as shellJoin,M as shellQuote,re as toSrtSettings,E as underWindowsHome,j as validateKit,le as windowsGrantsFor,X as windowsInstallRoot,de as windowsSandboxEnv,fe as withSrtWinEnv,G as writableRoots};
|
|
1
|
+
import{EventError as L}from"./event.js";import{normalizeGrant as y,SIGN_IN_NAMES as P,SIGN_IN_LABELS as x}from"./sandbox-grant.js";import{SECRET_DIR_NAMES as T,SECRET_DIR_PAIRS as H}from"./secret-names.js";const k=Object.freeze(["none","process","container","kubernetes","external"]),N=Object.freeze(["open","allowlist","none","gateway"]),S=Object.freeze(["~/.chatpanel","~/.ssh","~/.gnupg","~/.aws","~/.azure","~/.config/gcloud","~/.kube","~/.netrc","~/.docker/config.json","~/.npmrc","~/.pypirc"]),g=e=>{let t=String(e||"").trim();for(;t.length>1&&(t.endsWith("/")||t.endsWith("\\"));)t=t.slice(0,-1);return t},O=(e,t)=>t&&(e==="~"||e.startsWith("~/")||e.startsWith("~\\"))?t+e.slice(1):e,m=e=>String(e||"").replace(/\\/g,"/"),A=(e,t)=>{const n=m(g(e)),r=m(g(t));return!!n&&!!r&&(n===r||n.startsWith(`${r}/`))},G=S.map(e=>m(g(e)).replace(/^~\//,"").split("/").filter(Boolean));function W(e,t=""){const n=m(g(O(g(e),t)));if(!n)return!1;for(const o of S)if(A(n,o)||t&&A(n,O(o,t)))return!0;const r=n.split("/").filter(Boolean).map(o=>o.toLowerCase());return G.some(o=>{for(let s=0;s+o.length<=r.length;s+=1)if(o.every((l,c)=>l.toLowerCase()===r[s+c]))return!0;return!1})}const j=Object.freeze([...[...T].map(e=>`~/**/${e}`),...H.map(([e,t])=>`~/**/${e}/${t}`),...[".env",".netrc","_netrc",".git-credentials",".pgpass",".my.cnf",".npmrc",".pypirc",".htpasswd",".terraformrc",".vault-token","credentials","credentials.toml","id_rsa","id_dsa","id_ecdsa","id_ed25519","*.pem","*.p12","*.pfx","*.jks","*.keystore","*.kdbx","*.ppk"].map(e=>`~/**/${e}`)]);function ae(e,{home:t="",globs:n=[...S,...j]}={}){const r=m(g(O(g(e),t)));if(!r)return null;const o=r.split("/").filter(Boolean),s=m(g(t));for(const l of n){const c=m(g(l));if(c){if(c.startsWith("~/**/")){if(s&&!A(r,s))continue;const a=c.slice(5).split("/").filter(Boolean).map(K);for(let i=0;i+a.length<=o.length;i+=1)if(a.every((d,u)=>d.test(o[i+u])))return l;continue}if(A(r,O(c,t)))return l}}return null}function K(e){return new RegExp(`^${e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*")}$`,"i")}const C=".cache/chatpanel/ca-bundle.crt",ce=".cache/chatpanel/ca-bundle.pem";function le(e=""){const t=m(g(e));return t?`${t}/${C}`:`~/${C}`}const B=Object.freeze(["~/.npm","~/.cache","~/.local","~/Library/Caches","~/.nvm","~/.volta","~/.asdf","~/.nodenv","~/.bun","~/.deno","~/.pyenv","~/.rye","~/.pdm","~/.cargo","~/.rustup","~/go","~/.goenv","~/.m2","~/.gradle","~/.sdkman","~/.jenv","~/.gem","~/.rbenv","~/.bundle","~/.composer","~/.nuget","~/.dotnet","~/.stack","~/.ghcup","~/.opam","~/.pub-cache","~/.gitconfig","~/.config/git"]),z=Object.freeze(["/tmp","/private/tmp","~/.cache","~/.npm","~/.local/share/uv","~/.local/state"]),v=Object.freeze({codex:Object.freeze({hosts:["api.openai.com","chatgpt.com","auth.openai.com","*.openai.com"],write:["~/.codex"]}),claude:Object.freeze({hosts:["api.anthropic.com","*.anthropic.com","claude.ai","statsig.anthropic.com"],write:["~/.claude","~/.claude.json"],keychain:!0,sockets:["/tmp/cc-socks","/private/tmp/cc-socks"]}),antigravity:Object.freeze({hosts:["*.googleapis.com","*.google.com","oauth2.googleapis.com"],write:["~/.gemini","~/.antigravity","~/.config/antigravity"]}),custom:Object.freeze({hosts:[],write:[]}),mcp:Object.freeze({hosts:[],write:[]}),extract:Object.freeze({hosts:[],write:[]}),"model-server":Object.freeze({hosts:["huggingface.co","*.huggingface.co","*.hf.co","cdn-lfs.huggingface.co","cas-bridge.xethub.hf.co","dl.chatpanel.net"],write:[]})}),M="~/Library/Keychains",U=/(^|\/)Keychains\/?$/,I=Object.freeze({aws:Object.freeze({label:x.aws,where:"~/.aws",read:["~/.aws","~/.aws/credentials","~/.aws/sso"],hosts:["*.amazonaws.com","*.api.aws"],failure:/could not load (aws )?credentials|unable to locate credentials|CredentialsProviderError|NoCredentialProviders|failed to refresh cached credentials|aws credentials? (not found|could not be)/i}),oci:Object.freeze({label:x.oci,where:"~/.oci",read:["~/.oci","~/.oci/**/*.pem"],hosts:["*.oraclecloud.com"],failure:/could not find config file at .*\.oci|ConfigFileNotFound|oci config(uration)? (file )?(was )?not found|\.oci[\\/]config.*(not found|no such file|not permitted|permission denied)/i}),gcloud:Object.freeze({label:x.gcloud,where:"~/.config/gcloud",read:["~/.config/gcloud"],hosts:["*.googleapis.com","accounts.google.com"],failure:/could not load the default credentials|DefaultCredentialsError|could not (automatically )?(find|determine) (default )?credentials|application default credentials (were|are) not (found|available)/i}),azure:Object.freeze({label:x.azure,where:"~/.azure",read:["~/.azure"],hosts:["*.azure.com","login.microsoftonline.com"],failure:/DefaultAzureCredential failed|CredentialUnavailableError|please run 'az login'|AzureCliCredential authentication (unavailable|failed)/i})});function D(e){return f((y(e).signIn||[]).flatMap(t=>I[t].read))}function Y(e){return f((y(e).signIn||[]).flatMap(t=>I[t].hosts))}function de(e,{grant:t=null,sandboxed:n=!0,agentLabel:r="This agent",agent:o=""}={}){if(!n)return null;let s=[];try{s=y(t).signIn||[]}catch{}const l=String(e||"");for(const c of P){const a=I[c];if(!(s.includes(c)||!a.failure.test(l)))return{store:c,line:`${r} could not sign in to ${a.label}: the ChatPanel sandbox keeps your ${a.label} sign-in (${a.where}) from every agent until you allow it. To allow it for this agent only, turn on ${a.label} under "May sign in with" in its Coding Agents settings${o?`, or run: chatpanel-gateway sandbox allow ${o} ${c}`:""}. Nothing else it is denied changes.`}}return null}const F=Object.freeze(["github.com","*.github.com","*.githubusercontent.com","gitlab.com","bitbucket.org","registry.npmjs.org","pypi.org","files.pythonhosted.org","crates.io","static.crates.io","proxy.golang.org","sum.golang.org","huggingface.co","*.huggingface.co"]),E=e=>!!e&&typeof e=="object"&&!Array.isArray(e),_=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"&&t.length>0),p=(e,t)=>{if(!e)throw new L("SHAPE",t)},f=e=>[...new Set(e)];function $(e){p(E(e),"kit: must be an object"),p(typeof e.id=="string"&&e.id.length>0,"kit: id required"),p(E(e.network)&&N.includes(e.network.mode),`kit ${e.id}: network.mode must be one of ${N.join(", ")}`),p(_(e.network.allowedDomains||[]),`kit ${e.id}: network.allowedDomains must be string[]`),p(_(e.network.deniedDomains||[]),`kit ${e.id}: network.deniedDomains must be string[]`),p(E(e.filesystem),`kit ${e.id}: filesystem required`);for(const t of["allowWrite","denyWrite","allowRead","denyRead"])p(_(e.filesystem[t]||[]),`kit ${e.id}: filesystem.${t} must be string[]`);return p(_(e.filesystem.allowWrite)&&e.filesystem.allowWrite.length>0,`kit ${e.id}: filesystem.allowWrite must name at least the working directory`),p(_(e.network.unixSockets||[])&&(e.network.unixSockets||[]).every(t=>t.startsWith("/")&&t.replace(/\/+$/,"")!==""),`kit ${e.id}: network.unixSockets must be absolute folders, never /`),e.image!=null&&p(typeof e.image=="string",`kit ${e.id}: image must be a string`),e.credentials!=null&&p(Array.isArray(e.credentials)&&e.credentials.every(t=>E(t)&&typeof t.name=="string"&&typeof t.forHost=="string"),`kit ${e.id}: credentials must be [{ name, forHost }]`),{id:e.id,kind:e.kind||"process",image:e.image||null,network:{mode:e.network.mode,allowedDomains:f(e.network.allowedDomains||[]),deniedDomains:f(e.network.deniedDomains||[]),...(e.network.unixSockets||[]).length?{unixSockets:f(e.network.unixSockets)}:{}},filesystem:{allowWrite:f(e.filesystem.allowWrite),denyWrite:f(e.filesystem.denyWrite||[]),allowRead:f(e.filesystem.allowRead||[]),denyRead:f(e.filesystem.denyRead||[])},credentials:e.credentials||[],limits:E(e.limits)?{...e.limits}:{}}}import{normalizeGrant as xe,mergeGrants as Se,mergePersonGrants as Oe,parseHostList as Ae,SIGN_IN_NAMES as Re,SIGN_IN_LABELS as Ie}from"./sandbox-grant.js";import{SANDBOX_READ_MODES as ke,SANDBOX_RUNTIMES as Ne,parseWrapperTemplate as We,expandWrapper as je}from"./sandbox-choice.js";const X=e=>String(e).replace(/([\\/])\*$/,"$1**");function q({engine:e="custom",cwd:t,mode:n="open",extraHosts:r=[],extraWrite:o=[],extraDenyRead:s=[],grant:l=null,home:c="",reads:a="enumerated",readOnly:i=!1,peers:d=!0}={}){const u=v[e]||v.custom;p(typeof t=="string"&&t.length>0,"kit: cwd required");const h=y(l);return $({id:`${e}:${n}`,kind:"process",network:{mode:n,allowedDomains:n==="open"?["*"]:n==="none"?[]:f([...u.hosts,...F,...r,...h.hosts,...Y(h)]),deniedDomains:[],unixSockets:d?[...u.sockets||[]]:[]},filesystem:{allowWrite:f(i?[...z,...u.write]:[t,...z,...u.write,...[...o,...h.write].filter(R=>!W(R,c)).map(X)]),denyWrite:[],allowRead:f(a==="inverted"?[t,...B,...u.write,...u.keychain?[M]:[],...Z({grant:h,extraWrite:o,cwd:t,home:c}),...D(h)]:[t,...D(h)]),denyRead:f([...a==="inverted"?["~",...c?[c]:[]]:[],...[...S,...j].filter(R=>!(u.keychain&&U.test(R))),...s])}})}const V=Object.freeze({noWrite:Object.freeze(["runtime/sandbox-runtime","runtime/ort","bin","node_modules","package.json","package-lock.json","git-hooks","policy.json","bridge-token","agent-threads.json","update-check.json","launch.vbs","workspace","worktrees","channels","desktop","cli","actions-runner","release.env"]),noRead:Object.freeze(["channels","desktop","cli","actions-runner","release.env","workspace","worktrees"])});function ue({stateDir:e,codeDirs:t=[],home:n="",mode:r="open",hosts:o=[],scratch:s=[],fence:l=V}={}){p(typeof e=="string"&&e.length>1,"gateway kit: stateDir required");const c=q({engine:"custom",cwd:e,mode:r,extraHosts:o,home:n,reads:"inverted",peers:!1}),a=u=>typeof u=="string"&&u.startsWith("/")&&u.replace(/\/+$/,"")!==""&&u!==n,i=t.filter(a),d=u=>`${e.replace(/\/+$/,"")}/${u}`;return $({...c,id:`gateway:${r}`,filesystem:{...c.filesystem,allowWrite:f([e,"/tmp","/private/tmp",...s.filter(a)]),denyWrite:f([...i,...l.noWrite.map(d)]),allowRead:f([...c.filesystem.allowRead,...i]),denyRead:f([...c.filesystem.denyRead,...l.noRead.map(d)])}})}function Q(e){if(!/[*?[{]/.test(e))return e;const t=e.split(/[\\/]/),n=t.findIndex(s=>/[*?[{]/.test(s)),r=e.includes("\\")&&!e.includes("/")?"\\":"/",o=t.slice(0,n).join(r);return o&&o!=="~"?o:""}function Z({grant:e=null,extraWrite:t=[],cwd:n="",home:r=""}={}){const o=i=>r&&(i==="~"||i.startsWith("~/")||i.startsWith("~\\"))?r+i.slice(1):i,s=i=>{let d=String(i||"").trim();for(;d.length>1&&(d.endsWith("/")||d.endsWith("\\"));)d=d.slice(0,-1);return d},l=(i,d)=>i===d||i.startsWith(`${d}/`)||i.startsWith(`${d}\\`),c=s(o(n)),a=[];for(const i of[...y(e).write,...Array.isArray(t)?t:[]]){const d=Q(s(o(s(i))));if(d&&!W(d,r)&&!(c&&l(d,c))&&!a.some(u=>l(d,u))){for(let u=a.length-1;u>=0;u--)l(a[u],d)&&a.splice(u,1);a.push(d)}}return a}function fe(e,{loopback:t=[],home:n="",platform:r="darwin"}={}){const o=$(e),s=c=>n&&c.startsWith("~")?n+c.slice(1):c,l=o.network.mode==="none"?[]:t.map(c=>`127.0.0.1:${c}`);return{network:{allowedDomains:f([...o.network.allowedDomains,...l]),deniedDomains:o.network.deniedDomains,allowLocalBinding:r==="darwin"&&l.length>0,...r==="darwin"&&o.network.unixSockets?.length?{allowUnixSockets:o.network.unixSockets}:{}},filesystem:{denyRead:o.filesystem.denyRead.map(s),allowRead:o.filesystem.allowRead.map(s),allowWrite:o.filesystem.allowWrite.map(s),denyWrite:o.filesystem.denyWrite.map(s)}}}function pe({layer:e="none",runtime:t=null,kitId:n=null,mode:r=null,reason:o=null,hosts:s=null}={}){return p(k.includes(e),`sandbox record: layer must be one of ${k.join(", ")}`),{layer:e,runtime:t,kit:n,mode:r,...e==="none"&&o?{reason:o}:{},...Array.isArray(s)&&s.length?{hosts:f(s)}:{}}}function J(e,{platform:t="darwin"}={}){const n=String(e);if(t==="win32"){p(!/[\r\n]/.test(n),"win32 command line: an argument holds a newline, which cmd.exe cannot carry");let r=n;if(n===""||/[ \t\v"]/.test(n)){r='"';for(let o=0;o<n.length;o++){let s=0;for(;o<n.length&&n[o]==="\\";)s++,o++;if(o===n.length){r+="\\".repeat(s*2);break}n[o]==='"'?r+="\\".repeat(s*2+1)+'"':r+="\\".repeat(s)+n[o]}r+='"'}return r.replace(/[()%!^"<>&|]/g,"^$&")}return n===""?"''":/^[A-Za-z0-9_\-./=:@%+,]+$/.test(n)?n:`'${n.replace(/'/g,"'\\''")}'`}const ee=Object.freeze(["SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"]);function ge(e={},{platform:t="darwin",caBundle:n=""}={}){const r={NODE_USE_ENV_PROXY:"1"};if(n)for(const o of ee)e[o]||(r[o]=n);if(t==="linux")for(const o of["no_proxy","NO_PROXY"])typeof e[o]=="string"&&(r[o]=e[o].split(",").map(s=>s.trim()).filter(s=>s&&!/^(localhost|127\.0\.0\.1|::1|\[::1\])$/i.test(s)).join(","));return r}function me(e,t=[],{platform:n="darwin"}={}){return[e,...t].map(r=>J(r,{platform:n})).join(" ")}const we=/[\\/]+/,w=e=>String(e||"").replace(/\//g,"\\").replace(/\\+$/,"").toLowerCase(),te=e=>/^[a-z]:$/i.test(w(e))||w(e)==="";function b(e,t){const n=w(e),r=w(t);return!!r&&n!==r&&n.startsWith(r+"\\")}function ne(e){const t=String(e||"").replace(/\//g,"\\").split("\\");if(t.length<2)return"";const n=t.findIndex(r=>r.toLowerCase()==="node_modules");return(n>0?t.slice(0,n):t.slice(0,-1)).join("\\")}function he({kit:e,files:t=[],home:n}){p(typeof n=="string"&&n.length>0,"windows grants: home required");const r=a=>(a.startsWith("~")?n+a.slice(1):a).replace(/\//g,"\\"),o=[];for(const a of e?.filesystem?.allowWrite||[]){const i=r(a);!/^[a-z]:\\/i.test(i)&&!i.startsWith("\\\\")||(p(!te(i)&&w(i)!==w(n),`windows grants: a write on ${i} would hand the sandbox account the whole profile`),b(i,n)&&o.push(i))}const s=(a,i)=>i.some(d=>w(a)===w(d)||b(a,d)),l=[];for(const a of t){const i=ne(a);i&&b(i,n)&&l.push(i)}for(const a of e?.filesystem?.allowRead||[]){if(/[*?[]/.test(a))continue;const i=r(a);b(i,n)&&l.push(i)}const c=f(l).filter(a=>!s(a,o));return{read:c.filter(a=>!c.some(i=>i!==a&&b(a,i))),write:f(o)}}const oe=Object.freeze(["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","ANTHROPIC_BASE_URL","CLAUDE_CONFIG_DIR","OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_API_BASE","CODEX_HOME","GEMINI_API_KEY","GOOGLE_API_KEY","DEEPSEEK_API_KEY","DSH_HOME","OPENROUTER_API_KEY","GROQ_API_KEY","XAI_API_KEY","MISTRAL_API_KEY"]);function ye({engine:e="custom",home:t,env:n={},base:r={},carry:o=oe}={}){p(typeof t=="string"&&t.length>0,"windows env: home required");const s=t.replace(/\//g,"\\"),l=/^[a-z]:/i.test(s)?s.slice(0,2):"",c={USERPROFILE:s,...l?{HOMEDRIVE:l,HOMEPATH:s.slice(2)}:{}};for(const[a,i]of Object.entries(n))typeof i=="string"&&(r[a]!==i||o.includes(a))&&(c[a]=i);return e==="codex"&&!c.CODEX_HOME&&(c.CODEX_HOME=s+"\\.codex"),c}function Ee(e,t){p(Array.isArray(e),"srt-win argv: must be an array");const n=e.indexOf("exec"),r=n>=0?e.indexOf("--",n+1):-1;p(n>=0&&r>n,"srt-win argv: expected `exec … -- <shell> <command>`");const o=new Set;for(let l=n+1;l<r;l++)e[l]==="--env"&&typeof e[l+1]=="string"&&o.add(e[l+1].split("=")[0].toUpperCase());const s=[];for(const[l,c]of Object.entries(t||{}))p(/^[A-Za-z_][A-Za-z0-9_]*$/.test(l),`srt-win env: bad key ${l}`),p(!/[\r\n]/.test(c),`srt-win env: ${l} holds a newline`),o.has(l.toUpperCase())||s.push("--env",`${l}=${c}`);return[...e.slice(0,r),...s,...e.slice(r)]}export{C as CA_BUNDLE_RELPATH,ce as CA_BUNDLE_RELPATH_LEGACY,z as COMMON_WRITE,F as DEVELOPER_HOSTS,v as ENGINE_KITS,V as GATEWAY_FENCE,N as NETWORK_MODES,k as SANDBOX_LAYERS,ke as SANDBOX_READ_MODES,Ne as SANDBOX_RUNTIMES,S as SECRET_PATHS,j as SECRET_READ_GLOBS,Ie as SIGN_IN_LABELS,Re as SIGN_IN_NAMES,I as SIGN_IN_STORES,B as TOOLCHAIN_READ,oe as WINDOWS_CARRY_KEYS,le as caBundlePath,je as expandWrapper,ue as gatewayKit,W as isSecretWritePath,q as kitFor,Se as mergeGrants,Oe as mergePersonGrants,xe as normalizeGrant,Ae as parseHostList,We as parseWrapperTemplate,ae as readDenialFor,ge as sandboxEnvOverlay,pe as sandboxRecord,me as shellJoin,J as shellQuote,de as signInDenial,Y as signInHosts,D as signInRead,fe as toSrtSettings,b as underWindowsHome,$ as validateKit,he as windowsGrantsFor,ne as windowsInstallRoot,ye as windowsSandboxEnv,Ee as withSrtWinEnv,Z as writableRoots};
|
package/src/pii/pii-detect.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{assertEndpointUrl as D}from"./net.js";const
|
|
1
|
+
import{assertEndpointUrl as D}from"./net.js";const N=new Map,p=300;function V(){N.clear()}function T(e,t){let o=5381;const s=`${t?.backend}|${t?.url}|${t?.model}|${t?.strictness||""}|${JSON.stringify(t?.types||null)}|${e}`;for(let n=0;n<s.length;n++)o=(o<<5)+o+s.charCodeAt(n)|0;return`${s.length}:${o}`}function y(e,t,o){return new Promise((s,n)=>{const i=setTimeout(()=>n(new Error("detect timeout")),Math.max(200,t||1500)),r=()=>{clearTimeout(i),n(new Error("aborted"))};o&&o.addEventListener?.("abort",r,{once:!0}),e.then(c=>{clearTimeout(i),s(c)},c=>{clearTimeout(i),n(c)})})}function w(e){const t=String(e||"ENTITY").toUpperCase().replace(/[^A-Z0-9]/g,"")||"ENTITY";return{PER:"PERSON",PERSON:"PERSON",PERSONNAME:"PERSON",PRIVATEPERSON:"PERSON",GIVENNAME:"PERSON",FIRSTNAME:"PERSON",MIDDLENAME:"PERSON",SURNAME:"PERSON",LASTNAME:"PERSON",FULLNAME:"PERSON",ORG:"ORG",ORGANIZATION:"ORG",COMPANYNAME:"ORG",COMPANY:"ORG",GPE:"LOCATION",LOC:"LOCATION",LOCATION:"LOCATION",CITY:"LOCATION",STATE:"LOCATION",COUNTY:"LOCATION",COUNTRY:"LOCATION",STREET:"ADDRESS",BUILDINGNUM:"ADDRESS",BUILDINGNUMBER:"ADDRESS",ZIPCODE:"ADDRESS",POSTCODE:"ADDRESS",SECADDRESS:"ADDRESS",ADDRESS:"ADDRESS",PRIVATEADDRESS:"ADDRESS",NORP:"GROUP",EMAIL:"EMAIL",EMAILADDRESS:"EMAIL",PRIVATEEMAIL:"EMAIL",PHONE:"PHONE",PHONENUMBER:"PHONE",TELEPHONENUM:"PHONE",PRIVATEPHONE:"PHONE",PHONEIMEI:"ID",SOCIALNUM:"SSN",USSSN:"SSN",SSN:"SSN",CREDITCARDNUMBER:"CREDITCARD",CREDITCARD:"CREDITCARD",IBAN:"IBAN",IBANCODE:"IBAN",ACCOUNTNUM:"ID",ACCOUNTNUMBER:"ID",TAXNUM:"ID",IDCARDNUM:"ID",DRIVERLICENSENUM:"ID",PASSPORTNUM:"ID",VEHICLEVRM:"ID",DATEOFBIRTH:"ID",DOB:"ID",PRIVATEDATE:"ID",PRIVATEURL:"ID",USERNAME:"ID",USERID:"ID",IP:"ID",IPADDRESS:"ID",MAC:"ID",PASSWORD:"SECRET",APIKEY:"SECRET",SECRET:"SECRET"}[t]||t}const C=new Set(["EMAIL","PHONE","SSN","CREDITCARD","IBAN","ID","SECRET"]),d=new Set(["LOCATION","FAC","ADDRESS","GROUP","NRP"]),P=/(?:^|[\s$€£])\$?\d+(?:[.,]\d+)?\s?(?:[kmb]n?|mm|million|billion|thousand|%)(?=[\s.,;:!?)]|$)/i,g=/(?:^|\s)\d{1,6}(?=\s|,|$)/;function L(e){const t=String(e||"").trim();return P.test(t)&&!g.test(t)}const j=Object.freeze(["balanced","strict"]),b=e=>e?.strictness==="strict"||e?.detection?.strictness==="strict"?"strict":"balanced",R=new Set(["chap","chatpanel"]),M=new Set(["by","hey"]);function U(e){const t=String(e||"").toLowerCase().match(new RegExp("\\p{L}[\\p{L}\\p{N}]*","gu"))||[];return t.some(o=>R.has(o))&&t.every(o=>R.has(o)||M.has(o))}function k(e,t,o,s="balanced"){const n=r=>!o||o[r]!==!1;return(t==="PERSON"||t==="ORG")&&U(e)||s!=="strict"&&t==="ADDRESS"&&L(e)?!1:C.has(t)?!0:t==="PERSON"?n("person"):t==="ORG"?n("org"):d.has(t)?n("location"):(String(e).match(/\d/g)||[]).length>=7?n("number"):!1}function f(e,t,{strictness:o="balanced"}={}){let s=[];Array.isArray(e)?s=e:e&&Array.isArray(e.entities)?s=e.entities:e&&Array.isArray(e.ents)?s=e.ents:e&&Array.isArray(e.results)&&(s=e.results);const n=[],i=new Set;for(const r of s){if(!r)continue;const c=String(r.value??r.text??r.entity??r.word??"").trim(),a=w(r.type??r.label??r.entity_group??r.entity_type??r.tag);if(!c||c.length>200||!k(c,a,t,o))continue;const l=`${a}:${c.toLowerCase()}`;i.has(l)||(i.add(l),n.push({value:c,type:a}))}return n}const x=new Set("a an the i am is are was were be been being to of in on at for and or but if so not no yes ok okay hi hello hey you your yours me my mine we us our ours they them their he him his she her it its this that these those what where when who whom why how which do does did done have has had having will would can could should may might must shall there here now then last next first time day days week month year today tomorrow yesterday see saw seen say said tell told go went gone come came get got give gave take took make made know knew think thought want need like just also very really with from into onto over under about after before between through during without within up down out off again still used use using live lived move moved work worked help please thanks thank sorry new old good bad more most some any all each because as than too so such only own same other another much many few both either neither every never always often".split(/\s+/));function K(e){const t=String(e||"");let o=!1;return{text:t.replace(new RegExp("(^|[^\\p{L}\\p{N}'’])(\\p{Ll})(\\p{L}*)","gu"),(n,i,r,c)=>{const a=r+c;if(x.has(a))return n;const l=r.toUpperCase();return l.length!==1||l===r?n:(o=!0,i+l+c)}),changed:o}}function $(e){if(!e)return null;const t=String(e).indexOf("{"),o=String(e).lastIndexOf("}");if(t<0||o<=t)return null;try{return JSON.parse(String(e).slice(t,o+1))}catch{return null}}const v="You extract sensitive entities from text for redaction. Copy each value exactly as it appears. Include people, organizations, locations, and account/ID numbers. No commentary, no code fences.",H='Return ONLY JSON: {"entities":[{"value":"<verbatim text>","type":"PERSON|ORG|LOCATION|ID|EMAIL|PHONE|OTHER"}]}. No commentary, no code fences.',I=Object.freeze({block:"",format:null,parse:null});async function B(e,t,o,s){const n=await s(t.url,{method:"POST",headers:{"Content-Type":"application/json",...t.apiKey?{Authorization:`Bearer ${t.apiKey}`}:{}},body:JSON.stringify({text:e,...t.strictness==="strict"?{strict:!0}:{}}),signal:o});if(!n.ok)throw new Error(`detect HTTP ${n.status}`);return f(await n.json(),t.types,{strictness:t.strictness})}async function G(e,t,o,s,n=I){const i=String(t.url||"").replace(/\/$/,""),r=/\/chat\/completions$/.test(i)?i:/\/v\d+$/.test(i)?`${i}/chat/completions`:`${i}/v1/chat/completions`,c=`${v}
|
|
2
2
|
|
|
3
|
-
${n.block
|
|
3
|
+
${n.block||H}`,a=async S=>{const E=n.format?n.format(S):null,u=await s(r,{method:"POST",headers:{"Content-Type":"application/json",...t.apiKey?{Authorization:`Bearer ${t.apiKey}`}:{}},body:JSON.stringify({model:t.model||"local",temperature:0,max_tokens:t.maxTokens||256,messages:[{role:"system",content:c},{role:"user",content:e}],...E||{}}),signal:o});if(!u.ok){const O=new Error(`detect HTTP ${u.status}`);throw O.status=u.status,O}return u.json()};let l=null;if(n.format)for(const S of["schema","object","none"])try{l=await a(S);break}catch(E){if(S==="none"||E.status!==400&&E.status!==422)throw E}else l=await a("none");const h=l?.choices?.[0]?.message?.content??l?.content??"",A=n.parse?n.parse(h):$(h);return f(A,t.types,{strictness:t.strictness})}function m(e,t,o,s,n,i){if(typeof e=="function")try{e({backend:t.backend||"",host:Y(t.url),chars:o.length,entities:n,ms:Date.now()-s,ok:!i,error:i?String(i.message||i).slice(0,200):""})}catch{}}const Y=e=>{try{return new URL(String(e)).host}catch{return""}};async function z(e,t,{signal:o,fetchImpl:s=globalThis.fetch,strict:n=!1,structured:i=I,onEgress:r=null,onError:c=null}={}){const a=t?.detection?{...t.detection,strictness:b(t)}:null;if(!a||!a.backend||a.backend==="off"||!a.url||typeof s!="function")return[];const l=a.transport==="in-process";if(l&&s===globalThis.fetch)throw new Error("detection.transport 'in-process' needs an injected fetch; refusing to treat a network call as in-process");const h=String(e||"").slice(0,a.maxChars||8e3);if(h.trim().length<8)return[];const A=T(h,a);if(!n&&N.has(A))return N.get(A);const S=a.backend==="endpoint"?B:G;let E=[];try{l||D(a.url);const u=Date.now();try{E=await y(S(h,a,o,s,i),a.timeoutMs||1500,o),l||m(r,a,h,u,E.length,null)}catch(O){throw l||m(r,a,h,u,0,O),O}}catch(u){if(n)throw u;try{c?.(u)}catch{}return[]}return N.size>=p&&N.clear(),n||N.set(A,E),E}export{v as EXTRACT_SYS,j as REDACTION_STRICTNESS,V as clearDetectCache,z as detectEntities,w as normType,f as normalizeEntities,U as ownName,$ as parseJsonLoose,L as quantityNotAddress,K as recaseForDetection,b as strictnessOf,y as withTimeout};
|
package/src/pii/tool-harness.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{restoreText as
|
|
1
|
+
import{restoreText as T,restoreWithAliases as N,redactResultShape as w}from"./pii-redact.js";import{narrowSpecs as S}from"./tool-rank.js";const R=e=>/^mcp[_-]/i.test(String(e||""));function h(e,o){if(!o)return e;if(typeof e=="string")return N(e,o);if(Array.isArray(e))return e.map(t=>h(t,o));if(e&&typeof e=="object"){const t={};for(const n of Object.keys(e))t[n]=h(e[n],o);return t}return e}function I({ownTools:e=!1}={}){return"PRIVACY PLACEHOLDERS: some values in this conversation are tokens like [[PERSON_1]], [[LOCATION_1]], [[ORG_1]] that stand in for the user's real private data. Treat each one as a CONCRETE, specific value you already have — not missing or unknown information. Do not ask what it stands for, do not say it is unresolved, and do not refuse on privacy grounds. Reason and write with the placeholder exactly as written; the real value is restored in your answer automatically."+(e?g:"")}const d="Any tool you bring yourself — your own web search, browser, shell, file or code tools — receives the placeholder text literally: it finds nothing, and it opens, types or saves the placeholder itself. ",L=" ONLY THE TOOLS LISTED IN THIS CONVERSATION restore placeholders. "+d+"So for ANYTHING that involves a placeholder — a lookup, a search, a page to open, text to type or save — call the listed tool (for example `find` with action `web_search` or `history_search`) rather than your own; if no listed tool can do it, say so instead of handing a placeholder to a tool of your own. Prefer the listed tools for lookups in general — the user sees those as steps — and keep your own tools for what the listed ones cannot do.",g=" That restoring happens in your ANSWER only. "+d+"So never hand a placeholder to a tool of your own: if the request needs the real value in a tool, say which part you could not do.";function _({toolData:e="real",ownTools:o=!1}={}){const t="PRIVACY PLACEHOLDERS: some values in this conversation are tokens like [[PERSON_1]], [[LOCATION_1]], [[ORG_1]] that stand in for the user's real private data. ",n=e==="redactRemote"?"When you call a LOCAL tool the placeholder is automatically replaced with the real value before the tool runs; REMOTE (MCP) tools deliberately receive the placeholder to keep private data off third-party servers. ":`When you call ${o?"a tool LISTED IN THIS CONVERSATION":"ANY tool"}, these placeholders are AUTOMATICALLY replaced with the real values before the tool executes — the tool receives the TRUE value and returns correct results. `,l="So: treat each placeholder as a CONCRETE, specific value you already have — it is enough to act on, NOT missing or unknown information. CALL THE TOOL using the placeholder exactly as written, as if it were the real value. If answering needs the real data behind a placeholder (e.g. which city [[LOCATION_1]] is, who [[PERSON_1]] is, what [[ORG_1]] does), do NOT reply that you lack information or cannot answer. Instead pick the most relevant available tool for that placeholder's TYPE — LOCATION → geography / place lookups, PERSON → people lookups, ORG → company/org lookups, dates/IDs → the matching lookup — and pass the placeholder straight through as the argument. The harness restores the true value before the tool runs, so the lookup returns correct results. Make your best-guess tool call FIRST; only conclude you lack data AFTER a tool has actually returned nothing useful. Do NOT ask the user to re-type the value and do NOT refuse on privacy grounds — the lookup will work. The real values are restored in your final answer automatically, so write your answer using the placeholders too.",i=o?L:"";return t+n+l+i}const E=new Set(["web_search","web_fetch","fetch_url"]);function k(e){return E.has(String(e||"").toLowerCase())}function f(e,o,t){const n=y(o);return!n||n===e?e:t instanceof Map&&t.get(n)===e?n:e}function y(e){let o=e;if(typeof o=="string")try{o=JSON.parse(o)}catch{return""}const t=o&&typeof o=="object"?o.action:null;return typeof t=="string"?t:""}function C({vault:e=null,toolData:o="real",redactOpts:t=null,redactResults:n=!0,remoteTools:l=null,hiddenVia:i=null}={}){const c=!!e,O=o==="redactRemote",u=typeof l=="function"?l:l instanceof Set?r=>l.has(r):R,p=(r,a)=>{if(u(r))return!0;const s=y(a);return!!s&&s!==r&&u(s)};return{enabled:c,isRemoteTool:p,realToolName:(r,a)=>f(r,a,i),selectTools(r,a,s={}){return S(r,a,s)},toTool(r,a){return!c||O&&p(r,a)?a:h(a,e)},toModelResult(r,a,s){return!c||!n||!t||k(f(r,s,i))?a:w(a,e,t)},toUser(r){return c?T(r,e):r}}}export{k as isPublicSourceTool,R as isRemoteToolName,C as makeToolHarness,I as placeholderNote,_ as placeholderToolNote,f as realToolName,h as restoreToolArgs};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawnSync as M}from"node:child_process";import{existsSync as x}from"node:fs";import c from"node:path";import A from"node:os";import{defineSandboxRuntime as b,registerSandboxRuntime as w}from"./sandbox-runtime.js";import{sandboxRecord as _,parseWrapperTemplate as I,expandWrapper as D}from"./events/sandbox-policy.js";function h(n){if(c.isAbsolute(n))return x(n);try{const r=M(process.platform==="win32"?"where":"which",[n],{encoding:"utf8",timeout:3e3});return r.status===0&&String(r.stdout||"").trim().length>0}catch{return!1}}function y({config:n={},home:r=A.homedir(),isInstalled:s=h}={}){let e=null,t=null;function i(){if(!(e||t)){if(!n.command){t="no sandbox command is set — Settings › Runtime › Sandbox command";return}try{e=I(n.command)}catch(o){t=`the sandbox command is not usable: ${o.message.replace(/^sandbox command: /,"")}`;return}s(e[0])||(t=`${e[0]} (your sandbox command) is not installed on this computer`,e=null)}}return b({id:"command",label:"Your own sandbox command",async detect(){return i(),{ok:!!e,runtime:e?`command:${c.basename(e[0])}`:null,reason:t,ownSessions:!!e}},async wrap({kit:o,grant:a,bin:S,argv:d,opts:m,workdir:f,commandId:u}){if(i(),!e)return{passReason:t};const l=D(e,{bin:S,argv:d,workdir:f,home:r,hosts:a?.hosts||[],mode:o.network.mode}),g=_({layer:"process",runtime:`command:${c.basename(e[0])}`,kitId:o.id,mode:o.network.mode,hosts:a?.hosts||[]});return{bin:l[0],argv:l.slice(1),opts:{...m,shell:!1},record:g,commandId:u}}})}const T=/^(PATH|HOME|USER|LOGNAME|SHELL|TMPDIR|TMP|TEMP|PWD|OLDPWD|SHLVL|TERM_PROGRAM.*|TERM_SESSION_ID|SSH_AUTH_SOCK|SSH_AGENT_PID|DISPLAY|XPC_.*|__CF.*|SECURITYSESSIONID|LaunchInstanceID|Apple_.*|COMMAND_MODE|MallocNanoZone|ELECTRON_.*|_|NODE_OPTIONS)$/;function R({config:n={},isInstalled:r=h,platform:s=process.platform}={}){let e=null,t=null;function i(){if(e||t)return;if(!n.image){t="no container image is set — Settings › Runtime › Container image";return}const o=n.engine?[n.engine]:["podman","docker"];e=o.find(a=>r(a))||null,e||(t=`${o.join(" or ")} is not installed on this computer`)}return b({id:"container",label:"A container (Podman or Docker)",async detect(){return i(),{ok:!!e,runtime:e?`container:${e}`:null,reason:t,ownSessions:!!e}},async wrap({kit:o,bin:a,argv:S,opts:d,workdir:m,commandId:f}){if(i(),!e)return{passReason:t};const u=d?.env||process.env,l=Object.keys(u).filter(p=>!T.test(p)&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(p)).sort(),g=["run","--rm","-i","--init","--cap-drop","ALL","--security-opt","no-new-privileges",...o.network.mode==="none"?["--network","none"]:[],...e==="docker"&&s==="linux"&&process.getuid?["--user",`${process.getuid()}:${process.getgid()}`]:[],"-v",`${m}:${m}`,"-w",m,...l.flatMap(p=>["-e",p]),n.image,c.isAbsolute(a)?c.basename(a):a,...S],O=_({layer:"container",runtime:`container:${e}`,kitId:o.id,mode:o.network.mode});return{bin:e,argv:g,opts:{...d,env:u,shell:!1},record:O,commandId:f}}})}function E(){return b({id:"managed",label:"Managed by your organisation",async detect(){return{ok:!0,runtime:"managed",reason:null,ownSessions:!1}},async wrap({kit:n,bin:r,argv:s,opts:e,commandId:t}){return{bin:r,argv:s,opts:e,record:_({layer:"external",runtime:"managed",kitId:n.id,mode:n.network.mode}),commandId:t}}})}w("command",n=>y(n)),w("container",n=>R(n)),w("managed",()=>E());export{y as createCommandRuntime,R as createContainerRuntime,E as createManagedRuntime};
|
package/src/sandbox-host.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as
|
|
1
|
+
import{readFileSync as f,unlinkSync as u,realpathSync as i}from"node:fs";import{spawn as g}from"node:child_process";import{fileURLToPath as y}from"node:url";import{createSandbox as b}from"./sandbox.js";async function x(n,{compiled:l=!1}={}){n||(console.error("sandbox-host: a spec file is required"),process.exit(2));let r;try{r=JSON.parse(f(n,"utf8"))}catch(o){console.error(`sandbox-host: cannot read the spec: ${o.message}`),process.exit(2)}try{u(n)}catch{}const m=(o,t,h)=>{r.report?.url&&fetch(r.report.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:r.report.token,commandId:r.commandId,host:o,port:t,reason:h}),signal:AbortSignal.timeout(2e3)}).catch(()=>{})},a=b({config:r.config,loadSrt:()=>import(r.srt),compiled:l,loopback:r.loopback||[],onRefusal:o=>m(o.host,o.port,o.reason),log:o=>console.error(`[sandbox-host] ${o}`)});let e;try{e=await a.wrap(r.bin,r.argv,{cwd:r.cwd||void 0,env:process.env},{engine:r.engine,cwd:r.workdir,grant:r.grant,commandId:r.commandId})}catch(o){console.error(`[sandbox-host] ${o.message}`),process.exit(126)}e.record.layer==="none"&&console.error(`[sandbox-host] running outside the sandbox — ${e.record.reason}`);const s=g(e.bin,e.argv,{...e.opts,stdio:"inherit"}),c=o=>{try{s.kill(o)}catch{}};process.on("SIGTERM",()=>c("SIGTERM")),process.on("SIGINT",()=>c("SIGINT")),process.on("SIGHUP",()=>c("SIGHUP")),s.on("error",o=>{console.error(`[sandbox-host] could not start ${r.bin}: ${o.message}`),process.exit(127)}),s.on("exit",async(o,t)=>{try{a.close()}catch{}try{await(await import(r.srt)).SandboxManager.reset()}catch{}if(t)try{process.kill(process.pid,t)}catch{}process.exit(o??1)})}const p=(()=>{try{return i(y(import.meta.url))}catch{return""}})(),d=(()=>{try{return process.argv[1]?i(process.argv[1]):""}catch{return""}})();p&&d&&p===d&&await x(process.argv[2]);export{x as runSandboxHost};
|
package/src/sandbox-srt.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync as ke}from"node:child_process";import{writeFileSync as oe,mkdirSync as re,existsSync as De}from"node:fs";import{createHash as Ee,randomBytes as Oe}from"node:crypto";import{fileURLToPath as $e}from"node:url";import M from"node:os";import $ from"node:path";import{toSrtSettings as ie,sandboxRecord as Le,shellJoin as ae,sandboxEnvOverlay as F,windowsGrantsFor as Ce,windowsSandboxEnv as Re,withSrtWinEnv as Te,ENGINE_KITS as ce,DEVELOPER_HOSTS as de,SECRET_PATHS as Ne,COMMON_WRITE as He}from"./events/sandbox-policy.js";import{defineSandboxRuntime as _e,registerSandboxRuntime as Pe}from"./sandbox-runtime.js";function je(n=process.env.CHATPANEL_SRT_MODULE){if(!n)return"";try{const o=n.startsWith("file:")?$e(new URL("./cli.js",n)):$.join($.dirname(n),"cli.js");return De(o)?o:""}catch{return""}}const le=new Set;function ue(n,o=$.join(M.tmpdir(),"chatpanel-srt")){const y=JSON.stringify(n),p=$.join(o,`${Ee("sha256").update(y).digest("hex").slice(0,16)}.json`);return le.has(p)||(re(o,{recursive:!0,mode:448}),oe(p,y,{mode:384}),le.add(p)),p}function Me(){try{const n=ke(process.platform==="win32"?"where":"which",["srt"],{encoding:"utf8",timeout:3e3});return n.status===0&&String(n.stdout||"").trim().length>0}catch{return!1}}const z="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)";function Ue({config:n,platform:o=process.platform,home:y=M.homedir(),loopback:p=[],compiled:W=!1,selfFiles:he=[process.execPath,process.argv[1]||""],onExit:we=_=>process.on("exit",_),hostEntry:B=null,reportUrl:J="",mintReportToken:fe=()=>"",onRefusal:be=()=>{},parseRefusal:xe=()=>null,loadSrt:X=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:G=Me,cliEntry:K=je(),hostEntryFor:q=()=>"",log:L=()=>{}}={}){const _=new Set;let c=null,w=null,a=null,U=null,C=null,g=null,A=null;const R=new Set;let Q=!1;const me="Windows: the sandbox runs a process as a separate account, and mapping your sign-in, the CLI and its environment into it is built but not yet proved on a signed-in machine — CHATPANEL_SANDBOX_WINDOWS=1 turns it on (docs/sandboxing.md S1)",pe="Windows: the sandbox account needs the runtime the gateway carries (the `srt` CLI cannot map your sign-in into it) — run the bridge through chatpanel-gateway";async function Se(){if(!n.windows){w=me;return}if(W){w=pe;return}try{a=await X()}catch(t){w=`sandbox-runtime is not installed — it ships with the gateway (${t.message})`;return}if(!a?.SandboxManager?.wrapWithSandboxArgv||typeof a.grantWindowsAcl!="function"||typeof a.getWindowsSandboxUserStatusAsync!="function"){w="Windows: this sandbox-runtime is older than 0.0.77, which the account mapping needs";return}try{g=a.resolveSrtWin({path:a.VENDORED_SRT_WIN_EXE})}catch(t){w=`Windows: srt-win.exe is not beside sandbox-runtime (${t.message})`;return}let e;try{e=await a.getWindowsSandboxUserStatusAsync({srtWin:g})}catch(t){A=!1,w=`Windows: srt-win could not be asked whether the sandbox account exists (${t.message}) — ${z}`;return}if(A=!!(e?.provisioned&&e.sid),!A){w=`Windows: the sandbox account is not installed — ${z}`;return}C=e.sid,c="srt-lib"}async function ye(){if(!(c||w)){if(!n.enabled){w="sandboxing is off (CHATPANEL_SANDBOX=off)";return}if(o==="win32")return Se();if(!W)try{if(a=await X(),a?.SandboxManager?.wrapWithSandboxArgv){c="srt-lib";return}}catch(e){L(`sandbox: library not available (${e.message})`)}if(G()){c="srt-cli";return}w=W?"srt is not on PATH — the compiled bridge cannot carry it: npm i -g @anthropic-ai/sandbox-runtime":"sandbox-runtime is not installed — it ships with the gateway; standalone: npm i -g @anthropic-ai/sandbox-runtime"}}let Y=!1;function Z(e,{hosts:t=[],sockets:s=[]}={}){const r={...e.network};let i=!1;if((r.allowedDomains||[]).includes("*")){const d=r.allowedDomains.filter(l=>l.startsWith("127.0.0.1:"));r.allowedDomains=[...new Set([...Object.values(ce).flatMap(l=>l.hosts),...de,...n.extraHosts,...t,...d])],i=!0}return o==="darwin"&&s.length&&(r.allowUnixSockets=s),{settings:{...e,network:r},narrowed:i}}const ee=(e,{narrowed:t},s)=>(t&&(e.narrowed=`open → allowlist: the srt CLI refuses "*" — the gateway's embedded bridge runs open`),s.length&&o==="darwin"&&(e.sockets=s,delete e.socketsDropped),e);function I(){return K&&!W?{bin:process.execPath,argv:[K]}:c==="srt-cli"||G()?{bin:"srt",argv:[]}:null}function ge(){const e=Array.isArray(n.exactHosts)?n.exactHosts:n.mode==="open"?["*"]:n.mode==="none"?[]:[...new Set([...Object.values(ce).flatMap(r=>r.hosts),...de,...n.extraHosts])],t={id:`session:${n.mode}`,network:{mode:n.mode,allowedDomains:e},filesystem:{allowWrite:[M.tmpdir(),...He,...n.extraWrite],denyRead:[...Ne,...n.extraDenyRead]}},s=ie(t,{loopback:p,home:o==="linux"?y:"",platform:o});return o==="darwin"&&Array.isArray(n.exactSockets)&&n.exactSockets.length&&(s.network.allowUnixSockets=n.exactSockets),g?{...s,windows:{srtWin:{path:g.exe}}}:s}async function te(){return U||(U=a.SandboxManager.initialize(ge()).then(()=>{try{a.SandboxManager.getSandboxViolationStore?.()?.subscribe?.(e=>{for(const t of e||[]){const s=xe(t?.line);if(!s||!t?.encodedCommand)continue;let r="";try{r=Buffer.from(t.encodedCommand,"base64").toString("utf8")}catch{continue}const i=`${r}|${s.host}|${t.timestamp instanceof Date?t.timestamp.getTime():String(t.timestamp)}`;_.has(i)||(_.add(i),be({commandId:r,...s,at:t.timestamp instanceof Date?t.timestamp.getTime():Date.now()}))}})}catch(e){L(`sandbox: violations not subscribed (${e.message})`)}})),U}function ve(e){const t=$.join(M.tmpdir(),"chatpanel-srt");re(t,{recursive:!0,mode:448});const s=$.join(t,`host-${Oe(8).toString("hex")}.json`);return oe(s,JSON.stringify(e),{mode:384}),s}function We(e,t){const s=(d,l)=>a.expandWindowsFsPaths(d,{mode:l}).filter(u=>!R.has(`${l}:${u.toLowerCase()}`)),r=s(e,"grant"),i=s(t,"grant");if(!(!r.length&&!i.length)){a.grantWindowsAcl({sandboxUserSid:C,read:r,write:i,srtWin:g});for(const d of r)R.add(`grant:${d.toLowerCase()}`);for(const d of i)R.add(`grant:${d.toLowerCase()}`);Q||(Q=!0,we(()=>{try{a.revokeWindowsAcl({sandboxUserSid:C,srtWin:g})}catch{}}))}}async function Ae(e,t,s,{engine:r,workdir:i,kit:d,settings:l,commandId:u,record:T,caBundle:S=""}){await te();const k=h=>typeof h=="string"&&/^[a-z]:\\/i.test(h),{read:P,write:D}=Ce({kit:d,files:[e,...k(t[0])?[t[0]]:[],...he].filter(Boolean),home:y});We(P,D);const f=ae(e,t,{platform:"win32"}),E=await a.SandboxManager.wrapWithSandboxArgv(f,void 0,{filesystem:{denyRead:l.filesystem.denyRead,denyWrite:l.filesystem.denyWrite}},void 0,i,{commandId:u,commandText:f}),x=s?.env||process.env,v={...Re({engine:r,home:y,env:x,base:process.env}),...F({},{platform:o,caBundle:S})},N=Te(E.argv,v),b={};for(const[h,H]of Object.entries(E.env||{}))process.env[h]!==H&&(b[h]=H);return{bin:N[0],argv:N.slice(1),opts:{...s,env:{...x,...b},shell:!1},record:T,commandId:u}}return _e({id:"srt",label:"Anthropic sandbox-runtime",async detect(){return await ye(),{ok:!!c,runtime:c,reason:w,ownSessions:!!(c&&(c==="srt-lib"&&(B??q(W))||o!=="win32"&&I())),...o==="win32"&&A!==null?{provisioned:A,...A?{}:{install:z}}:{}}},async wrap({kit:e,grant:t,bin:s,argv:r,opts:i,engine:d,workdir:l,commandId:u,caBundle:T=""}){const S=ie(e,{loopback:p,home:o==="linux"?y:"",platform:o}),k=ae(s,r),P=Array.isArray(n.exactHosts),D=n.mode==="allowlist"&&t.hosts.length>0&&!P,f=S.network.allowUnixSockets||[],E=f.length>0&&!P;delete S.network.allowUnixSockets;const x=(D||E)&&c==="srt-lib"?B??q(W):"",v=D&&!x&&o!=="win32"?I():null,N=!!(x||v),b=Le({layer:"process",runtime:x?"srt-host":v?"srt-cli":c,kitId:e.id,mode:e.network.mode,hosts:N||!D?t.hosts:[]});D&&!N&&(b.hostsDropped=t.hosts,Y||(Y=!0,L(`sandbox: hosts granted to ${d} (${t.hosts.join(", ")}) need a session of their own — no sandbox host or srt CLI here, so the process runs with the shared allow list`))),E&&!x?b.socketsDropped=f:E&&(b.sockets=f);try{if(x){const m=fe(u),O={bin:s,argv:r,cwd:i?.cwd||null,engine:d,workdir:l,grant:t,commandId:u,config:{enabled:!0,mode:n.mode,extraHosts:[],extraWrite:n.extraWrite,extraDenyRead:n.extraDenyRead,windows:n.windows,exactHosts:e.network.allowedDomains,exactSockets:f},loopback:p,srt:process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime",report:J?{url:J,token:m}:null},j={...i?.env||process.env};return{bin:process.execPath,argv:[x,ve(O)],opts:{...i,env:j,shell:!1},record:b,commandId:u}}if(v){const m={...i?.env||process.env};Object.assign(m,F(m,{platform:o,caBundle:T}));const O=Z(S,{hosts:t.hosts,sockets:f});return{bin:v.bin,argv:[...v.argv,"-s",ue(O.settings),"-c",k],opts:{...i,env:m,shell:!1},record:ee(b,O,f),commandId:u}}if(c==="srt-lib"&&o==="win32")return{...await Ae(s,r,i,{engine:d,workdir:l,kit:e,settings:S,commandId:u,record:b,caBundle:T})};if(c==="srt-lib"){await te();const m=await a.SandboxManager.wrapWithSandboxArgv(k,void 0,{filesystem:S.filesystem},void 0,l,{commandId:u,commandText:k}),O=i?.env||process.env,j={};for(const[ne,se]of Object.entries(m.env||{}))process.env[ne]!==se&&(j[ne]=se);const V={...O,...j};return Object.assign(V,F(V,{platform:o,caBundle:T})),{bin:m.argv[0],argv:m.argv.slice(1),opts:{...i,env:V,shell:!1},record:b,commandId:u}}const h=I(),H=Z(S,{hosts:t.hosts,sockets:f});return{bin:h.bin,argv:[...h.argv,"-s",ue(H.settings),"-c",k],opts:{...i,shell:!1},record:ee(b,H,f),commandId:u}}catch(h){return L(`sandbox: could not wrap ${s}: ${h.message}`),{passReason:h?.code==="SHAPE"?`the sandbox policy refused this run: ${h.message}`:`sandbox-runtime failed to wrap the command: ${h.message}`}}},violations(e){try{return a?.SandboxManager?.getSandboxViolationStore?.()?.getViolationsForCommand?.(e)||[]}catch{return[]}},close(){if(!(!C||!R.size)){try{a.revokeWindowsAcl({sandboxUserSid:C,srtWin:g})}catch(e){L(`sandbox: could not release the Windows grants: ${e.message}`)}R.clear()}}})}Pe("srt",n=>Ue(n));export{Ue as createSrtRuntime};
|
|
1
|
+
import{spawnSync as Te}from"node:child_process";import{writeFileSync as ae,mkdirSync as ce,existsSync as de}from"node:fs";import{createHash as Ce,randomBytes as _e}from"node:crypto";import{fileURLToPath as le}from"node:url";import M from"node:os";import $ from"node:path";import{toSrtSettings as ue,sandboxRecord as Ne,shellJoin as he,sandboxEnvOverlay as V,windowsGrantsFor as He,windowsSandboxEnv as Pe,withSrtWinEnv as je,ENGINE_KITS as we,DEVELOPER_HOSTS as fe,SECRET_PATHS as Me,COMMON_WRITE as Ue}from"./events/sandbox-policy.js";import{defineSandboxRuntime as Ie,registerSandboxRuntime as Fe}from"./sandbox-runtime.js";function Ve(t=process.env.CHATPANEL_SRT_MODULE){if(!t)return"";try{const r=t.startsWith("file:")?le(new URL("./cli.js",t)):$.join($.dirname(t),"cli.js");return de(r)?r:""}catch{return""}}const be=new Set;function pe(t,r=$.join(M.tmpdir(),"chatpanel-srt")){const y=JSON.stringify(t),S=$.join(r,`${Ce("sha256").update(y).digest("hex").slice(0,16)}.json`);return be.has(S)||(ce(r,{recursive:!0,mode:448}),ae(S,y,{mode:384}),be.add(S)),S}function ze(t=process.env.CHATPANEL_SRT_MODULE){if(!t||!String(t).startsWith("file:"))return!1;try{return de(le(t))}catch{return!1}}function Be(){try{const t=Te(process.platform==="win32"?"where":"which",["srt"],{encoding:"utf8",timeout:3e3});return t.status===0&&String(t.stdout||"").trim().length>0}catch{return!1}}const z="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)";function Je({config:t,platform:r=process.platform,home:y=M.homedir(),loopback:S=[],compiled:W=!1,selfFiles:xe=[process.execPath,process.argv[1]||""],onExit:Se=H=>process.on("exit",H),hostEntry:B=null,reportUrl:J="",mintReportToken:me=()=>"",onRefusal:ye=()=>{},parseRefusal:ge=()=>null,loadSrt:X=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:q=Be,cliEntry:G=Ve(),hostEntryFor:K=()=>"",onDisk:Y=ze,now:Q=()=>Date.now(),log:L=()=>{}}={}){const H=new Set;let d=null,c=null,Z=0,a=null,U=null,R=null,g=null,A=null;const T=new Set;let ee=!1;const ve="Windows: the sandbox runs a process as a separate account, and mapping your sign-in, the CLI and its environment into it is built but not yet proved on a signed-in machine — CHATPANEL_SANDBOX_WINDOWS=1 turns it on (docs/sandboxing.md S1)",We="Windows: the sandbox account needs the runtime the gateway carries (the `srt` CLI cannot map your sign-in into it) — run the bridge through chatpanel-gateway";async function Ae(){if(!t.windows){c=ve;return}if(W&&!Y()){c=We;return}try{a=await X()}catch(n){c=`sandbox-runtime is not installed — it ships with the gateway (${n.message})`;return}if(!a?.SandboxManager?.wrapWithSandboxArgv||typeof a.grantWindowsAcl!="function"||typeof a.getWindowsSandboxUserStatusAsync!="function"){c="Windows: this sandbox-runtime is older than 0.0.77, which the account mapping needs";return}try{g=a.resolveSrtWin({path:a.VENDORED_SRT_WIN_EXE})}catch(n){c=`Windows: srt-win.exe is not beside sandbox-runtime (${n.message})`;return}let e;try{e=await a.getWindowsSandboxUserStatusAsync({srtWin:g})}catch(n){A=!1,c=`Windows: srt-win could not be asked whether the sandbox account exists (${n.message}) — ${z}`;return}if(A=!!(e?.provisioned&&e.sid),!A){c=`Windows: the sandbox account is not installed — ${z}`;return}R=e.sid,d="srt-lib"}const De=6e4;async function ke(){d||c&&Q()-Z<De||(c=null,await Ee(),c&&(Z=Q()))}async function Ee(){if(!t.enabled){c="sandboxing is off (CHATPANEL_SANDBOX=off)";return}if(r==="win32")return Ae();if(!W||Y())try{if(a=await X(),a?.SandboxManager?.wrapWithSandboxArgv){const e=await a.SandboxManager.checkDependenciesAsync?.().catch(()=>null);if(e?.errors?.length){c=`the sandbox needs ${e.errors.join(", ")} on this computer${r==="linux"?" — install them (Debian/Ubuntu: sudo apt install bubblewrap socat ripgrep; Fedora: sudo dnf install bubblewrap socat ripgrep)":""}`,a=null;return}d="srt-lib";return}}catch(e){L(`sandbox: library not available (${e.message})`)}if(q()){d="srt-cli";return}c=W?"the sandbox runtime is not on this computer — the gateway binary unpacks the one it carries when it starts (chatpanel-gateway 0.94.0 or later); an older binary needs `srt` on PATH":"sandbox-runtime is not installed — it ships with the gateway; standalone: npm i -g @anthropic-ai/sandbox-runtime"}let te=!1;function ne(e,{hosts:n=[],sockets:s=[]}={}){const o={...e.network};let i=!1;if((o.allowedDomains||[]).includes("*")){const l=o.allowedDomains.filter(u=>u.startsWith("127.0.0.1:"));o.allowedDomains=[...new Set([...Object.values(we).flatMap(u=>u.hosts),...fe,...t.extraHosts,...n,...l])],i=!0}return r==="darwin"&&s.length&&(o.allowUnixSockets=s),{settings:{...e,network:o},narrowed:i}}const se=(e,{narrowed:n},s)=>(n&&(e.narrowed=`open → allowlist: the srt CLI refuses "*" — the gateway's embedded bridge runs open`),s.length&&r==="darwin"&&(e.sockets=s,delete e.socketsDropped),e);function I(){return G&&!W?{bin:process.execPath,argv:[G]}:d==="srt-cli"||q()?{bin:"srt",argv:[]}:null}function Oe(){const e=Array.isArray(t.exactHosts)?t.exactHosts:t.mode==="open"?["*"]:t.mode==="none"?[]:[...new Set([...Object.values(we).flatMap(o=>o.hosts),...fe,...t.extraHosts])],n={id:`session:${t.mode}`,network:{mode:t.mode,allowedDomains:e},filesystem:{allowWrite:[M.tmpdir(),...Ue,...t.extraWrite],denyRead:[...Me,...t.extraDenyRead]}},s=ue(n,{loopback:S,home:r==="linux"?y:"",platform:r});return r==="darwin"&&Array.isArray(t.exactSockets)&&t.exactSockets.length&&(s.network.allowUnixSockets=t.exactSockets),g?{...s,windows:{srtWin:{path:g.exe}}}:s}async function re(){return U||(U=a.SandboxManager.initialize(Oe()).then(()=>{try{a.SandboxManager.getSandboxViolationStore?.()?.subscribe?.(e=>{for(const n of e||[]){const s=ge(n?.line);if(!s||!n?.encodedCommand)continue;let o="";try{o=Buffer.from(n.encodedCommand,"base64").toString("utf8")}catch{continue}const i=`${o}|${s.host}|${n.timestamp instanceof Date?n.timestamp.getTime():String(n.timestamp)}`;H.has(i)||(H.add(i),ye({commandId:o,...s,at:n.timestamp instanceof Date?n.timestamp.getTime():Date.now()}))}})}catch(e){L(`sandbox: violations not subscribed (${e.message})`)}})),U}function $e(e){const n=$.join(M.tmpdir(),"chatpanel-srt");ce(n,{recursive:!0,mode:448});const s=$.join(n,`host-${_e(8).toString("hex")}.json`);return ae(s,JSON.stringify(e),{mode:384}),s}function Le(e,n){const s=(l,u)=>a.expandWindowsFsPaths(l,{mode:u}).filter(h=>!T.has(`${u}:${h.toLowerCase()}`)),o=s(e,"grant"),i=s(n,"grant");if(!(!o.length&&!i.length)){a.grantWindowsAcl({sandboxUserSid:R,read:o,write:i,srtWin:g});for(const l of o)T.add(`grant:${l.toLowerCase()}`);for(const l of i)T.add(`grant:${l.toLowerCase()}`);ee||(ee=!0,Se(()=>{try{a.revokeWindowsAcl({sandboxUserSid:R,srtWin:g})}catch{}}))}}async function Re(e,n,s,{engine:o,workdir:i,kit:l,settings:u,commandId:h,record:C,caBundle:m=""}){await re();const D=w=>typeof w=="string"&&/^[a-z]:\\/i.test(w),{read:P,write:k}=He({kit:l,files:[e,...D(n[0])?[n[0]]:[],...xe].filter(Boolean),home:y});Le(P,k);const f=he(e,n,{platform:"win32"}),E=await a.SandboxManager.wrapWithSandboxArgv(f,void 0,{filesystem:{denyRead:u.filesystem.denyRead,denyWrite:u.filesystem.denyWrite}},void 0,i,{commandId:h,commandText:f}),p=s?.env||process.env,v={...Pe({engine:o,home:y,env:p,base:process.env}),...V({},{platform:r,caBundle:m})},_=je(E.argv,v),b={};for(const[w,N]of Object.entries(E.env||{}))process.env[w]!==N&&(b[w]=N);return{bin:_[0],argv:_.slice(1),opts:{...s,env:{...p,...b},shell:!1},record:C,commandId:h}}return Ie({id:"srt",label:"Anthropic sandbox-runtime",async detect(){return await ke(),{ok:!!d,runtime:d,reason:c,ownSessions:!!(d&&(d==="srt-lib"&&(B??K(W))||r!=="win32"&&I())),...r==="win32"&&A!==null?{provisioned:A,...A?{}:{install:z}}:{}}},async wrap({kit:e,grant:n,bin:s,argv:o,opts:i,engine:l,workdir:u,commandId:h,caBundle:C=""}){const m=ue(e,{loopback:S,home:r==="linux"?y:"",platform:r}),D=he(s,o),P=Array.isArray(t.exactHosts),k=t.mode==="allowlist"&&n.hosts.length>0&&!P,f=m.network.allowUnixSockets||[],E=f.length>0&&!P;delete m.network.allowUnixSockets;const p=(k||E)&&d==="srt-lib"?B??K(W):"",v=k&&!p&&r!=="win32"?I():null,_=!!(p||v),b=Ne({layer:"process",runtime:p?"srt-host":v?"srt-cli":d,kitId:e.id,mode:e.network.mode,hosts:_||!k?n.hosts:[]});k&&!_&&(b.hostsDropped=n.hosts,te||(te=!0,L(`sandbox: hosts granted to ${l} (${n.hosts.join(", ")}) need a session of their own — no sandbox host or srt CLI here, so the process runs with the shared allow list`))),E&&!p?b.socketsDropped=f:E&&(b.sockets=f);try{if(p){const x=me(h),O={bin:s,argv:o,cwd:i?.cwd||null,engine:l,workdir:u,grant:n,commandId:h,config:{enabled:!0,mode:t.mode,extraHosts:[],extraWrite:t.extraWrite,extraDenyRead:t.extraDenyRead,windows:t.windows,exactHosts:e.network.allowedDomains,exactSockets:f,required:t.required||!1},loopback:S,srt:process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime",report:J?{url:J,token:x}:null},j={...i?.env||process.env};return{bin:process.execPath,argv:[p,$e(O)],opts:{...i,env:j,shell:!1},record:b,commandId:h}}if(v){const x={...i?.env||process.env};Object.assign(x,V(x,{platform:r,caBundle:C}));const O=ne(m,{hosts:n.hosts,sockets:f});return{bin:v.bin,argv:[...v.argv,"-s",pe(O.settings),"-c",D],opts:{...i,env:x,shell:!1},record:se(b,O,f),commandId:h}}if(d==="srt-lib"&&r==="win32")return{...await Re(s,o,i,{engine:l,workdir:u,kit:e,settings:m,commandId:h,record:b,caBundle:C})};if(d==="srt-lib"){await re();const x=await a.SandboxManager.wrapWithSandboxArgv(D,void 0,{filesystem:m.filesystem},void 0,u,{commandId:h,commandText:D}),O=i?.env||process.env,j={};for(const[oe,ie]of Object.entries(x.env||{}))process.env[oe]!==ie&&(j[oe]=ie);const F={...O,...j};return Object.assign(F,V(F,{platform:r,caBundle:C})),{bin:x.argv[0],argv:x.argv.slice(1),opts:{...i,env:F,shell:!1},record:b,commandId:h}}const w=I(),N=ne(m,{hosts:n.hosts,sockets:f});return{bin:w.bin,argv:[...w.argv,"-s",pe(N.settings),"-c",D],opts:{...i,shell:!1},record:se(b,N,f),commandId:h}}catch(w){return L(`sandbox: could not wrap ${s}: ${w.message}`),{passReason:w?.code==="SHAPE"?`the sandbox policy refused this run: ${w.message}`:`sandbox-runtime failed to wrap the command: ${w.message}`}}},violations(e){try{return a?.SandboxManager?.getSandboxViolationStore?.()?.getViolationsForCommand?.(e)||[]}catch{return[]}},close(){if(!(!R||!T.size)){try{a.revokeWindowsAcl({sandboxUserSid:R,srtWin:g})}catch(e){L(`sandbox: could not release the Windows grants: ${e.message}`)}T.clear()}}})}Fe("srt",t=>Je(t));export{Je as createSrtRuntime};
|
package/src/sandbox.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as ae}from"node:child_process";import"node:fs";import{randomBytes as ie}from"node:crypto";import{AsyncLocalStorage as ue}from"node:async_hooks";import{fileURLToPath as ce}from"node:url";import N from"node:os";import le from"node:path";import{ensureCaBundle as de}from"./ca-bundle.js";import{kitFor as pe,sandboxRecord as fe,normalizeGrant as P,writableRoots as xe,NETWORK_MODES as me}from"./events/sandbox-policy.js";import{createSandboxRuntime as he,sandboxRuntimeIds as we}from"./sandbox-runtime.js";import"./sandbox-srt.js";const V=new ue,Se=new Set(["codex","claude","antigravity","custom"]);function Ve(e,t){let n;try{n=P(e)}catch{n=null}return V.run(n,t)}function Ye(e){const t=e&&typeof e=="object"?e:{};if(!t.reach||t.reach==="any"||!t.sandbox||typeof t.sandbox!="object"||!("outside"in t.sandbox))return t;const{outside:n,...s}=t.sandbox;return{...t,sandbox:s}}function Y(){return V.getStore()||null}function ze(e,{config:t=te(),grant:n=Y(),home:s=N.homedir()}={}){try{return xe({grant:n,extraWrite:t.extraWrite,cwd:e,home:s})}catch{return[]}}const be=/deny network-outbound\s+(\S+?):(\d+)\s*(?:\((.*)\))?/;function z(e){const t=be.exec(String(e||""));return t?{host:t[1].toLowerCase(),port:Number(t[2])||0,reason:t[3]||""}:null}const g=new Map,R=[],O=new Map,Ae=new Set,ye=50;function J({commandId:e,host:t,port:n=0,reason:s="",at:a=Date.now()}){if(!e||!t)return;let o=g.get(e);for(o||(o=new Map,g.set(e,o)),o.set(t,{at:a,reason:s,port:n}),R.push({id:e,engine:O.get(e)||String(e).split(":")[0],host:t,at:a});R.length>ye;)R.shift()}function _e(e){const t=g.get(e);return t?[...t.entries()].sort((n,s)=>s[1].at-n[1].at).map(([n])=>n):[]}function Ne(e=20){return R.slice(-e).reverse()}function Je(){g.clear(),R.length=0,O.clear(),Ae.clear()}const q=new Map;function Q(e){const t=ie(16).toString("hex");return q.set(t,e),t}function qe(e={}){const t=q.get(String(e?.token||""));return!t||t!==e.commandId?!1:(J({commandId:t,host:String(e.host||"").toLowerCase().slice(0,253),port:Number(e.port)||0,reason:String(e.reason||"").slice(0,200)}),!0)}let Re=0;const Te=e=>`${e}:${(++Re).toString(36)}${Date.now().toString(36).slice(-4)}`,L=new Map;function Ee(e,t,{kind:n="agent",label:s=""}={}){if(!e||!t)return e;try{e.sandbox=t.record}catch{}if(typeof e.on!="function")return e;const a=t.commandId||"";L.set(e,{id:a,kind:n,engine:O.get(a)||String(a).split(":")[0]||"custom",command:t.label||"",label:s,pid:e.pid??null,since:Date.now(),sandbox:t.record});const o=()=>L.delete(e);return e.once("exit",o),e.once("error",o),e}function Qe(){return[...L.values()].map(e=>({...e,refused:_e(e.id)}))}function Ze(){L.clear()}function Z(e){if(e)return"";try{return ce(new URL("./sandbox-host.js",import.meta.url))}catch{return""}}const ee="open",et="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)",ge=()=>[Number(process.env.CHATPANEL_GATEWAY_PORT)||4320,Number(process.env.CHATPANEL_BRIDGE_PORT)||Number(process.env.PORT)||4319],W=e=>String(e||"").split(",").map(t=>t.trim()).filter(Boolean);function te(e=process.env){const t=String(e.CHATPANEL_SANDBOX||ee).toLowerCase(),n=t!=="off"&&t!=="0"&&t!=="false",s=me.includes(t)?t:ee;return{enabled:n,mode:s,extraHosts:W(e.CHATPANEL_SANDBOX_ALLOW_HOSTS),extraWrite:W(e.CHATPANEL_SANDBOX_ALLOW_WRITE),extraDenyRead:W(e.CHATPANEL_SANDBOX_DENY_READ),windows:e.CHATPANEL_SANDBOX_WINDOWS==="1",reads:e.CHATPANEL_SANDBOX_READS==="inverted"?"inverted":"enumerated"}}function Oe({config:e=te(),loadSrt:t=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:n=void 0,cliEntry:s=void 0,onRefusal:a=l=>J(l),reportUrl:o=process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT?`http://127.0.0.1:${process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT}/sandbox/refused`:"http://127.0.0.1:4319/sandbox/refused",hostEntry:p=null,compiled:u=!1,platform:i=process.platform,home:x=N.homedir(),loopback:$=ge(),selfFiles:B=[process.execPath,process.argv[1]||""],onExit:k=l=>process.on("exit",l),runtimeId:T=process.env.CHATPANEL_SANDBOX_RUNTIME||"srt",makeRuntime:M=null,log:m=()=>{}}={}){let l=null,E=null,d={ok:!1,runtime:null,reason:null,ownSessions:!1};function b(){if(l||E)return l;try{l=M?M({config:e,platform:i,home:x,loopback:$,compiled:u,selfFiles:B,onExit:k,hostEntry:p,reportUrl:o,mintReportToken:Q,onRefusal:a,parseRefusal:z,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:Z,log:m}):he(T,{config:e,platform:i,home:x,loopback:$,compiled:u,selfFiles:B,onExit:k,hostEntry:p,reportUrl:o,mintReportToken:Q,onRefusal:a,parseRefusal:z,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:Z,log:m})}catch(r){E=r?.message||String(r),m(`sandbox: ${E}`)}return l}async function X(){if(!e.enabled)return d={ok:!1,runtime:null,reason:"sandboxing is off (CHATPANEL_SANDBOX=off)",ownSessions:!1},d;const r=b();if(!r)return d={ok:!1,runtime:null,reason:E,ownSessions:!1},d;try{d={...d,...await r.detect()}}catch(c){d={ok:!1,runtime:null,reason:`the ${r.id} sandbox could not be started: ${c.message}`,ownSessions:!1}}return d}return{config:e,async status(){const r=await X(),c=b();return{enabled:e.enabled,mode:e.mode,runtime:r.runtime,platform:i,layer:c?.id||T,layers:we(),...r.reason?{reason:r.reason}:{},extras:{hosts:e.extraHosts,write:e.extraWrite,denyRead:e.extraDenyRead},ownSessions:!!r.ownSessions,refused:Ne(),...r.provisioned!==void 0?{provisioned:r.provisioned}:{},...r.install?{install:r.install}:{}}},close(){try{b()?.close()}catch(r){m(`sandbox: close failed: ${r.message}`)}},async wrap(r,c,A,{engine:f="custom",cwd:y=null,commandId:h=null,grant:F=Y(),readOnly:re=!1,peers:se=!0}={}){const G=await X();h=h||Te(f),O.set(h,f);const I=y||A?.cwd||process.cwd(),U=le.basename(String(r||"")),_=S=>({bin:r,argv:c,opts:A,record:fe({layer:"none",reason:S}),commandId:h,label:U});let j=!1;try{j=P(F).outside===!0}catch{}if(j&&Se.has(f))return _("you allowed this agent to run outside the ChatPanel sandbox (its own sandbox still applies)");if(!G.ok)return _(G.reason);const oe=await de({home:N.homedir(),log:m}).catch(()=>"");let K,D;try{D=P(F),K=pe({engine:f,cwd:I,mode:e.mode,extraHosts:e.extraHosts,extraWrite:[N.tmpdir(),...e.extraWrite],extraDenyRead:e.extraDenyRead,grant:D,home:N.homedir(),reads:e.reads,readOnly:re,peers:se})}catch(S){return _(`kit: ${S.message}`)}let w;try{w=await b().wrap({kit:K,grant:D,bin:r,argv:c,opts:A,engine:f,workdir:I,commandId:h,caBundle:oe})}catch(S){return m(`sandbox: could not wrap ${r}: ${S.message}`),_(`the ${T} sandbox failed to wrap the command: ${S.message}`)}return!w||w.passReason?_(w?.passReason||`the ${T} sandbox returned nothing`):{...w,commandId:w.commandId||h,label:U}},async wrapOwn(r,c,A,f={}){const y=await this.wrap(r,c(!1),A,f);return y.record.layer==="none"?{...y,argv:c(!0),inner:!0}:{...y,inner:!1}},violations(r){try{return b()?.violations(r)||[]}catch{return[]}}}}let C=null;function ne(){if(!C){const{isCompiledBinary:e}=Le();C=Oe({compiled:e(),log:t=>console.error(`[bridge] ${t}`)})}return C}function tt(e){C=e}let v=null;function Le(){return v||(v={isCompiledBinary:()=>{const e=(process.execPath||"").split(/[\\/]/).pop().toLowerCase();return!(e.startsWith("node")||e.startsWith("bun"))}}),v}const H=new Set;function nt(e,t){if(!t||t.layer!=="none"||typeof e!="function")return;const n=t.reason||"unknown";H.has(n)||(H.add(n),e({type:"status",text:`Running outside a sandbox — ${n}`}))}function rt(){H.clear()}const Ce=/sandbox_apply: Operation not permitted/;function st(e,t="This agent"){return Ce.test(String(e||""))?`${t} tried to start a sandbox of its own inside the ChatPanel sandbox, and macOS does not allow one inside another — so that tool could not run. To let it, turn on "Run outside the ChatPanel sandbox" in this agent's settings.`:null}async function ot(e,t,n,s={},{spawnImpl:a=ae,box:o=ne(),kind:p="agent",label:u=""}={}){const i=await o.wrap(e,t,n,s);return Ee(a(i.bin,i.argv,i.opts),i,{kind:p,label:u})}async function at(e,{box:t=ne(),platform:n=process.platform,loadSrt:s=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),out:a=console.log,err:o=console.error}={}){const p=e[0]||"status";if(p==="status")return a(JSON.stringify(await t.status(),null,2)),0;if(p!=="install")return o("usage: chatpanel-bridge sandbox [status|install]"),2;if(n!=="win32")return a("Nothing to install here: on macOS and Linux the sandbox runs as you. Only Windows has the one-time account setup."),0;let u;try{u=await s()}catch(i){return o(`sandbox-runtime is not installed — it ships with the gateway, so run \`chatpanel-gateway sandbox install\` (${i.message})`),1}try{const i=u.resolveSrtWin({path:u.VENDORED_SRT_WIN_EXE}),x=await u.installWindowsSandboxAsync({srtWin:i});return x?.cancelled?(o("Cancelled at the administrator prompt — nothing was installed."),1):(a(`The sandbox account is installed${x?.user?.sid?` (${x.user.sid})`:""}. Start the bridge with CHATPANEL_SANDBOX_WINDOWS=1; /health.sandbox says what the next run gets.`),0)}catch(i){o(`install failed: ${i.message}`);try{o(u.windowsInstallInstructions())}catch{}return 1}}export{Ze as _resetLiveForTest,rt as _resetNotedForTest,Je as _resetRefusalsForTest,tt as _setSandboxForTest,qe as acceptRefusalReport,Oe as createSandbox,Y as currentGrant,ze as grantedWriteRoots,Qe as liveProcesses,st as nestedSandboxLine,nt as noteSandbox,z as parseRefusalLine,Ne as recentRefusals,J as recordRefusal,_e as refusalsFor,at as runSandboxCli,ne as sandbox,te as sandboxConfigFromEnv,ot as sandboxedSpawn,Ee as track,Ve as withGrant,Ye as withoutOutsideWhenCapped};
|
|
1
|
+
import{spawn as me}from"node:child_process";import"node:fs";import{randomBytes as Ae}from"node:crypto";import{AsyncLocalStorage as we}from"node:async_hooks";import{fileURLToPath as Se}from"node:url";import N from"node:os";import ge from"node:path";import{ensureCaBundle as be}from"./ca-bundle.js";import{kitFor as Ne,validateKit as _e,sandboxRecord as Z,normalizeGrant as T,mergePersonGrants as ye,signInHosts as Ee,writableRoots as Te,NETWORK_MODES as ee}from"./events/sandbox-policy.js";import{awsSignIn as Oe}from"./aws-credentials.js";import{createSandboxRuntime as Re,sandboxRuntimeIds as Le}from"./sandbox-runtime.js";import{isCompiledBinary as De,hostFacts as Ce}from"./events/runtime-host.js";import"./sandbox-srt.js";import"./sandbox-command.js";const te=new we,ne=new Set(["codex","claude","antigravity","custom"]);function lt(e,t){let n;try{n=T(e)}catch{n=null}return te.run(n,t)}function pt(e){const t=e&&typeof e=="object"?e:{};if(!t.reach||t.reach==="any"||!t.sandbox||typeof t.sandbox!="object"||!("outside"in t.sandbox))return t;const{outside:n,...s}=t.sandbox;return{...t,sandbox:s}}function ft(e,t,{config:n=k().config}={}){const s=t&&typeof t=="object"?t:{},o=n?.agents?.[String(e||"")];if(!o||s.reach&&s.reach!=="any")return s;let a;try{a=ye(s.sandbox,o)}catch{a=T(o)}return{...s,sandbox:a}}function se(){return te.getStore()||null}function ht(e,{config:t=de(),grant:n=se(),home:s=N.homedir()}={}){try{return Te({grant:n,extraWrite:t.extraWrite,cwd:e,home:s})}catch{return[]}}const Pe=/deny network-outbound\s+(\S+?):(\d+)\s*(?:\((.*)\))?/;function re(e){const t=Pe.exec(String(e||""));return t?{host:t[1].toLowerCase(),port:Number(t[2])||0,reason:t[3]||""}:null}const B=new Map,O=[],v=new Map,$e=new Set,He=50;function oe({commandId:e,host:t,port:n=0,reason:s="",at:o=Date.now()}){if(!e||!t)return;let a=B.get(e);for(a||(a=new Map,B.set(e,a)),a.set(t,{at:o,reason:s,port:n}),O.push({id:e,engine:v.get(e)||String(e).split(":")[0],host:t,at:o});O.length>He;)O.shift()}function Be(e){const t=B.get(e);return t?[...t.entries()].sort((n,s)=>s[1].at-n[1].at).map(([n])=>n):[]}function ve(e=20){return O.slice(-e).reverse()}function xt(){B.clear(),O.length=0,v.clear(),$e.clear()}const ae=new Map;function ie(e){const t=Ae(16).toString("hex");return ae.set(t,e),t}function mt(e={}){const t=ae.get(String(e?.token||""));return!t||t!==e.commandId?!1:(oe({commandId:t,host:String(e.host||"").toLowerCase().slice(0,253),port:Number(e.port)||0,reason:String(e.reason||"").slice(0,200)}),!0)}let Ie=0;const We=e=>`${e}:${(++Ie).toString(36)}${Date.now().toString(36).slice(-4)}`,I=new Map;function Xe(e,t,{kind:n="agent",label:s=""}={}){if(!e||!t)return e;try{e.sandbox=t.record}catch{}if(typeof e.on!="function")return e;const o=t.commandId||"";I.set(e,{id:o,kind:n,engine:v.get(o)||String(o).split(":")[0]||"custom",command:t.label||"",label:s,pid:e.pid??null,since:Date.now(),sandbox:t.record});const a=()=>I.delete(e);return e.once("exit",a),e.once("error",a),e}function At(){return[...I.values()].map(e=>({...e,refused:Be(e.id)}))}function wt(){I.clear()}function ue(e){if(e)return"--sandbox-host";try{return Se(new URL("./sandbox-host.js",import.meta.url))}catch{return""}}const ce="open",St="run `chatpanel-bridge sandbox install` once (it asks for administrator approval)",ke=()=>[Number(process.env.CHATPANEL_GATEWAY_PORT)||4320,Number(process.env.CHATPANEL_BRIDGE_PORT)||Number(process.env.PORT)||4319],X=e=>String(e||"").split(",").map(t=>t.trim()).filter(Boolean),Ge=["off","0","false"];function Me(e,t){const n={};if(!e)return n;let s;try{s=JSON.parse(e)}catch{return t.push("CHATPANEL_SANDBOX_AGENTS is not JSON — no agent has settings of its own"),n}if(!s||typeof s!="object"||Array.isArray(s))return t.push("CHATPANEL_SANDBOX_AGENTS must be an object keyed by agent id — no agent has settings of its own"),n;for(const[o,a]of Object.entries(s))try{n[o]=T(a)}catch(f){t.push(`sandbox settings for agent "${o}" are not valid and were left out — ${f.message}`)}return n}function de(e=process.env){const t=String(e.CHATPANEL_SANDBOX||ce).toLowerCase(),n=!Ge.includes(t),s=ee.includes(t)?t:ce,o=[];return n&&!ee.includes(t)&&o.push(`CHATPANEL_SANDBOX="${t}" is not one of open, allowlist, off — the sandbox stays on, in "open" mode`),{enabled:n,mode:s,agents:Me(e.CHATPANEL_SANDBOX_AGENTS,o),warnings:o,extraHosts:X(e.CHATPANEL_SANDBOX_ALLOW_HOSTS),extraWrite:X(e.CHATPANEL_SANDBOX_ALLOW_WRITE),extraDenyRead:X(e.CHATPANEL_SANDBOX_DENY_READ),windows:e.CHATPANEL_SANDBOX_WINDOWS==="1",reads:e.CHATPANEL_SANDBOX_READS==="inverted"?"inverted":"enumerated",command:String(e.CHATPANEL_SANDBOX_COMMAND||""),image:String(e.CHATPANEL_SANDBOX_IMAGE||""),engine:["podman","docker"].includes(e.CHATPANEL_SANDBOX_ENGINE)?e.CHATPANEL_SANDBOX_ENGINE:"",required:["policy"].includes(String(e.CHATPANEL_SANDBOX_REQUIRED||"").toLowerCase())?"policy":["1","on","true","yes"].includes(String(e.CHATPANEL_SANDBOX_REQUIRED||"").toLowerCase())?"on":!1}}function Fe({config:e=de(),loadSrt:t=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),cliPresent:n=void 0,cliEntry:s=void 0,onRefusal:o=x=>oe(x),reportUrl:a=process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT?`http://127.0.0.1:${process.env.CHATPANEL_BRIDGE_PORT||process.env.PORT}/sandbox/refused`:"http://127.0.0.1:4319/sandbox/refused",hostEntry:f=null,compiled:d=!1,platform:u=process.platform,home:S=N.homedir(),loopback:M=ke(),selfFiles:F=[process.execPath,process.argv[1]||""],onExit:j=x=>process.on("exit",x),runtimeId:D=process.env.CHATPANEL_SANDBOX_RUNTIME||"srt",makeRuntime:q=null,signInAws:le=Oe,srtOnDisk:C=void 0,now:P=void 0,log:h=()=>{}}={}){let x=null,$=null,m={ok:!1,runtime:null,reason:null,ownSessions:!1};function _(){if(x||$)return x;try{x=q?q({config:e,platform:u,home:S,loopback:M,compiled:d,selfFiles:F,onExit:j,hostEntry:f,reportUrl:a,mintReportToken:ie,onRefusal:o,parseRefusal:re,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:ue,...C?{onDisk:C}:{},...P?{now:P}:{},log:h}):Re(D,{config:e,platform:u,home:S,loopback:M,compiled:d,selfFiles:F,onExit:j,hostEntry:f,reportUrl:a,mintReportToken:ie,onRefusal:o,parseRefusal:re,loadSrt:t,...n?{cliPresent:n}:{},...s!==void 0?{cliEntry:s}:{},hostEntryFor:ue,...C?{onDisk:C}:{},...P?{now:P}:{},log:h})}catch(r){$=r?.message||String(r),h(`sandbox: ${$}`)}return x}async function U(){if(!e.enabled)return m={ok:!1,runtime:null,reason:"sandboxing is off (CHATPANEL_SANDBOX=off)",ownSessions:!1},m;const r=_();if(!r)return m={ok:!1,runtime:null,reason:$,ownSessions:!1},m;try{m={...m,...await r.detect()}}catch(l){m={ok:!1,runtime:null,reason:`the ${r.id} sandbox could not be started: ${l.message}`,ownSessions:!1}}return m}return{config:e,async status(){const r=await U(),l=_();return{enabled:e.enabled,mode:e.mode,runtime:r.runtime,platform:u,...e.required?{required:e.required}:{},layer:l?.id||D,layers:Le(),...r.reason?{reason:r.reason}:{},extras:{hosts:e.extraHosts,write:e.extraWrite,denyRead:e.extraDenyRead},...e.agents&&Object.keys(e.agents).length?{agents:e.agents}:{},...e.warnings?.length?{warnings:e.warnings}:{},...r.runtime==="srt-cli"&&e.mode==="open"?{narrowed:'This install runs agents through the `srt` command, which cannot allow every public host: each agent reaches its own service, the developer hosts, the hosts you add here and its sign-ins\' — nothing else. Installing the gateway with npm runs "open" as it says.'}:{},ownSessions:!!r.ownSessions,refused:ve(),...r.provisioned!==void 0?{provisioned:r.provisioned}:{},...r.install?{install:r.install}:{}}},close(){try{_()?.close()}catch(r){h(`sandbox: close failed: ${r.message}`)}},async wrap(r,l,g,{engine:p="custom",cwd:y=null,commandId:w=null,grant:J=se(),readOnly:pe=!1,peers:fe=!0,kit:K=null}={}){const Y=await U();w=w||We(p),v.set(w,p);const Q=y||g?.cwd||process.cwd(),E=ge.basename(String(r||"")),H=i=>{if(e.required)throw Object.assign(new Error(`The sandbox is required on this computer and could not be applied to ${E||"this process"} — ${i}. Nothing was run.`),{code:"sandbox_required",reason:i});return{bin:r,argv:l,opts:g,record:Z({layer:"none",reason:i}),commandId:w,label:E}},he=i=>{if(e.required==="policy")throw Object.assign(new Error(`Your organisation requires the sandbox, so ${E||"this agent"} cannot run outside it. Nothing was run.`),{code:"sandbox_required",reason:i});return{bin:r,argv:l,opts:g,record:Z({layer:"none",reason:i}),commandId:w,label:E}};let V=!1;try{V=T(J).outside===!0}catch{}if(V&&ne.has(p))return he("you allowed this agent to run outside the ChatPanel sandbox (its own sandbox still applies)");if(!Y.ok)return H(Y.reason);const xe=await be({home:N.homedir(),log:h}).catch(()=>"");let z,c;try{if(c=T(J),c.signIn&&!ne.has(p)){const{signIn:i,...W}=c;c=W}c.signIn&&(c={...c,hosts:[...new Set([...c.hosts,...Ee(c)])]}),z=K?_e(K):Ne({engine:p,cwd:Q,mode:e.mode,extraHosts:e.extraHosts,extraWrite:[N.tmpdir(),...e.extraWrite],extraDenyRead:e.extraDenyRead,grant:c,home:N.homedir(),reads:e.reads,readOnly:pe,peers:fe})}catch(i){return H(`kit: ${i.message}`)}let b;try{b=await _().wrap({kit:z,grant:c,bin:r,argv:l,opts:g,engine:p,workdir:Q,commandId:w,caBundle:xe})}catch(i){return h(`sandbox: could not wrap ${r}: ${i.message}`),H(`the ${D} sandbox failed to wrap the command: ${i.message}`)}if(!b||b.passReason)return H(b?.passReason||`the ${D} sandbox returned nothing`);const A={...b,commandId:b.commandId||w,label:E};if(c.signIn&&(A.record.signIn=c.signIn,c.signIn.includes("aws"))){const i=await le({env:A.opts?.env||process.env,engine:p,home:N.homedir()}).catch(W=>({failed:`AWS sign-in: ${W.message}`}));i?.env?(A.opts={...A.opts,env:{...A.opts?.env||process.env,...i.env}},i.expiresAt&&(A.expiresAt=i.expiresAt),h(`sandbox: ${p} is signed in to AWS with profile "${i.profile}" — its credential_process ran outside the sandbox${i.expiresAt?`, good until ${new Date(i.expiresAt).toISOString()}`:""}`)):i?.failed&&(A.record.signInNote=i.failed,h(`sandbox: ${i.failed}`))}return A},async wrapOwn(r,l,g,p={}){const y=await this.wrap(r,l(!1),g,p);return y.record.layer==="none"?{...y,argv:l(!0),inner:!0}:{...y,inner:!1}},violations(r){try{return _()?.violations(r)||[]}catch{return[]}}}}let R=null;function k(){if(!R){const{isCompiledBinary:e}=je();R=Fe({compiled:e(),log:t=>console.error(`[bridge] ${t}`)});for(const t of R.config.warnings||[])console.error(`[bridge] sandbox: ${t}`)}return R}function gt(e){R=e}let G=null;function je(){return G||(G={isCompiledBinary:()=>De(Ce())}),G}const L=new Set;function bt(e,t){if(!t||typeof e!="function"||(t.signInNote&&!L.has(t.signInNote)&&(L.add(t.signInNote),e({type:"status",text:t.signInNote})),t.layer!=="none"))return;const n=t.reason||"unknown";L.has(n)||(L.add(n),e({type:"status",text:`Running outside a sandbox — ${n}`}))}function Nt(){L.clear()}const qe=/sandbox_apply: Operation not permitted/;function _t(e,t="This agent"){return qe.test(String(e||""))?`${t} tried to start a sandbox of its own inside the ChatPanel sandbox, and macOS does not allow one inside another — so that tool could not run. To let it, turn on "Run outside the ChatPanel sandbox" in this agent's settings.`:null}async function yt(e,t,n,s={},{spawnImpl:o=me,box:a=k(),kind:f="agent",label:d=""}={}){const u=await a.wrap(e,t,n,s);return Xe(o(u.bin,u.argv,u.opts),u,{kind:f,label:d})}async function Et(e,{box:t=k(),platform:n=process.platform,loadSrt:s=()=>import(process.env.CHATPANEL_SRT_MODULE||"@anthropic-ai/sandbox-runtime"),out:o=console.log,err:a=console.error}={}){const f=e[0]||"status";if(f==="status")return o(JSON.stringify(await t.status(),null,2)),0;if(f!=="install")return a("usage: chatpanel-bridge sandbox [status|install]"),2;if(n!=="win32")return o("Nothing to install here: on macOS and Linux the sandbox runs as you. Only Windows has the one-time account setup."),0;let d;try{d=await s()}catch(u){return a(`sandbox-runtime is not installed — it ships with the gateway, so run \`chatpanel-gateway sandbox install\` (${u.message})`),1}try{const u=d.resolveSrtWin({path:d.VENDORED_SRT_WIN_EXE}),S=await d.installWindowsSandboxAsync({srtWin:u});return S?.cancelled?(a("Cancelled at the administrator prompt — nothing was installed."),1):(o(`The sandbox account is installed${S?.user?.sid?` (${S.user.sid})`:""}. Start the bridge with CHATPANEL_SANDBOX_WINDOWS=1; /health.sandbox says what the next run gets.`),0)}catch(u){a(`install failed: ${u.message}`);try{a(d.windowsInstallInstructions())}catch{}return 1}}export{wt as _resetLiveForTest,Nt as _resetNotedForTest,xt as _resetRefusalsForTest,gt as _setSandboxForTest,mt as acceptRefusalReport,Fe as createSandbox,se as currentGrant,ht as grantedWriteRoots,At as liveProcesses,_t as nestedSandboxLine,bt as noteSandbox,re as parseRefusalLine,ve as recentRefusals,oe as recordRefusal,Be as refusalsFor,Et as runSandboxCli,k as sandbox,de as sandboxConfigFromEnv,yt as sandboxedSpawn,Xe as track,ft as withAgentGrant,lt as withGrant,pt as withoutOutsideWhenCapped};
|