@remoteshell/device 0.0.0-stage → 0.1.0-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +26 -0
- package/NOTICE +20 -0
- package/bin/dev-agent-client.mjs +228 -0
- package/bin/dev-agent-runner.mjs +60 -0
- package/bin/dev-api-client.mjs +31 -0
- package/bin/dev-auto-worker.mjs +25 -0
- package/bin/dev-browser-open.mjs +12 -0
- package/bin/dev-dogfood-read.mjs +3 -0
- package/bin/dev-heartbeat-service.mjs +77 -0
- package/bin/dev-pairing-client.mjs +63 -0
- package/bin/dev-secrets.mjs +33 -0
- package/bin/dev-setup-recovery.mjs +34 -0
- package/bin/dev-signer-pin.mjs +22 -0
- package/bin/device.mjs +384 -0
- package/bin/direct-npx-runtime.mjs +150 -0
- package/bin/enrollment-client.mjs +105 -0
- package/bin/install-acquire.mjs +89 -0
- package/bin/install-integrity.mjs +74 -0
- package/bin/install-plan.mjs +43 -0
- package/bin/lifecycle.mjs +172 -0
- package/bin/native-path-contract.mjs +23 -0
- package/bin/remoteshell-device-install.cmd +17 -0
- package/bin/remoteshell-device-install.ps1 +17 -0
- package/bin/remoteshell-device-install.sh +15 -0
- package/bin/remoteshell-device-preflight.cmd +10 -0
- package/bin/remoteshell-device-preflight.ps1 +10 -0
- package/bin/remoteshell-easy-diagnose.ps1 +32 -0
- package/bin/remoteshell-easy-install.ps1 +292 -0
- package/bin/remoteshell-easy-install.sh +71 -0
- package/bin/remoteshell-easy-uninstall.ps1 +128 -0
- package/bin/windows-acl-wmi-client.mjs +50 -0
- package/bin/windows-acl-wmi.js +43 -0
- package/bin/windows-credential-boundary.mjs +113 -0
- package/bin/windows-direct-autostart-runner.mjs +50 -0
- package/bin/windows-direct-autostart.mjs +110 -0
- package/bin/windows-install-layout.mjs +28 -0
- package/bin/windows-native-installer.mjs +91 -0
- package/bin/windows-private-store.mjs +176 -0
- package/bin/windows-user-lifecycle.mjs +34 -0
- package/npm-shrinkwrap.json +8591 -0
- package/package.json +27 -4
- package/shared/lib/bounded-search-contract.mjs +5 -0
- package/shared/lib/bounded-search-policy.mjs +24 -0
- package/shared/lib/config.mjs +14 -0
- package/shared/lib/contracts.mjs +26 -0
- package/shared/lib/dc-generic-policy.mjs +102 -0
- package/shared/lib/dc-relay-contract.mjs +42 -0
- package/shared/lib/dc-tool-catalog.mjs +67 -0
- package/shared/lib/dev-dc-relay-contract.mjs +20 -0
- package/shared/lib/dev-paged-output.mjs +32 -0
- package/shared/lib/dev-root-exclusions.mjs +56 -0
- package/shared/lib/errors.mjs +9 -0
- package/shared/lib/events.mjs +5 -0
- package/shared/lib/execution-policy.mjs +41 -0
- package/shared/lib/isolated-read-boundary.mjs +50 -0
- package/shared/lib/isolated-read-policy.mjs +29 -0
- package/shared/lib/lifecycle-events.mjs +13 -0
- package/shared/lib/runtime-timing.mjs +9 -0
- package/shared/lib/synthetic-auxiliary-policy.mjs +21 -0
- package/shared/lib/synthetic-write-policy.mjs +52 -0
- package/shared/lib/tool-registry.mjs +58 -0
- package/src/config/l2-dev-oci-credential.mjs +39 -0
- package/src/config/p2-private-credential.mjs +15 -0
- package/src/connection/dev-dogfood-processes.mjs +25 -0
- package/src/connection/dev-dogfood-read.mjs +64 -0
- package/src/connection/dev-dogfood-task.mjs +113 -0
- package/src/connection/dev-dogfood-write.mjs +62 -0
- package/src/connection/dev-file-task.mjs +119 -0
- package/src/connection/dev-r4-file-task.mjs +56 -0
- package/src/connection/dev-read-tools.mjs +134 -0
- package/src/connection/dev-root-scopes.mjs +82 -0
- package/src/core/c1-dc-transport.mjs +26 -0
- package/src/core/c1-startup.mjs +22 -0
- package/src/core/c1-supervisor.mjs +111 -0
- package/src/core/c1-worker.mjs +88 -0
- package/src/core/fixture.txt +2 -0
- package/src/dc/dc-access-readiness.mjs +31 -0
- package/src/dc/dev-dc-relay.mjs +47 -0
- package/src/device-agent/main.mjs +1 -0
- package/src/gateway-keepalive.mjs +73 -0
- package/src/main.mjs +436 -0
- package/src/policy/bounded-search-adapter.mjs +115 -0
- package/src/policy/isolated-read-adapter.mjs +50 -0
- package/src/policy/isolated-read-mount.mjs +27 -0
- package/src/policy/synthetic-auxiliary-adapter.mjs +75 -0
- package/src/policy/synthetic-file-adapter.mjs +26 -0
- package/src/policy/synthetic-file-transaction.mjs +87 -0
- package/src/policy/synthetic-write-adapter.mjs +151 -0
- package/src/policy/synthetic-write-mount.mjs +23 -0
- package/src/policy/verified-bounded-search.mjs +12 -0
- package/src/policy/verified-isolated-read.mjs +15 -0
- package/src/policy/verified-synthetic-write.mjs +14 -0
- package/README.md +0 -3
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// Only the authenticated R4 Gateway session may deliver this envelope.
|
|
2
|
+
// Caller-supplied R3 tool grants alone cannot produce r4_authorization.
|
|
3
|
+
import {createHash} from 'node:crypto';
|
|
4
|
+
import {readFileSync,lstatSync,realpathSync} from 'node:fs';
|
|
5
|
+
import {resolve} from 'node:path';
|
|
6
|
+
import {executeDevDogfoodWrite} from './dev-dogfood-write.mjs';
|
|
7
|
+
const ROOT='016ce9ca-6f3e-4454-8efe-a9447f00a7a2';
|
|
8
|
+
const FILE='device-agent/tests/device-dev/device-dev-dogfood-read.test.mjs';
|
|
9
|
+
const BASE='e6bbb11aef6f90209a735395384e9ae77cc353ab3cb6df7a51f43d1dea827499';
|
|
10
|
+
const uuid=x=>typeof x==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(x);
|
|
11
|
+
const sha=x=>createHash('sha256').update(x).digest('hex');
|
|
12
|
+
const deny=()=>{throw Error('DEV_R4_FILE_DENIED');};
|
|
13
|
+
const states=new Map();
|
|
14
|
+
export function validateR4AgentTool(tool,{rootId,now=Date.now(),deviceId,sessionId}={}){
|
|
15
|
+
const a=tool?.arguments,auth=a?.r4_authorization,name=tool?.name;
|
|
16
|
+
if(!a||!auth||Object.getPrototypeOf(auth)!==Object.prototype||
|
|
17
|
+
a.root_id!==ROOT||rootId!==ROOT||a.path!==FILE||
|
|
18
|
+
!uuid(deviceId)||!uuid(sessionId)||!uuid(auth.owner_user_id)||!uuid(auth.connection_id)||
|
|
19
|
+
!uuid(auth.consent_id)||auth.device_id!==deviceId||
|
|
20
|
+
auth.contract_version!=='dev-l4-file-v1'||auth.baseline_sha256!==BASE||
|
|
21
|
+
!Number.isSafeInteger(auth.expires_at)||auth.expires_at<=now||
|
|
22
|
+
!Number.isSafeInteger(auth.credential_version)||!Number.isSafeInteger(auth.grant_version)||
|
|
23
|
+
!['edit_block','node_test'].includes(auth.tool_id)||
|
|
24
|
+
(auth.tool_id==='edit_block'?name!=='edit_block':name!=='start_process'||a.command!=='node_test'))deny();
|
|
25
|
+
const required=['root_id','path','r4_authorization',...(name==='edit_block'?
|
|
26
|
+
['expectedHash','old_string','new_string']:['command'])];
|
|
27
|
+
if(Object.keys(a).sort().join(',')!==required.sort().join(','))deny();
|
|
28
|
+
if(name==='edit_block'&&(!/^[a-f0-9]{64}$/.test(a.expectedHash||'')||
|
|
29
|
+
typeof a.old_string!=='string'||!a.old_string.length||a.old_string.length>32768||
|
|
30
|
+
typeof a.new_string!=='string'||a.new_string.length>32768))deny();
|
|
31
|
+
const fields=['contract_version','consent_id','baseline_sha256','expires_at','tool_id',
|
|
32
|
+
'owner_user_id','connection_id','device_id','credential_version','grant_version'];
|
|
33
|
+
if(Object.keys(auth).sort().join(',')!==fields.sort().join(','))deny();
|
|
34
|
+
const {r4_authorization:ignored,...args}=a;
|
|
35
|
+
return Object.freeze({name,arguments:args});
|
|
36
|
+
}
|
|
37
|
+
export async function executeR4AgentTool({tool,root,rootId,client,deviceId,sessionId,processes}={}){
|
|
38
|
+
const sanitized=validateR4AgentTool(tool,{rootId,deviceId,sessionId});
|
|
39
|
+
const auth=tool.arguments.r4_authorization;
|
|
40
|
+
if(typeof root!=='string'||!root.startsWith('/')||resolve(root)!==root)deny();
|
|
41
|
+
const target=resolve(root,FILE);
|
|
42
|
+
const st=lstatSync(target);
|
|
43
|
+
if(!st.isFile()||st.isSymbolicLink()||st.nlink!==1||realpathSync(target)!==target)deny();
|
|
44
|
+
if(sanitized.name==='start_process'){
|
|
45
|
+
// The process adapter enforces canonical source path and shell:false.
|
|
46
|
+
return JSON.stringify(processes.start({root,deviceId,sessionId,tool:sanitized}));
|
|
47
|
+
}
|
|
48
|
+
const key=auth.consent_id+':'+deviceId+':'+sessionId;
|
|
49
|
+
const current=sha(readFileSync(target)),previous=states.get(key)||BASE;
|
|
50
|
+
if(current!==previous||current!==sanitized.arguments.expectedHash)deny();
|
|
51
|
+
const result=JSON.parse(await executeDevDogfoodWrite({root,tool:sanitized,client}));
|
|
52
|
+
if(result.edited!==true||result.previous_sha256!==current||
|
|
53
|
+
!/^[a-f0-9]{64}$/.test(result.sha256||''))deny();
|
|
54
|
+
if(result.sha256===BASE)states.delete(key);else states.set(key,result.sha256);
|
|
55
|
+
return JSON.stringify(result);
|
|
56
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import {validPageArgs,boundedSnapshotPage} from '../../shared/lib/dev-paged-output.mjs';
|
|
2
|
+
import {excludedPath,assertAllowedPath} from '../../shared/lib/dev-root-exclusions.mjs';
|
|
3
|
+
// P2-10 readonly developer tools, limited to the already owner-approved DEV root.
|
|
4
|
+
// No command strings from MCP callers and no Git writes.
|
|
5
|
+
import {lstatSync,realpathSync,readFileSync,readdirSync} from 'node:fs';
|
|
6
|
+
import {join,relative,resolve,sep} from 'node:path';
|
|
7
|
+
import {execFile} from 'node:child_process';
|
|
8
|
+
import {promisify} from 'node:util';
|
|
9
|
+
const execFileAsync=promisify(execFile);
|
|
10
|
+
const DENY=()=>{throw Error('DEV_READ_TOOL_DENIED');};
|
|
11
|
+
const pathOk=p=>typeof p==='string'&&p.length<=256&&p.length>0&&
|
|
12
|
+
(p==='.'||/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(p))&&!p.split('/').includes('..');
|
|
13
|
+
function rootOf(root){
|
|
14
|
+
if(typeof root!=='string'||!root.startsWith('/')||resolve(root)!==root||root==='/'||realpathSync(root)!==root)DENY();
|
|
15
|
+
const st=lstatSync(root);if(!st.isDirectory()||st.isSymbolicLink()||st.uid!==process.getuid?.())DENY();
|
|
16
|
+
return root;
|
|
17
|
+
}
|
|
18
|
+
function inside(root,name,{mayNotExist=false}={}){
|
|
19
|
+
if(!pathOk(name))DENY();
|
|
20
|
+
const dest=resolve(root,name),rel=relative(root,dest);
|
|
21
|
+
if(rel==='..'||rel.startsWith('..'+sep)||rel.startsWith('/'))DENY();
|
|
22
|
+
let at=root;for(const component of name.split('/')){
|
|
23
|
+
if(component==='.')continue;
|
|
24
|
+
at=join(at,component);
|
|
25
|
+
let st;try{st=lstatSync(at);}catch(e){if(mayNotExist&&e.code==='ENOENT')return dest;DENY();}
|
|
26
|
+
if(st.isSymbolicLink()||(!st.isFile()&&!st.isDirectory()))DENY();
|
|
27
|
+
}
|
|
28
|
+
return dest;
|
|
29
|
+
}
|
|
30
|
+
async function git(root,args){
|
|
31
|
+
try{return (await execFileAsync('git',args,{cwd:root,timeout:2500,maxBuffer:1024*1024,
|
|
32
|
+
env:{PATH:process.env.PATH||'/usr/bin:/bin',HOME:process.env.HOME||'/tmp',LANG:'C',
|
|
33
|
+
GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:'/dev/null',GIT_NO_REPLACE_OBJECTS:'1',
|
|
34
|
+
GIT_OPTIONAL_LOCKS:'0',GIT_TERMINAL_PROMPT:'0'}})).stdout;}
|
|
35
|
+
catch{DENY();}
|
|
36
|
+
}
|
|
37
|
+
async function repo(worktree){
|
|
38
|
+
const top=(await git(worktree,['rev-parse','--show-toplevel'])).trim();
|
|
39
|
+
if(top!==worktree)DENY(); // A subdirectory inside a repository is not its worktree root.
|
|
40
|
+
const dotgit=join(worktree,'.git');
|
|
41
|
+
const st=lstatSync(dotgit);
|
|
42
|
+
if(st.isSymbolicLink()||!st.isDirectory()&&!st.isFile())DENY();
|
|
43
|
+
return worktree;
|
|
44
|
+
}
|
|
45
|
+
// Bound actual UTF-8 bytes, not JS characters. Preserve complete code points.
|
|
46
|
+
const bounded=(value,max=12000)=>{
|
|
47
|
+
const data=Buffer.from(value,'utf8');
|
|
48
|
+
if(data.length<=max)return {text:value,truncated:false};
|
|
49
|
+
let end=max;
|
|
50
|
+
while(end>0&&(data[end]&0xc0)===0x80)end--;
|
|
51
|
+
if(!end)DENY();
|
|
52
|
+
return {text:data.subarray(0,end).toString('utf8'),truncated:true};
|
|
53
|
+
};
|
|
54
|
+
const ext=/\.(?:mjs|js|cjs|ts|tsx|jsx|json|md|txt|yaml|yml|css|html|py|sh|toml|sql)$/i;
|
|
55
|
+
export async function devReadTools({root,name,path='.',query,regex=false,limit=50,offset=0,file,exclusion_policy,page}={}){
|
|
56
|
+
const base=rootOf(root);
|
|
57
|
+
if(exclusion_policy)assertAllowedPath(path,exclusion_policy);
|
|
58
|
+
if(!['search_content','git_status','git_diff'].includes(name))DENY();
|
|
59
|
+
if(name==='search_content'){
|
|
60
|
+
if(!pathOk(path)||typeof query!=='string'||query.length<1||query.length>128||/[\x00-\x1f\x7f]/.test(query)||
|
|
61
|
+
typeof regex!=='boolean'||!Number.isInteger(limit)||limit<1||limit>100||
|
|
62
|
+
!Number.isInteger(offset)||offset<0||offset>10000)DENY();
|
|
63
|
+
const target=inside(base,path);let pattern;
|
|
64
|
+
if(regex){
|
|
65
|
+
// Disallow backreferences, assertions and nested/stacked quantifiers.
|
|
66
|
+
if(/[\\][1-9]|\(\?[=!<]|\([^)]*[+*{][^)]*\)[+*{]|[+*?][+*?{]/.test(query))DENY();
|
|
67
|
+
try{pattern=new RegExp(query,'u');}catch{DENY();}
|
|
68
|
+
}
|
|
69
|
+
const search=x=>regex?(pattern.lastIndex=0,pattern.test(x)):x.includes(query);
|
|
70
|
+
const pending=[target],matches=[];let scanned=0,seen=0,bytes=0,truncated=false;
|
|
71
|
+
const start=Date.now();
|
|
72
|
+
while(pending.length){
|
|
73
|
+
if(Date.now()-start>1200||scanned>=350||bytes>=2_000_000){truncated=true;break;}
|
|
74
|
+
const current=pending.pop();
|
|
75
|
+
if(exclusion_policy&&excludedPath(relative(base,current)||'.',exclusion_policy))continue;
|
|
76
|
+
const st=lstatSync(current);
|
|
77
|
+
if(st.isDirectory()){
|
|
78
|
+
if(relative(base,current).split(sep).length>8)continue;
|
|
79
|
+
const entries=readdirSync(current,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name));
|
|
80
|
+
for(let i=entries.length-1;i>=0;i--){
|
|
81
|
+
const e=entries[i];
|
|
82
|
+
if(exclusion_policy&&excludedPath(relative(base,join(current,e.name)),exclusion_policy))continue;
|
|
83
|
+
if(e.isSymbolicLink()||!e.isDirectory()&&!e.isFile()||['.git','node_modules','dist','.next','coverage'].includes(e.name))continue;
|
|
84
|
+
pending.push(join(current,e.name));
|
|
85
|
+
}
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if(!st.isFile()||!ext.test(current)||st.size>65536)continue;
|
|
89
|
+
scanned++;bytes+=st.size;
|
|
90
|
+
const lines=readFileSync(current,'utf8').split('\n');
|
|
91
|
+
for(let index=0;index<lines.length;index++){
|
|
92
|
+
const line=lines[index];if(!search(line))continue;
|
|
93
|
+
if(seen++<offset)continue;
|
|
94
|
+
if(matches.length>=limit){truncated=true;break;}
|
|
95
|
+
matches.push({file:relative(base,current),line:index+1,text:line.slice(0,240)});
|
|
96
|
+
}
|
|
97
|
+
if(truncated)break;
|
|
98
|
+
}
|
|
99
|
+
return {matches,count:matches.length,offset,next_offset:truncated?offset+matches.length:null,
|
|
100
|
+
scanned,truncated:truncated||pending.length>0};
|
|
101
|
+
}
|
|
102
|
+
// 'path' chooses a nested repository under the already approved root.
|
|
103
|
+
// Its own .git must be inside that directory; the parent grant is not replaced.
|
|
104
|
+
const worktree=inside(base,path);
|
|
105
|
+
if(!lstatSync(worktree).isDirectory())DENY();
|
|
106
|
+
await repo(worktree);
|
|
107
|
+
if(name==='git_status'){
|
|
108
|
+
if(file!==undefined)DENY();
|
|
109
|
+
const raw=await git(worktree,['status','--short','--untracked-files=all','--no-renames']);
|
|
110
|
+
const status=exclusion_policy?raw.split('\n').filter(line=>{
|
|
111
|
+
if(!line)return false;
|
|
112
|
+
const filePath=line.slice(3).replace(/^"|"$/g,'');
|
|
113
|
+
return !excludedPath(path==='.'?filePath:path+'/'+filePath,exclusion_policy);
|
|
114
|
+
}).join('\n'):raw;
|
|
115
|
+
const b=bounded(status);
|
|
116
|
+
return {status:b.text,truncated:b.truncated};
|
|
117
|
+
}
|
|
118
|
+
if(file!==undefined){inside(worktree,file,{mayNotExist:true});
|
|
119
|
+
if(exclusion_policy)assertAllowedPath(path==='.'?file:path+'/'+file,exclusion_policy);}
|
|
120
|
+
const args=['diff','--no-ext-diff','--no-textconv','--no-color','--unified=3'];
|
|
121
|
+
if(file!==undefined)args.push('--',file);
|
|
122
|
+
const raw=await git(worktree,args);
|
|
123
|
+
// Parse patch sections before bounding; excluded paths are never returned.
|
|
124
|
+
const filtered=exclusion_policy?raw.split(/(?=^diff --git )/m).filter(chunk=>{
|
|
125
|
+
if(!chunk.trim())return false;
|
|
126
|
+
const head=chunk.split('\n',1)[0],m=/^diff --git a\/(.*?) b\/(.*?)$/.exec(head);
|
|
127
|
+
if(!m)DENY();
|
|
128
|
+
return ![m[1],m[2]].some(f=>excludedPath(path==='.'?f:path+'/'+f,exclusion_policy));
|
|
129
|
+
}).join(''):raw;
|
|
130
|
+
if(page){const {text,...meta}=boundedSnapshotPage(filtered,page,exclusion_policy??0);
|
|
131
|
+
return {diff:text,...meta};}
|
|
132
|
+
const b=bounded(filtered);
|
|
133
|
+
return {diff:b.text,truncated:b.truncated};
|
|
134
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// P2-14 device-observed root scopes. Discovery is metadata, never an access grant.
|
|
2
|
+
import {createHash} from 'node:crypto';
|
|
3
|
+
import {devDogfoodTaskEnvelope} from './dev-dogfood-task.mjs';
|
|
4
|
+
import {isDcPublic} from '../../shared/lib/dc-generic-policy.mjs';
|
|
5
|
+
import {homedir} from 'node:os';
|
|
6
|
+
import {lstatSync,realpathSync,readdirSync,accessSync,constants} from 'node:fs';
|
|
7
|
+
import {resolve,join,relative,isAbsolute,sep} from 'node:path';
|
|
8
|
+
const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
9
|
+
const safeDir=p=>{
|
|
10
|
+
try{
|
|
11
|
+
if(!isAbsolute(p)||resolve(p)!==p||realpathSync(p)!==p)return false;
|
|
12
|
+
const stat=lstatSync(p);
|
|
13
|
+
if(!stat.isDirectory()||stat.isSymbolicLink()||
|
|
14
|
+
typeof process.getuid==='function'&&stat.uid!==process.getuid())return false;
|
|
15
|
+
accessSync(p,constants.R_OK|constants.X_OK);return true;
|
|
16
|
+
}catch{return false;}
|
|
17
|
+
};
|
|
18
|
+
export function scopeIdFor({deviceId,path}={}){
|
|
19
|
+
if(!UUID.test(deviceId||'')||!isAbsolute(path||'')||resolve(path)!==path)throw Error('ROOT_SCOPE_INVALID');
|
|
20
|
+
const hex=createHash('sha256').update('remoteshell-root-scope-v1\0').update(deviceId).update('\0').update(path).digest('hex');
|
|
21
|
+
return [hex.slice(0,8),hex.slice(8,12),'5'+hex.slice(13,16),
|
|
22
|
+
((parseInt(hex[16],16)&3)|8).toString(16)+hex.slice(17,20),hex.slice(20,32)].join('-');
|
|
23
|
+
}
|
|
24
|
+
export function createRootScopeDiscovery({deviceId,home=homedir(),legacyRootId,legacyRoot,limit=48}={}){
|
|
25
|
+
if(!UUID.test(deviceId||'')||!UUID.test(legacyRootId||'')||
|
|
26
|
+
typeof home!=='string'||!safeDir(home)||!Number.isSafeInteger(limit)||limit<1||limit>128)
|
|
27
|
+
throw Error('ROOT_SCOPE_INVALID');
|
|
28
|
+
const canonical=realpathSync(home),items=[],seen=new Set();
|
|
29
|
+
const append=(path,is_home=false)=>{
|
|
30
|
+
if(items.length>=limit||!safeDir(path)||seen.has(path))return;
|
|
31
|
+
const rel=relative(canonical,path);
|
|
32
|
+
if(rel==='..'||rel.startsWith('..'+sep)||isAbsolute(rel))return;
|
|
33
|
+
seen.add(path);items.push(Object.freeze({root_id:path===legacyRoot?legacyRootId:scopeIdFor({deviceId,path}),path,supported:process.platform!=='win32',is_home}));
|
|
34
|
+
};
|
|
35
|
+
append(canonical,true);
|
|
36
|
+
const traverse=(dir,depth)=>{
|
|
37
|
+
if(items.length>=limit||depth>2)return;
|
|
38
|
+
let entries;try{entries=readdirSync(dir,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name));}catch{return;}
|
|
39
|
+
for(const e of entries){
|
|
40
|
+
if(items.length>=limit)break;
|
|
41
|
+
if(e.name.startsWith('.')||e.name==='node_modules'||!e.isDirectory()||e.isSymbolicLink())continue;
|
|
42
|
+
const path=join(dir,e.name);
|
|
43
|
+
if(!safeDir(path))continue;
|
|
44
|
+
append(path);
|
|
45
|
+
// Project folders under HOME/work, HOME/projects, and HOME/src only.
|
|
46
|
+
if(depth===0&&['work','projects','src','dev'].includes(e.name))traverse(path,depth+1);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
traverse(canonical,0);
|
|
50
|
+
// Existing legacy mapping is never reused as the computed home scope ID.
|
|
51
|
+
if(typeof legacyRoot==='string'&&safeDir(legacyRoot)&&UUID.test(legacyRootId)&&
|
|
52
|
+
!seen.has(legacyRoot)){
|
|
53
|
+
items.push(Object.freeze({root_id:legacyRootId,path:legacyRoot,supported:true,is_home:legacyRoot===canonical}));
|
|
54
|
+
}
|
|
55
|
+
const index=new Map(items.filter(x=>x.supported).map(x=>[x.root_id,x.path]));
|
|
56
|
+
return Object.freeze({
|
|
57
|
+
device_id:deviceId,root_scopes:Object.freeze(items),
|
|
58
|
+
resolve:rootId=>index.get(rootId)||null
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Only a registered supported root can enter the D1 execution path. The CP
|
|
63
|
+
// already authorized each owner/device/connection/root/tool; this is the
|
|
64
|
+
// independent Agent root and tool boundary, not a grant.
|
|
65
|
+
const NEW_SCOPE_READ=new Set(['list_directory','read_file','start_search',
|
|
66
|
+
'search_content','git_status','git_diff']);
|
|
67
|
+
export function routeDiscoveredRootTask({wireTask,sessionId,rootScopes,legacyRootId,deviceId}={}){
|
|
68
|
+
const a=wireTask?.tool?.arguments;
|
|
69
|
+
if(!a||typeof a!=='object'||!rootScopes||typeof rootScopes.resolve!=='function')
|
|
70
|
+
throw Error('DEV_ROOT_SCOPE_DENIED');
|
|
71
|
+
const id=a.root_id,root=rootScopes.resolve(id);
|
|
72
|
+
if(!root)throw Error('DEV_ROOT_SCOPE_DENIED');
|
|
73
|
+
const isLegacy=id===legacyRootId;
|
|
74
|
+
const approvedFile=!!a.file_authorization&&
|
|
75
|
+
['dev_edit_block','dev_node_test'].includes(wireTask.tool.name);
|
|
76
|
+
const approvedDc=!!a.dc_authorization&&isDcPublic(wireTask.tool.name);
|
|
77
|
+
if(!isLegacy&&(!NEW_SCOPE_READ.has(wireTask.tool.name)&&!approvedFile&&!approvedDc||
|
|
78
|
+
a.r4_authorization!==undefined))
|
|
79
|
+
throw Error('DEV_ROOT_SCOPE_DENIED');
|
|
80
|
+
const task=devDogfoodTaskEnvelope(wireTask,{sessionId,rootId:id,deviceId});
|
|
81
|
+
return Object.freeze({task,root_id:id,root,isLegacy});
|
|
82
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import {StdioClientTransport} from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
2
|
+
|
|
3
|
+
export function classifyDcFatal(text){
|
|
4
|
+
if(/(?:wasm|WebAssembly).{0,160}(?:could not allocate|allocation failed|failed to|out of memory|unable to|memory allocation)|(?:allocation failed|could not allocate|failed to reserve|out of memory).{0,160}(?:wasm|WebAssembly)/is.test(text))return 'WASM_ALLOCATION';
|
|
5
|
+
if(/out of memory|ENOMEM|Failed to reserve virtual memory/i.test(text))return 'MEMORY_ALLOCATION';
|
|
6
|
+
if(/Cannot find module|ERR_MODULE_NOT_FOUND/.test(text))return 'DEPENDENCY_MISSING';
|
|
7
|
+
return null;
|
|
8
|
+
}
|
|
9
|
+
// SDK 1.32.1 is pinned. Its public pid/onclose omit the termination signal;
|
|
10
|
+
// observe the owned ChildProcess for diagnostics only, without altering IPC.
|
|
11
|
+
export class C1DcTransport extends StdioClientTransport {
|
|
12
|
+
constructor(parameters,{diagnostic=line=>process.stderr.write(line+'\n')}={}){
|
|
13
|
+
super(parameters);this.diagnostic=diagnostic;let tail='',last=null;
|
|
14
|
+
this.stderr?.on('data',chunk=>{tail=(tail+chunk.toString()).slice(-4096);const code=classifyDcFatal(tail);if(code&&code!==last){last=code;this.diagnostic('C1_DC_FATAL_'+code);}});
|
|
15
|
+
}
|
|
16
|
+
async start(){
|
|
17
|
+
await super.start();
|
|
18
|
+
const child=this._process;
|
|
19
|
+
if(!child||child.pid!==this.pid||typeof child.once!=='function')throw Error('C1_DC_OBSERVER_UNAVAILABLE');
|
|
20
|
+
child.once('exit',(code,signal)=>{
|
|
21
|
+
const safeCode=Number.isInteger(code)?String(code):'NONE';
|
|
22
|
+
const safeSignal=['SIGABRT','SIGSEGV','SIGKILL','SIGTERM','SIGXCPU','SIGXFSZ'].includes(signal)?signal:signal?'OTHER':'NONE';
|
|
23
|
+
this.diagnostic(`C1_DC_EXIT_CODE_${safeCode}_SIGNAL_${safeSignal}`);
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export function assertLoopbackOnlyNetwork({devices,ipv4,ipv6}){
|
|
2
|
+
const names=devices.split('\n').slice(2).filter(line=>line.trim()).map(line=>line.split(':')[0].trim());
|
|
3
|
+
if(names.some(name=>name!=='lo'))throw Error('C1_NETWORK_DENIED');
|
|
4
|
+
for(const line of ipv4.split('\n').slice(1).filter(line=>line.trim()))if(line.trim().split(/\s+/)[0]!=='lo')throw Error('C1_NETWORK_DENIED');
|
|
5
|
+
// Linux retains loopback/local and unreachable default entries in ipv6_route
|
|
6
|
+
// even when a fresh private namespace has no external interface or egress.
|
|
7
|
+
for(const line of ipv6.split('\n').filter(line=>line.trim())){
|
|
8
|
+
const fields=line.trim().split(/\s+/);if(fields.length!==10||fields[9]!=='lo')throw Error('C1_NETWORK_DENIED');
|
|
9
|
+
}
|
|
10
|
+
return true;
|
|
11
|
+
}
|
|
12
|
+
export function classifyC1Startup(text){
|
|
13
|
+
const fatal=/C1_DC_FATAL_(WASM_ALLOCATION|MEMORY_ALLOCATION|DEPENDENCY_MISSING)/.exec(text);if(fatal)return 'DC_FATAL_'+fatal[1];
|
|
14
|
+
const exit=/C1_DC_EXIT_CODE_(NONE|-?\d+)_SIGNAL_(SIGABRT|SIGSEGV|SIGKILL|SIGXCPU|SIGXFSZ)/.exec(text);if(exit)return 'DC_SIGNAL_'+exit[2];
|
|
15
|
+
const stage=/C1_STAGE_([A-Z_]{1,100})/.exec(text);if(stage)return 'STAGE_'+stage[1];
|
|
16
|
+
if(/uid_map|Operation not permitted|No permissions/.test(text))return 'NAMESPACE_DENIED';
|
|
17
|
+
if(/Cannot load externalized builtin/.test(text))return 'NODE_BUILTIN_MISSING';
|
|
18
|
+
if(/Cannot find module|ERR_MODULE_NOT_FOUND/.test(text))return 'DEPENDENCY_MISSING';
|
|
19
|
+
if(/out of memory|ENOMEM|Failed to reserve virtual memory/i.test(text))return 'RESOURCE_LIMIT';
|
|
20
|
+
if(/\/root\/\.bashrc: Permission denied/.test(text))return 'SHELL_HOME_DENIED';
|
|
21
|
+
return 'UNKNOWN';
|
|
22
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import {spawn,execFileSync} from 'node:child_process';
|
|
2
|
+
import {mkdtempSync,mkdirSync,readdirSync,realpathSync,readlinkSync,rmSync,existsSync} from 'node:fs';
|
|
3
|
+
import {tmpdir} from 'node:os';
|
|
4
|
+
import {join,dirname,resolve,sep} from 'node:path';
|
|
5
|
+
import {createInterface} from 'node:readline';
|
|
6
|
+
import {taskEnvelope} from '../../shared/lib/contracts.mjs';
|
|
7
|
+
import {classifyC1Startup} from './c1-startup.mjs';
|
|
8
|
+
|
|
9
|
+
const denied=()=>{throw Error('C1_SUPERVISOR_DENIED');};
|
|
10
|
+
const quote=v=>`'${String(v).replaceAll("'","'\\''")}'`;
|
|
11
|
+
export async function executeC1Transaction(value,{command,post}){
|
|
12
|
+
const task=taskEnvelope(value);let prepared=false,accepted=false,uncertain=false;
|
|
13
|
+
try{
|
|
14
|
+
await post('/device/c1/authorize',{request_id:task.request_id});
|
|
15
|
+
const reply=await command('execute',task);prepared=true;
|
|
16
|
+
if(typeof reply.result!=='string'||Buffer.byteLength(reply.result)>4096)denied();
|
|
17
|
+
await post('/device/c1/prepare',{request_id:task.request_id});
|
|
18
|
+
await command('commit',task);
|
|
19
|
+
try{await post('/device/result',{request_id:task.request_id,ok:true,result:reply.result});accepted=true;}
|
|
20
|
+
catch(error){
|
|
21
|
+
let receipt;try{receipt=await post('/device/c1/outcome',{request_id:task.request_id});}
|
|
22
|
+
catch{uncertain=true;throw Error('C1_COMMIT_UNCERTAIN');}
|
|
23
|
+
if(receipt.status!=='completed')throw error;accepted=true;
|
|
24
|
+
}
|
|
25
|
+
await command('finalize',task);return reply.result;
|
|
26
|
+
}catch(error){
|
|
27
|
+
if(prepared&&!accepted&&!uncertain){try{await command('rollback',task);}catch{throw Error('C1_ROLLBACK_UNVERIFIED');}}
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function verifyTree(root){
|
|
32
|
+
const visit=directory=>{for(const entry of readdirSync(directory,{withFileTypes:true})){const path=join(directory,entry.name);if(entry.isSymbolicLink()){const target=realpathSync(path);if(target!==root&&!target.startsWith(root+sep))denied();}else if(entry.isDirectory())visit(path);}};visit(root);
|
|
33
|
+
}
|
|
34
|
+
export function c1SandboxCommand(runtime,scratch){
|
|
35
|
+
const binary=realpathSync('/usr/bin/node'),files=new Map([['/usr/bin/node',binary]]);
|
|
36
|
+
if(!binary.startsWith('/usr/bin/'))denied();
|
|
37
|
+
for(const line of execFileSync('ldd',[binary],{encoding:'utf8'}).split('\n')){
|
|
38
|
+
const path=/=>\s+(\/\S+)\s+\(/.exec(line)?.[1]??/^\s*(\/\S+)\s+\(/.exec(line)?.[1];
|
|
39
|
+
if(path){const source=realpathSync(path);if(!source.startsWith('/usr/lib/'))denied();files.set(path,source);}
|
|
40
|
+
}
|
|
41
|
+
const source=realpathSync(join(runtime,'src')),modules=realpathSync(join(runtime,'node_modules'));
|
|
42
|
+
const shared=realpathSync(join(runtime,existsSync(join(runtime,'shared'))?'shared':'../shared'));
|
|
43
|
+
verifyTree(source);verifyTree(modules);verifyTree(shared);
|
|
44
|
+
const dirs=new Set(['/app','/app/src','/app/src/device-agent','/app/shared','/app/node_modules','/scratch','/home']);
|
|
45
|
+
for(const [target] of files)for(let p=dirname(target);p!=='/';p=dirname(p))dirs.add(p);
|
|
46
|
+
const args=['--unshare-all','--die-with-parent','--new-session','--cap-drop','ALL'];
|
|
47
|
+
for(const d of [...dirs].sort((a,b)=>a.split('/').length-b.split('/').length))args.push('--dir',d);
|
|
48
|
+
args.push('--ro-bind',source,'/app/src/device-agent','--ro-bind',shared,'/app/shared','--ro-bind',modules,'/app/node_modules','--proc','/proc','--dev','/dev','--remount-ro','/dev');
|
|
49
|
+
for(const [target,host] of files)args.push('--ro-bind',host,target);
|
|
50
|
+
args.push('--bind',join(scratch,'root'),'/scratch','--bind',join(scratch,'home'),'/home','--chdir','/scratch','--clearenv','--setenv','PATH','/usr/bin','--setenv','DO_NOT_TRACK','1');
|
|
51
|
+
for(const kind of ['user','mnt','pid','net'])args.push('--setenv',`RS_C1_HOST_${kind.toUpperCase()}`,readlinkSync(`/proc/self/ns/${kind}`));
|
|
52
|
+
args.push('--','/usr/bin/node','--max-old-space-size=128','/app/src/device-agent/core/c1-worker.mjs');
|
|
53
|
+
const boot=['set -eu',`mount -t tmpfs -o size=32m,mode=0700,rw,nosuid,nodev,noexec tmpfs ${quote(join(scratch,'root'))}`,`mount -t tmpfs -o size=32m,mode=0700,rw,nosuid,nodev,noexec tmpfs ${quote(join(scratch,'home'))}`,`mkdir -p ${quote(join(scratch,'home/dc/tmp'))}`,`exec bwrap ${args.map(quote).join(' ')}`].join('\n');
|
|
54
|
+
return ['prlimit',['--as=8589934592','--cpu=60','--nofile=128','--nproc=256','--fsize=1048576','--','unshare','--user','--map-root-user','--mount','--fork','--kill-child=SIGKILL','--','/bin/bash','--noprofile','--norc','-ceu',boot]];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export class C1Supervisor {
|
|
58
|
+
#child;#scratch;#waiting=null;#busy=false;#closed=false;#post;#ready;#bufferBytes=0;#startupCause='UNKNOWN';#startupStage='START';
|
|
59
|
+
constructor({runtime,post}={}){
|
|
60
|
+
if(typeof post!=='function')denied();this.#post=post;
|
|
61
|
+
this.#scratch=mkdtempSync(join(tmpdir(),'rs-c1-supervisor-'));mkdirSync(join(this.#scratch,'root'),{mode:0o700});mkdirSync(join(this.#scratch,'home'),{mode:0o700});
|
|
62
|
+
try{
|
|
63
|
+
const [command,args]=c1SandboxCommand(resolve(runtime),this.#scratch);
|
|
64
|
+
this.#child=spawn(command,args,{env:{PATH:'/usr/sbin:/usr/bin:/sbin:/bin'},stdio:['pipe','pipe','pipe']});
|
|
65
|
+
this.#child.stdin.on('error',()=>{this.#waiting?.reject(Error('C1_WORKER_PIPE_CLOSED'));this.#waiting=null;});
|
|
66
|
+
// Protocol stdout is bounded. stderr never contains Gateway credentials and
|
|
67
|
+
// is not forwarded into MCP responses.
|
|
68
|
+
let diagnostic='';
|
|
69
|
+
this.#child.stderr.on('data',chunk=>{
|
|
70
|
+
diagnostic=(diagnostic+chunk.toString()).slice(-2048);
|
|
71
|
+
// An allowlisted checkpoint; never retain or relay arbitrary child stderr.
|
|
72
|
+
const stages=[...diagnostic.matchAll(/C1_PROGRESS_(DC_CONNECT_BEGIN|DC_CONNECT_DONE|READY_SEND)/g)];
|
|
73
|
+
if(stages.length)this.#startupStage=stages.at(-1)[1];
|
|
74
|
+
const cause=classifyC1Startup(diagnostic);if(cause!=='UNKNOWN')this.#startupCause=cause;
|
|
75
|
+
});
|
|
76
|
+
const lines=createInterface({input:this.#child.stdout,crlfDelay:Infinity});
|
|
77
|
+
lines.on('line',line=>{this.#bufferBytes+=Buffer.byteLength(line);if(this.#bufferBytes>131072){this.close();return;}try{const value=JSON.parse(line);this.#waiting?.resolve(value);this.#waiting=null;}catch{this.close();}});
|
|
78
|
+
// 'exit' may fire before the stdio streams finish draining. Wait for
|
|
79
|
+
// 'close' so the bounded, sanitized stderr classifier sees the final
|
|
80
|
+
// owned DC child diagnostic before reporting a startup failure.
|
|
81
|
+
this.#child.once('close',()=>{this.#waiting?.reject(Error('C1_WORKER_EXITED_'+this.#startupCause+'_LAST_'+this.#startupStage));this.#waiting=null;});
|
|
82
|
+
this.#child.once('error',()=>{this.#waiting?.reject(Error('C1_WORKER_START_FAILED'));this.#waiting=null;});
|
|
83
|
+
this.#ready=this.#receive(10000).then(value=>{if(value.type!=='ready'||value.version!=='0.3.1')denied();});
|
|
84
|
+
}catch(error){this.close();throw error;}
|
|
85
|
+
}
|
|
86
|
+
#receive(timeout=7000){
|
|
87
|
+
return new Promise((resolve,reject)=>{
|
|
88
|
+
if(this.#closed||this.#waiting)return reject(Error('C1_PROTOCOL_STATE'));
|
|
89
|
+
const timer=setTimeout(()=>{
|
|
90
|
+
this.#waiting=null;
|
|
91
|
+
// A fixed, bounded diagnostic distinguishes a live worker stalled in
|
|
92
|
+
// DC connect from an exited one or a worker that never reached connect.
|
|
93
|
+
const alive=this.#child&&this.#child.exitCode===null&&this.#child.signalCode===null;
|
|
94
|
+
const stage=this.#startupStage;
|
|
95
|
+
reject(Error('C1_WORKER_TIMEOUT_'+(alive?'ALIVE_':'EXITED_')+stage));
|
|
96
|
+
},timeout);
|
|
97
|
+
this.#waiting={resolve:v=>{clearTimeout(timer);resolve(v);},reject:e=>{clearTimeout(timer);reject(e);}};
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
ready(){return this.#ready;}
|
|
101
|
+
async #command(type,task){const pending=this.#receive();this.#child.stdin.write(JSON.stringify({type,...(type==='execute'?{task}:{request_id:task.request_id})})+'\n');const reply=await pending;if(type==='execute'&&reply.type==='rejected'&&reply.request_id===task.request_id)throw Error('C1_REQUEST_DENIED');if(reply.type!==(type==='execute'?'prepared':type)||reply.request_id!==task.request_id)denied();return reply;}
|
|
102
|
+
async execute(value){
|
|
103
|
+
if(this.#busy||this.#closed)denied();this.#busy=true;
|
|
104
|
+
try{
|
|
105
|
+
await this.#ready;
|
|
106
|
+
return await executeC1Transaction(value,{command:(type,task)=>this.#command(type,task),post:this.#post});
|
|
107
|
+
}catch(error){if(/C1_(WORKER|ROLLBACK|COMMIT|PROTOCOL)/.test(error.message))this.close({uncertain:error.message==='C1_COMMIT_UNCERTAIN'});throw error;}
|
|
108
|
+
finally{this.#busy=false;}
|
|
109
|
+
}
|
|
110
|
+
close({uncertain=false}={}){if(this.#closed)return;this.#closed=true;this.#waiting?.reject(Error('C1_SUPERVISOR_CLOSED'));this.#waiting=null;if(this.#child){if(!uncertain)this.#child.stdin.end();this.#child.kill(uncertain?'SIGKILL':'SIGTERM');}if(this.#scratch)rmSync(this.#scratch,{recursive:true,force:true});}
|
|
111
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import {isSyntheticAuxiliaryName} from '../../shared/lib/synthetic-auxiliary-policy.mjs';
|
|
2
|
+
import {prepareSyntheticAuxiliaryTransaction} from '../policy/synthetic-auxiliary-adapter.mjs';
|
|
3
|
+
import {prepareSyntheticFileTransaction} from '../policy/synthetic-file-transaction.mjs';
|
|
4
|
+
import {createInterface} from 'node:readline';
|
|
5
|
+
import {createRequire} from 'node:module';
|
|
6
|
+
import {dirname,join} from 'node:path';
|
|
7
|
+
import {createHash} from 'node:crypto';
|
|
8
|
+
import {constants,openSync,closeSync,fstatSync,readFileSync,writeFileSync,lstatSync,unlinkSync,renameSync,readlinkSync} from 'node:fs';
|
|
9
|
+
import {execFileSync} from 'node:child_process';
|
|
10
|
+
import {Client} from '@modelcontextprotocol/sdk/client/index.js';
|
|
11
|
+
import {C1DcTransport} from './c1-dc-transport.mjs';
|
|
12
|
+
import {taskEnvelope} from '../../shared/lib/contracts.mjs';
|
|
13
|
+
import {makeVerifiedSyntheticWriteAdapter} from '../policy/verified-synthetic-write.mjs';
|
|
14
|
+
import {assertLoopbackOnlyNetwork} from './c1-startup.mjs';
|
|
15
|
+
|
|
16
|
+
let stage='NAMESPACE';
|
|
17
|
+
const fatal=error=>{
|
|
18
|
+
const cause=['ENOENT','EACCES','EPERM','ENOMEM'].includes(error?.code)?error.code:/closed/i.test(error?.message??'')?'CONNECTION_CLOSED':'DENIED';
|
|
19
|
+
process.stderr.write(`C1_STAGE_${stage}_${cause}\n`,()=>process.exit(1));
|
|
20
|
+
setTimeout(()=>process.exit(1),1000).unref();
|
|
21
|
+
};
|
|
22
|
+
process.once('uncaughtException',fatal);process.once('unhandledRejection',fatal);
|
|
23
|
+
|
|
24
|
+
// Startup progress is reported only as a fixed stage label. No stderr from
|
|
25
|
+
// Desktop Commander, paths, environment values, or credentials are forwarded.
|
|
26
|
+
const startupStage=label=>process.stderr.write('C1_PROGRESS_'+label+'\n');
|
|
27
|
+
const root='/scratch',home='/home/dc',require=createRequire(import.meta.url);
|
|
28
|
+
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
29
|
+
const send=value=>process.stdout.write(JSON.stringify(value)+'\n');
|
|
30
|
+
const fail=()=>{throw Error('C1_WORKER_DENIED');};
|
|
31
|
+
for(const kind of ['user','mnt','pid','net'])if(readlinkSync(`/proc/self/ns/${kind}`)===process.env[`RS_C1_HOST_${kind.toUpperCase()}`])fail();
|
|
32
|
+
if(readFileSync('/proc/1/comm','utf8').trim()!=='bwrap'||process.ppid!==1)fail();
|
|
33
|
+
stage='NETWORK';
|
|
34
|
+
assertLoopbackOnlyNetwork({devices:readFileSync('/proc/net/dev','utf8'),ipv4:readFileSync('/proc/net/route','utf8'),ipv6:readFileSync('/proc/net/ipv6_route','utf8')});
|
|
35
|
+
stage='CAPABILITIES';
|
|
36
|
+
const status=readFileSync('/proc/self/status','utf8');
|
|
37
|
+
if(!/^NoNewPrivs:\s+1$/m.test(status)||!/^CapEff:\s+0+$/m.test(status))fail();
|
|
38
|
+
stage='NOEXEC';
|
|
39
|
+
writeFileSync('/scratch/probe.txt','#!/bin/sh\nexit 0\n',{mode:0o700});
|
|
40
|
+
try{execFileSync('/scratch/probe.txt');fail();}catch(error){if(error.code!=='EACCES')throw error;}finally{unlinkSync('/scratch/probe.txt');}
|
|
41
|
+
stage='DC_PACKAGE';
|
|
42
|
+
const pkg=require.resolve('@wonderwhy-er/desktop-commander/package.json');if(require(pkg).version!=='0.3.1')fail();
|
|
43
|
+
const client=new Client({name:'rs-c1-worker',version:'1.0.0'}),transport=new C1DcTransport({command:process.execPath,args:[join(dirname(pkg),'dist/index.js'),'--no-onboarding'],cwd:root,env:{PATH:'/usr/bin',HOME:home,TMPDIR:home+'/tmp',DO_NOT_TRACK:'1',CI:'1'},stderr:'pipe'});
|
|
44
|
+
stage='DC_CONNECT';startupStage('DC_CONNECT_BEGIN');
|
|
45
|
+
await client.connect(transport);
|
|
46
|
+
startupStage('DC_CONNECT_DONE');stage='MOUNT';
|
|
47
|
+
const run=makeVerifiedSyntheticWriteAdapter({enabled:true,root,client,authorized:async()=>true,onAudit:()=>{}});
|
|
48
|
+
let pending=null,requests=0,scope=null;
|
|
49
|
+
async function rollback(){
|
|
50
|
+
if(!pending)return;
|
|
51
|
+
if(pending.filePlan){await pending.filePlan.rollback();pending=null;return;}
|
|
52
|
+
const {path,before,after}=pending,st=lstatSync(path);
|
|
53
|
+
if(!st.isFile()||st.isSymbolicLink()||st.nlink!==1||st.dev!==after.dev||st.ino!==after.ino)fail();
|
|
54
|
+
if(before===null)unlinkSync(path);
|
|
55
|
+
else{const temp=join(root,'.c1-rollback');writeFileSync(temp,before,{flag:'wx',mode:0o600});renameSync(temp,path);if(sha(readFileSync(path))!==sha(before))fail();}
|
|
56
|
+
pending=null;
|
|
57
|
+
}
|
|
58
|
+
stage='REQUEST';startupStage('READY_SEND');send({type:'ready',version:'0.3.1'});
|
|
59
|
+
const lines=createInterface({input:process.stdin,crlfDelay:Infinity});
|
|
60
|
+
try{
|
|
61
|
+
for await(const line of lines){
|
|
62
|
+
if(Buffer.byteLength(line)>70000)fail();
|
|
63
|
+
const message=JSON.parse(line);
|
|
64
|
+
if(message.type==='execute'){
|
|
65
|
+
if(pending||++requests>16)fail();
|
|
66
|
+
const task=taskEnvelope(message.task),isAuxiliary=isSyntheticAuxiliaryName(task.tool.name),isFileTool=['create_directory','move_file','write_pdf'].includes(task.tool.name),path=isFileTool||isAuxiliary?null:join(root,task.tool.arguments.path);
|
|
67
|
+
const identity=JSON.stringify([task.context.owner_id,task.context.connection_id,task.context.device_id]);
|
|
68
|
+
if(scope!==null&&scope!==identity)fail();scope=identity;
|
|
69
|
+
let filePlan;try{if(isAuxiliary)filePlan=await prepareSyntheticAuxiliaryTransaction(client,task.tool);else if(isFileTool)filePlan=prepareSyntheticFileTransaction(root,task.tool);}catch{send({type:'rejected',request_id:task.request_id});continue;}
|
|
70
|
+
let before=null;
|
|
71
|
+
try{if(path){const fd=openSync(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const st=fstatSync(fd);if(!st.isFile()||st.nlink!==1||st.size>32768)fail();before=readFileSync(fd);}finally{closeSync(fd);}}}catch(error){if(error.code!=='ENOENT')throw error;}
|
|
72
|
+
let result;
|
|
73
|
+
try{result=await run(task.tool.name,task.tool.arguments,task.context);}
|
|
74
|
+
catch(error){if(error.code==='SYNTHETIC_WRITE_ROLLBACK_UNVERIFIED')throw error;send({type:'rejected',request_id:task.request_id});continue;}
|
|
75
|
+
if(filePlan)await filePlan.verify();
|
|
76
|
+
pending={path,before,after:path?lstatSync(path):null,filePlan,request_id:task.request_id,state:'prepared'};
|
|
77
|
+
send({type:'prepared',request_id:task.request_id,result});
|
|
78
|
+
}else if(['commit','rollback','finalize'].includes(message.type)){
|
|
79
|
+
if(!pending||message.request_id!==pending.request_id)fail();
|
|
80
|
+
if(message.type==='rollback')await rollback();
|
|
81
|
+
else if(message.type==='commit'){if(pending.state!=='prepared')fail();pending.state='committed';}
|
|
82
|
+
else if(message.type==='finalize'){if(pending.state!=='committed')fail();pending=null;}
|
|
83
|
+
send({type:message.type,request_id:message.request_id});
|
|
84
|
+
}else fail();
|
|
85
|
+
}
|
|
86
|
+
}finally{
|
|
87
|
+
try{await rollback();}finally{await client.close().catch(()=>{});await transport.close().catch(()=>{});}
|
|
88
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import {isAbsolute,relative,resolve,sep} from 'node:path';
|
|
2
|
+
|
|
3
|
+
// Diagnostic only: a DC config value is not proof that every tool
|
|
4
|
+
// enforces directory limits (e.g. symlinks or terminal commands).
|
|
5
|
+
export function assessDcAccessBoundary(config,rootPath){
|
|
6
|
+
const dirs=config?.allowedDirectories;
|
|
7
|
+
if(!Array.isArray(dirs))return Object.freeze({status:'UNKNOWN',configuredCount:0,canRemoveRsRootChecks:false});
|
|
8
|
+
// Original DC treats an empty allow-list as its normal unrestricted default.
|
|
9
|
+
// This is not a missing setup step or an RS connection failure.
|
|
10
|
+
if(dirs.length===0)return Object.freeze({status:'UNRESTRICTED_DEFAULT',configuredCount:0,canRemoveRsRootChecks:false});
|
|
11
|
+
const valid=dirs.filter(p=>typeof p==='string'&&isAbsolute(p)&&p.length<4096);
|
|
12
|
+
if(valid.length!==dirs.length)return Object.freeze({status:'INVALID',configuredCount:dirs.length,canRemoveRsRootChecks:false});
|
|
13
|
+
if(typeof rootPath!=='string'||!isAbsolute(rootPath))
|
|
14
|
+
return Object.freeze({status:'ROOT_UNKNOWN',configuredCount:dirs.length,canRemoveRsRootChecks:false});
|
|
15
|
+
const target=resolve(rootPath);
|
|
16
|
+
const matched=valid.some(p=>{
|
|
17
|
+
const rel=relative(resolve(p),target);
|
|
18
|
+
return rel===''||rel!=='..'&&!rel.startsWith('..'+sep)&&!isAbsolute(rel);
|
|
19
|
+
});
|
|
20
|
+
return Object.freeze({status:matched?'CONFIGURED_CANDIDATE':'ROOT_MISMATCH',
|
|
21
|
+
configuredCount:dirs.length,canRemoveRsRootChecks:false});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function inspectDcAccessBoundary(client,rootPath){
|
|
25
|
+
if(!client||typeof client.callTool!=='function')throw Error('DC_CLIENT_UNAVAILABLE');
|
|
26
|
+
try{
|
|
27
|
+
const result=await client.callTool({name:'get_config',arguments:{}});
|
|
28
|
+
// Never infer authorization from tool display text.
|
|
29
|
+
return assessDcAccessBoundary(result?.structuredContent?.config,rootPath);
|
|
30
|
+
}catch{return Object.freeze({status:'UNAVAILABLE',configuredCount:0,canRemoveRsRootChecks:false});}
|
|
31
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// #249: original Desktop Commander MCP delegation, not a replacement engine.
|
|
2
|
+
// The caller must have completed owner/device/root/tool approval before entry.
|
|
3
|
+
// No home-grown file reading, shell spawning, output conversion or PID rewriting.
|
|
4
|
+
import {realpathSync} from 'node:fs';
|
|
5
|
+
import {isDcPublic,validateDcGenericArgs,validateDcPathScope,dcHasPath,dcFilePaths} from '../../shared/lib/dc-generic-policy.mjs';
|
|
6
|
+
import {isAbsolute,relative,resolve,sep} from 'node:path';
|
|
7
|
+
import {validateDcRelayArgs} from '../../shared/lib/dc-relay-contract.mjs';
|
|
8
|
+
export {validateDcRelayArgs} from '../../shared/lib/dc-relay-contract.mjs';
|
|
9
|
+
const DENIED=()=>Object.assign(new Error('DC_RELAY_DENIED'),{code:'DC_RELAY_DENIED'});
|
|
10
|
+
const plain=x=>x&&typeof x==='object'&&!Array.isArray(x)&&Object.getPrototypeOf(x)===Object.prototype;
|
|
11
|
+
// Scope enforcement is independent of DC. Require a canonical existing file,
|
|
12
|
+
// and prohibit symlinks escaping the selected approved Root.
|
|
13
|
+
export function verifyDcReadScope(path,root){
|
|
14
|
+
try{
|
|
15
|
+
const base=realpathSync(root),target=realpathSync(path),rel=relative(base,target);
|
|
16
|
+
if(rel==='..'||rel.startsWith('..'+sep)||isAbsolute(rel))throw DENIED();
|
|
17
|
+
return target;
|
|
18
|
+
}catch{throw DENIED()}
|
|
19
|
+
}
|
|
20
|
+
export async function callOriginalDc({client,name,args,approvedRoot,approvedCommand,approvedPid,
|
|
21
|
+
onTrace=()=>{}}={}){
|
|
22
|
+
if(!client||typeof client.callTool!=='function')throw DENIED();
|
|
23
|
+
validateDcRelayArgs(name,args);
|
|
24
|
+
if(name==='start_process'){
|
|
25
|
+
// Never silently substitute a wildcard tool/root grant for command consent.
|
|
26
|
+
if(typeof approvedCommand!=='string'||approvedCommand!==args.command)throw DENIED();
|
|
27
|
+
}else if(name==='read_process_output'&&(!Number.isSafeInteger(approvedPid)||args.pid!==approvedPid))throw DENIED();
|
|
28
|
+
onTrace({event:'dc_call',name,arguments:['read_file','list_directory'].includes(name)?{path:args.path,offset:args.offset,length:args.length,depth:args.depth}:
|
|
29
|
+
name==='start_process'?{command:'[redacted]',timeout_ms:args.timeout_ms}:{pid:args.pid}});
|
|
30
|
+
const result=await client.callTool({name,arguments:args});
|
|
31
|
+
if(!result||typeof result!=='object'||typeof result.isError!=='boolean'&&!Array.isArray(result.content))
|
|
32
|
+
throw DENIED();
|
|
33
|
+
onTrace({event:'dc_result',name,isError:result.isError===true});
|
|
34
|
+
return result; // Preserve original MCP content/isError; caller adds RS metadata separately.
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function callOriginalDcGeneric({client,name,args,catalog,approvedRoot,onTrace=()=>{}}={}){
|
|
38
|
+
if(!isDcPublic(name)||!client||typeof client.callTool!=='function')throw DENIED();
|
|
39
|
+
validateDcGenericArgs(name,args,catalog);
|
|
40
|
+
// Original DC enforces its own allowedDirectories and filesystem access.
|
|
41
|
+
// Do not apply a second RS folder policy to an already owner-bound tool call.
|
|
42
|
+
onTrace({event:'dc_call',name,arguments:dcHasPath(name)?{paths:dcFilePaths(name,args)}:{redacted:true}});
|
|
43
|
+
const result=await client.callTool({name,arguments:args});
|
|
44
|
+
if(!result||typeof result!=='object'||!Array.isArray(result.content))throw DENIED();
|
|
45
|
+
onTrace({event:'dc_result',name,isError:result.isError===true});
|
|
46
|
+
return result;
|
|
47
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import '../main.mjs';
|