@remoteshell/device 0.1.0-beta.1 → 0.1.0-beta.3
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 +233 -9
- package/bin/install-acquire.mjs +89 -0
- package/bin/install-integrity.mjs +74 -0
- package/bin/install-plan.mjs +43 -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 +289 -0
- package/bin/remoteshell-easy-install.sh +71 -0
- package/bin/remoteshell-easy-uninstall.ps1 +124 -0
- package/bin/windows-credential-boundary.mjs +106 -0
- package/bin/windows-install-layout.mjs +28 -0
- package/bin/windows-native-installer.mjs +91 -0
- package/bin/windows-private-store.mjs +163 -0
- package/bin/windows-user-lifecycle.mjs +34 -0
- package/npm-shrinkwrap.json +8591 -0
- package/package.json +14 -5
- package/shared/lib/bounded-search-contract.mjs +5 -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/{src/common → shared/lib}/synthetic-write-policy.mjs +0 -1
- 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/{device-agent → core}/c1-supervisor.mjs +9 -7
- package/src/{device-agent → core}/c1-worker.mjs +7 -7
- 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 -230
- package/src/gateway-keepalive.mjs +73 -0
- package/src/main.mjs +434 -0
- package/src/{common → policy}/bounded-search-adapter.mjs +2 -3
- package/src/{common → policy}/isolated-read-adapter.mjs +1 -1
- package/src/{common → policy}/isolated-read-mount.mjs +1 -1
- package/src/{common → policy}/synthetic-auxiliary-adapter.mjs +1 -1
- package/src/{common → policy}/synthetic-file-adapter.mjs +1 -1
- package/src/{common → policy}/synthetic-file-transaction.mjs +1 -1
- package/src/{common → policy}/synthetic-write-adapter.mjs +2 -3
- /package/{src/common → shared/lib}/bounded-search-policy.mjs +0 -0
- /package/{src/common → shared/lib}/config.mjs +0 -0
- /package/{src/common → shared/lib}/contracts.mjs +0 -0
- /package/{src/common → shared/lib}/errors.mjs +0 -0
- /package/{src/common → shared/lib}/events.mjs +0 -0
- /package/{src/common → shared/lib}/execution-policy.mjs +0 -0
- /package/{src/common → shared/lib}/isolated-read-boundary.mjs +0 -0
- /package/{src/common → shared/lib}/isolated-read-policy.mjs +0 -0
- /package/{src/common → shared/lib}/lifecycle-events.mjs +0 -0
- /package/{src/common → shared/lib}/runtime-timing.mjs +0 -0
- /package/{src/common → shared/lib}/synthetic-auxiliary-policy.mjs +0 -0
- /package/{src/common → shared/lib}/tool-registry.mjs +0 -0
- /package/src/{device-agent → core}/c1-dc-transport.mjs +0 -0
- /package/src/{device-agent → core}/c1-startup.mjs +0 -0
- /package/src/{device-agent → core}/fixture.txt +0 -0
- /package/src/{common → policy}/synthetic-write-mount.mjs +0 -0
- /package/src/{common → policy}/verified-bounded-search.mjs +0 -0
- /package/src/{common → policy}/verified-isolated-read.mjs +0 -0
- /package/src/{common → policy}/verified-synthetic-write.mjs +0 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import {createHash,randomUUID} from 'node:crypto';
|
|
2
|
+
import {lstatSync,realpathSync,readFileSync,writeFileSync,openSync,closeSync,fsyncSync,renameSync,unlinkSync,readdirSync} from 'node:fs';
|
|
3
|
+
import {resolve,relative,dirname,join,sep} from 'node:path';
|
|
4
|
+
const DENY=()=>{throw Error('DEV_DOGFOOD_WRITE_DENIED');};
|
|
5
|
+
const SHA=x=>createHash('sha256').update(x).digest('hex');
|
|
6
|
+
const FILE=/^(?!\.)(?:[A-Za-z0-9_-][A-Za-z0-9_.-]*\/)*(?!\.)(?:[A-Za-z0-9_-][A-Za-z0-9_.-]*)\.(?:c?js|mjs|json|md|txt)$/;
|
|
7
|
+
function rootOf(root){
|
|
8
|
+
if(typeof root!=='string'||!root.startsWith('/')||resolve(root)!==root)DENY();
|
|
9
|
+
const s=lstatSync(root);if(!s.isDirectory()||s.isSymbolicLink()||s.uid!==process.getuid?.()||realpathSync(root)!==root)DENY();return root;
|
|
10
|
+
}
|
|
11
|
+
function target(root,path,exists){
|
|
12
|
+
if(typeof path!=='string'||path.length>256||path.startsWith('/')||!FILE.test(path)||path.split('/').some(x=>x==='.'||x==='..'||/^\.env/i.test(x)||/credential|secret|token|password|private.?key/i.test(x)))DENY();
|
|
13
|
+
const parts=path.split('/'),name=parts.pop();let parent=root;
|
|
14
|
+
for(const part of parts){parent=join(parent,part);const s=lstatSync(parent);if(!s.isDirectory()||s.isSymbolicLink()||realpathSync(parent)!==parent)DENY();}
|
|
15
|
+
const abs=resolve(parent,name),delta=relative(root,abs);if(delta==='..'||delta.startsWith('..'+sep)||delta.startsWith('/'))DENY();
|
|
16
|
+
let st;try{st=lstatSync(abs);}catch(e){if(e?.code!=='ENOENT')DENY();}
|
|
17
|
+
if(exists?(!st||!st.isFile()||st.isSymbolicLink()||st.nlink!==1||realpathSync(abs)!==abs):Boolean(st))DENY();
|
|
18
|
+
return abs;
|
|
19
|
+
}
|
|
20
|
+
function exact(args,keys){return args&&Object.getPrototypeOf(args)===Object.prototype&&Object.keys(args).sort().join(',')===keys.slice().sort().join(',');}
|
|
21
|
+
function call(client,name,args){return client.callTool({name,arguments:args},undefined,{signal:AbortSignal.timeout(5000)});}
|
|
22
|
+
function check(result){if(result?.isError===true)DENY();const text=(result?.content||[]).filter(x=>x.type==='text').map(x=>x.text).join('\n');if(Buffer.byteLength(text)>4096)DENY();}
|
|
23
|
+
function syncDir(path){const fd=openSync(path,'r');try{fsyncSync(fd);}finally{closeSync(fd);}}
|
|
24
|
+
function exists(path){try{lstatSync(path);return true;}catch(e){if(e?.code==='ENOENT')return false;throw e;}}
|
|
25
|
+
function replaceAtomically(path,content){
|
|
26
|
+
const temp=join(dirname(path),`.rs-dogfood-${randomUUID()}.tmp`);let fd;
|
|
27
|
+
try{fd=openSync(temp,'wx',0o600);writeFileSync(fd,content);fsyncSync(fd);closeSync(fd);fd=undefined;renameSync(temp,path);syncDir(dirname(path));}
|
|
28
|
+
finally{if(fd!==undefined)closeSync(fd);try{unlinkSync(temp);}catch{}}
|
|
29
|
+
}
|
|
30
|
+
export async function executeDevDogfoodWrite({root,tool,client}={}){
|
|
31
|
+
const base=rootOf(root),a=tool?.arguments;
|
|
32
|
+
if(!client||typeof client.callTool!=='function'||!tool)DENY();
|
|
33
|
+
if(tool.name==='write_file'){
|
|
34
|
+
if(!exact(a,['root_id','path','content'])||typeof a.content!=='string'||Buffer.byteLength(a.content)>32768||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(a.content))DENY();
|
|
35
|
+
const dest=target(base,a.path,false),stage=join(dirname(dest),`.rs-stage-${randomUUID()}.txt`),bytes=Buffer.from(a.content);
|
|
36
|
+
try{check(await call(client,'write_file',{path:stage,content:a.content,mode:'rewrite',origin:'llm'}));
|
|
37
|
+
const st=lstatSync(stage);if(!st.isFile()||st.isSymbolicLink()||st.size!==bytes.length||!readFileSync(stage).equals(bytes)||exists(dest))DENY();
|
|
38
|
+
renameSync(stage,dest);syncDir(dirname(dest));
|
|
39
|
+
return JSON.stringify({created:true,bytes:bytes.length,sha256:SHA(bytes)});
|
|
40
|
+
}catch{try{unlinkSync(stage);}catch{}DENY();}
|
|
41
|
+
}
|
|
42
|
+
if(tool.name==='edit_block'){
|
|
43
|
+
if(!exact(a,['root_id','path','old_string','new_string','expectedHash'])||typeof a.old_string!=='string'||!a.old_string.length||typeof a.new_string!=='string'||typeof a.expectedHash!=='string'||!/^[a-f0-9]{64}$/.test(a.expectedHash))DENY();
|
|
44
|
+
const dest=target(base,a.path,true),st=lstatSync(dest);if(st.size>65536)DENY();
|
|
45
|
+
const before=readFileSync(dest),old=before.toString('utf8');if(!Buffer.from(old).equals(before)||SHA(before)!==a.expectedHash||old.split(a.old_string).length!==2)DENY();
|
|
46
|
+
const updated=old.replace(a.old_string,a.new_string);if(Buffer.byteLength(updated)>65536)DENY();
|
|
47
|
+
try{
|
|
48
|
+
const result=await call(client,'edit_block',{file_path:dest,old_string:a.old_string,new_string:a.new_string,expected_replacements:1,origin:'llm'});check(result);
|
|
49
|
+
const after=readFileSync(dest);if(!after.equals(Buffer.from(updated)))DENY();
|
|
50
|
+
return JSON.stringify({edited:true,bytes:after.length,sha256:SHA(after),previous_sha256:SHA(before)});
|
|
51
|
+
}catch{try{replaceAtomically(dest,before);}catch{}DENY();}
|
|
52
|
+
}
|
|
53
|
+
if(tool.name==='delete_file'){
|
|
54
|
+
if(!exact(a,['root_id','path','expectedHash'])||typeof a.expectedHash!=='string'||!/^[a-f0-9]{64}$/.test(a.expectedHash))DENY();
|
|
55
|
+
const dest=target(base,a.path,true),before=readFileSync(dest);if(SHA(before)!==a.expectedHash)DENY();
|
|
56
|
+
const quarantine=join(dirname(dest),`.rs-delete-${randomUUID()}.tmp`);
|
|
57
|
+
try{renameSync(dest,quarantine);if(!readFileSync(quarantine).equals(before))DENY();unlinkSync(quarantine);syncDir(dirname(dest));
|
|
58
|
+
return JSON.stringify({deleted:true,bytes:before.length,previous_sha256:SHA(before)});
|
|
59
|
+
}catch{try{if(lstatSync(quarantine).isFile())renameSync(quarantine,dest);}catch{}DENY();}
|
|
60
|
+
}
|
|
61
|
+
DENY();
|
|
62
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// P2-11B general owner-consented one-file source edit and selected Node test.
|
|
2
|
+
import {createHash,randomBytes} from 'node:crypto';
|
|
3
|
+
import {openSync,readFileSync,writeFileSync,renameSync,rmSync,lstatSync,realpathSync,statSync,constants,closeSync,fstatSync} from 'node:fs';
|
|
4
|
+
import {resolve,dirname,join,sep,relative} from 'node:path';
|
|
5
|
+
import {spawn} from 'node:child_process';
|
|
6
|
+
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);
|
|
7
|
+
const validPath=p=>typeof p==='string'&&p.length>0&&p.length<=256&&p.endsWith('.mjs')&&
|
|
8
|
+
/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(p)&&!p.split('/').some(x=>x==='..'||x==='.');
|
|
9
|
+
const hash=x=>createHash('sha256').update(x).digest('hex');
|
|
10
|
+
const states=new Map(),busy=new Set();
|
|
11
|
+
const fail=code=>({ok:false,error_code:code});
|
|
12
|
+
function target(root,path){
|
|
13
|
+
if(!validPath(path)||typeof root!=='string'||!root.startsWith('/')||root==='/'||resolve(root)!==root)return null;
|
|
14
|
+
try{
|
|
15
|
+
if(realpathSync(root)!==root||!lstatSync(root).isDirectory()||lstatSync(root).uid!==process.getuid?.())return null;
|
|
16
|
+
const dest=resolve(root,path);
|
|
17
|
+
if(relative(root,dest).startsWith('..'+sep))return null;
|
|
18
|
+
let cur=root;
|
|
19
|
+
for(const part of path.split('/')){
|
|
20
|
+
cur=join(cur,part);
|
|
21
|
+
const st=lstatSync(cur);
|
|
22
|
+
if(st.isSymbolicLink())return {error:'SYMLINK_DENIED'};
|
|
23
|
+
if(!st.isDirectory()&&!st.isFile())return null;
|
|
24
|
+
}
|
|
25
|
+
const st=lstatSync(dest);
|
|
26
|
+
if(!st.isFile()||st.nlink!==1||st.uid!==process.getuid?.()||st.size>262144||
|
|
27
|
+
realpathSync(dest)!==dest)return null;
|
|
28
|
+
return {path:dest,stat:st};
|
|
29
|
+
}catch{return {error:'FILE_NOT_FOUND'};}
|
|
30
|
+
}
|
|
31
|
+
export function validateDevFileAgentTool(tool,{rootId,deviceId,sessionId,now=Date.now()}={}){
|
|
32
|
+
const a=tool?.arguments,au=a?.file_authorization;
|
|
33
|
+
if(!a||!au||Object.getPrototypeOf(au)!==Object.prototype||!uuid(rootId)||a.root_id!==rootId||
|
|
34
|
+
!uuid(deviceId)||!uuid(sessionId)||!uuid(au.owner_user_id)||!uuid(au.connection_id)||
|
|
35
|
+
!uuid(au.consent_id)||au.device_id!==deviceId||au.root_id!==rootId||au.contract_version!=='dev-file-v1'||
|
|
36
|
+
!['dev_edit_block','dev_node_test'].includes(tool.name)||au.tool_id!==tool.name||
|
|
37
|
+
!validPath(a.path)||!validPath(a.test_path)||a.path!==au.path||a.test_path!==au.test_path||
|
|
38
|
+
!/^[a-f0-9]{64}$/.test(a.baseline_sha256||'')||a.baseline_sha256!==au.baseline_sha256||
|
|
39
|
+
!Number.isSafeInteger(au.expires_at)||au.expires_at<=now||
|
|
40
|
+
!Number.isSafeInteger(au.credential_version)||au.credential_version<0||
|
|
41
|
+
!Number.isSafeInteger(au.grant_version)||au.grant_version<0)throw Error('DEV_FILE_AGENT_DENIED');
|
|
42
|
+
const keys=Object.keys(a).sort().join(',');
|
|
43
|
+
const expected=tool.name==='dev_edit_block'?'baseline_sha256,expectedHash,file_authorization,new_string,old_string,path,root_id,test_path':
|
|
44
|
+
'baseline_sha256,command,file_authorization,path,root_id,test_path';
|
|
45
|
+
const authKeys='baseline_sha256,connection_id,consent_id,contract_version,credential_version,device_id,expires_at,grant_version,owner_user_id,path,root_id,test_path,tool_id';
|
|
46
|
+
if(keys!==expected.split(',').sort().join(',')||Object.keys(au).sort().join(',')!==authKeys.split(',').sort().join(','))throw Error('DEV_FILE_AGENT_DENIED');
|
|
47
|
+
if(tool.name==='dev_edit_block'&&(!/^[a-f0-9]{64}$/.test(a.expectedHash||'')||
|
|
48
|
+
typeof a.old_string!=='string'||a.old_string.length<1||a.old_string.length>8192||
|
|
49
|
+
typeof a.new_string!=='string'||a.new_string.length>8192))throw Error('DEV_FILE_AGENT_DENIED');
|
|
50
|
+
if(tool.name==='dev_node_test'&&a.command!=='node_test')throw Error('DEV_FILE_AGENT_DENIED');
|
|
51
|
+
return a;
|
|
52
|
+
}
|
|
53
|
+
function nodeTest(root,testPath){
|
|
54
|
+
return new Promise(resolvePromise=>{
|
|
55
|
+
const chunks=[],errs=[];let stdoutBytes=0,stderrBytes=0,timedOut=false,truncated=false,finished=false;
|
|
56
|
+
let child;
|
|
57
|
+
try{child=spawn(process.execPath,['--test',testPath],{
|
|
58
|
+
cwd:root,shell:false,stdio:['ignore','pipe','pipe'],
|
|
59
|
+
env:{PATH:process.env.PATH||'/usr/bin:/bin',HOME:process.env.HOME||'/tmp',NODE_ENV:'test',
|
|
60
|
+
LANG:'C',CI:'true'}
|
|
61
|
+
});}catch{return resolvePromise(fail('TEST_FAILED'));}
|
|
62
|
+
const take=(target,chunk,kind)=>{const bytes=kind==='out'?stdoutBytes:stderrBytes;
|
|
63
|
+
const allowed=Math.max(0,8192-bytes);if(chunk.length>allowed)truncated=true;
|
|
64
|
+
if(allowed)target.push(chunk.subarray(0,allowed));
|
|
65
|
+
if(kind==='out')stdoutBytes+=chunk.length;else stderrBytes+=chunk.length;
|
|
66
|
+
};
|
|
67
|
+
child.stdout?.on('data',c=>take(chunks,c,'out'));
|
|
68
|
+
child.stderr?.on('data',c=>take(errs,c,'err'));
|
|
69
|
+
const timer=setTimeout(()=>{timedOut=true;child.kill('SIGKILL');},6000);
|
|
70
|
+
child.on('error',()=>{clearTimeout(timer);if(!finished){finished=true;resolvePromise(fail('TEST_FAILED'));}});
|
|
71
|
+
child.on('close',(code,signal)=>{clearTimeout(timer);if(finished)return;finished=true;
|
|
72
|
+
resolvePromise({ok:!timedOut&&code===0,error_code:timedOut?'PROCESS_TIMEOUT':code===0?null:'TEST_FAILED',
|
|
73
|
+
exit_code:code,signal:signal||null,stdout:Buffer.concat(chunks).toString('utf8'),
|
|
74
|
+
stderr:Buffer.concat(errs).toString('utf8'),output_truncated:truncated});
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
export async function executeDevFileAgentTool({tool,root,rootId,deviceId,sessionId}={}){
|
|
79
|
+
const a=validateDevFileAgentTool(tool,{rootId,deviceId,sessionId});
|
|
80
|
+
const source=target(root,a.path),test=target(root,a.test_path);
|
|
81
|
+
if(source?.error)return JSON.stringify(fail(source.error));
|
|
82
|
+
if(test?.error)return JSON.stringify(fail(test.error));
|
|
83
|
+
if(!source||!test)return JSON.stringify(fail('ROOT_DENIED'));
|
|
84
|
+
if(tool.name==='dev_node_test')return JSON.stringify(await nodeTest(root,a.test_path));
|
|
85
|
+
const key=a.file_authorization.consent_id+':'+deviceId+':'+sessionId+':'+a.path;
|
|
86
|
+
if(busy.has(source.path))return JSON.stringify(fail('REVOKED'));
|
|
87
|
+
busy.add(source.path);
|
|
88
|
+
try{
|
|
89
|
+
const fd=openSync(source.path,constants.O_RDONLY|constants.O_NOFOLLOW);
|
|
90
|
+
let before,originalStat;
|
|
91
|
+
try{originalStat=fstatSync(fd);if(!originalStat.isFile()||originalStat.nlink!==1||
|
|
92
|
+
originalStat.dev!==source.stat.dev||originalStat.ino!==source.stat.ino)return JSON.stringify(fail('ROOT_DENIED'));
|
|
93
|
+
before=readFileSync(fd);
|
|
94
|
+
}finally{closeSync(fd);}
|
|
95
|
+
const current=hash(before),previous=states.get(key)||a.baseline_sha256;
|
|
96
|
+
if(current!==previous||current!==a.expectedHash)return JSON.stringify(fail('SHA_MISMATCH'));
|
|
97
|
+
const old=Buffer.from(a.old_string,'utf8'),replacement=Buffer.from(a.new_string,'utf8');
|
|
98
|
+
const index=before.indexOf(old);
|
|
99
|
+
if(index===-1||before.indexOf(old,index+1)!==-1)return JSON.stringify(fail('BLOCK_NOT_UNIQUE'));
|
|
100
|
+
const after=Buffer.concat([before.subarray(0,index),replacement,before.subarray(index+old.length)]);
|
|
101
|
+
const newSha=hash(after);
|
|
102
|
+
// Compare the same inode/hash immediately before atomic replacement.
|
|
103
|
+
const again=target(root,a.path);
|
|
104
|
+
if(!again||again.error||again.stat.ino!==source.stat.ino||again.stat.dev!==source.stat.dev||
|
|
105
|
+
hash(readFileSync(source.path))!==current)return JSON.stringify(fail('SHA_MISMATCH'));
|
|
106
|
+
const temporary=join(dirname(source.path),'.rs-file-'+randomBytes(12).toString('hex')+'.tmp');
|
|
107
|
+
try{
|
|
108
|
+
const out=openSync(temporary,constants.O_CREAT|constants.O_EXCL|constants.O_WRONLY|constants.O_NOFOLLOW,
|
|
109
|
+
originalStat.mode&0o777);
|
|
110
|
+
try{writeFileSync(out,after);}finally{closeSync(out);}
|
|
111
|
+
if(lstatSync(source.path).ino!==source.stat.ino||hash(readFileSync(source.path))!==current)
|
|
112
|
+
return JSON.stringify(fail('SHA_MISMATCH'));
|
|
113
|
+
renameSync(temporary,source.path);
|
|
114
|
+
}finally{rmSync(temporary,{force:true});}
|
|
115
|
+
if(newSha===a.baseline_sha256)states.delete(key);else states.set(key,newSha);
|
|
116
|
+
return JSON.stringify({ok:true,changed:newSha!==current,previous_sha256:current,sha256:newSha});
|
|
117
|
+
}catch{return JSON.stringify(fail('ROOT_DENIED'));}
|
|
118
|
+
finally{busy.delete(source.path);}
|
|
119
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {spawn,execFileSync} from 'node:child_process';
|
|
2
|
-
import {mkdtempSync,mkdirSync,readdirSync,realpathSync,readlinkSync,rmSync} from 'node:fs';
|
|
2
|
+
import {mkdtempSync,mkdirSync,readdirSync,realpathSync,readlinkSync,rmSync,existsSync} from 'node:fs';
|
|
3
3
|
import {tmpdir} from 'node:os';
|
|
4
4
|
import {join,dirname,resolve,sep} from 'node:path';
|
|
5
5
|
import {createInterface} from 'node:readline';
|
|
6
|
-
import {taskEnvelope} from '
|
|
6
|
+
import {taskEnvelope} from '../../shared/lib/contracts.mjs';
|
|
7
7
|
import {classifyC1Startup} from './c1-startup.mjs';
|
|
8
8
|
|
|
9
9
|
const denied=()=>{throw Error('C1_SUPERVISOR_DENIED');};
|
|
@@ -38,16 +38,18 @@ export function c1SandboxCommand(runtime,scratch){
|
|
|
38
38
|
const path=/=>\s+(\/\S+)\s+\(/.exec(line)?.[1]??/^\s*(\/\S+)\s+\(/.exec(line)?.[1];
|
|
39
39
|
if(path){const source=realpathSync(path);if(!source.startsWith('/usr/lib/'))denied();files.set(path,source);}
|
|
40
40
|
}
|
|
41
|
-
const source=realpathSync(join(runtime,'src')),modules=realpathSync(join(runtime,'node_modules'));
|
|
42
|
-
const
|
|
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']);
|
|
43
45
|
for(const [target] of files)for(let p=dirname(target);p!=='/';p=dirname(p))dirs.add(p);
|
|
44
46
|
const args=['--unshare-all','--die-with-parent','--new-session','--cap-drop','ALL'];
|
|
45
47
|
for(const d of [...dirs].sort((a,b)=>a.split('/').length-b.split('/').length))args.push('--dir',d);
|
|
46
|
-
args.push('--ro-bind',source,'/app/src','--ro-bind',modules,'/app/node_modules','--proc','/proc','--dev','/dev','--remount-ro','/dev');
|
|
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');
|
|
47
49
|
for(const [target,host] of files)args.push('--ro-bind',host,target);
|
|
48
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');
|
|
49
51
|
for(const kind of ['user','mnt','pid','net'])args.push('--setenv',`RS_C1_HOST_${kind.toUpperCase()}`,readlinkSync(`/proc/self/ns/${kind}`));
|
|
50
|
-
args.push('--','/usr/bin/node','--max-old-space-size=128','/app/src/device-agent/c1-worker.mjs');
|
|
52
|
+
args.push('--','/usr/bin/node','--max-old-space-size=128','/app/src/device-agent/core/c1-worker.mjs');
|
|
51
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');
|
|
52
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]];
|
|
53
55
|
}
|
|
@@ -78,7 +80,7 @@ export class C1Supervisor {
|
|
|
78
80
|
// owned DC child diagnostic before reporting a startup failure.
|
|
79
81
|
this.#child.once('close',()=>{this.#waiting?.reject(Error('C1_WORKER_EXITED_'+this.#startupCause+'_LAST_'+this.#startupStage));this.#waiting=null;});
|
|
80
82
|
this.#child.once('error',()=>{this.#waiting?.reject(Error('C1_WORKER_START_FAILED'));this.#waiting=null;});
|
|
81
|
-
this.#ready=this.#receive(10000).then(value=>{if(value.type!=='ready'||value.version!=='0.3.
|
|
83
|
+
this.#ready=this.#receive(10000).then(value=>{if(value.type!=='ready'||value.version!=='0.3.1')denied();});
|
|
82
84
|
}catch(error){this.close();throw error;}
|
|
83
85
|
}
|
|
84
86
|
#receive(timeout=7000){
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {isSyntheticAuxiliaryName} from '
|
|
2
|
-
import {prepareSyntheticAuxiliaryTransaction} from '../
|
|
3
|
-
import {prepareSyntheticFileTransaction} from '../
|
|
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
4
|
import {createInterface} from 'node:readline';
|
|
5
5
|
import {createRequire} from 'node:module';
|
|
6
6
|
import {dirname,join} from 'node:path';
|
|
@@ -9,8 +9,8 @@ import {constants,openSync,closeSync,fstatSync,readFileSync,writeFileSync,lstatS
|
|
|
9
9
|
import {execFileSync} from 'node:child_process';
|
|
10
10
|
import {Client} from '@modelcontextprotocol/sdk/client/index.js';
|
|
11
11
|
import {C1DcTransport} from './c1-dc-transport.mjs';
|
|
12
|
-
import {taskEnvelope} from '
|
|
13
|
-
import {makeVerifiedSyntheticWriteAdapter} from '../
|
|
12
|
+
import {taskEnvelope} from '../../shared/lib/contracts.mjs';
|
|
13
|
+
import {makeVerifiedSyntheticWriteAdapter} from '../policy/verified-synthetic-write.mjs';
|
|
14
14
|
import {assertLoopbackOnlyNetwork} from './c1-startup.mjs';
|
|
15
15
|
|
|
16
16
|
let stage='NAMESPACE';
|
|
@@ -39,7 +39,7 @@ stage='NOEXEC';
|
|
|
39
39
|
writeFileSync('/scratch/probe.txt','#!/bin/sh\nexit 0\n',{mode:0o700});
|
|
40
40
|
try{execFileSync('/scratch/probe.txt');fail();}catch(error){if(error.code!=='EACCES')throw error;}finally{unlinkSync('/scratch/probe.txt');}
|
|
41
41
|
stage='DC_PACKAGE';
|
|
42
|
-
const pkg=require.resolve('@wonderwhy-er/desktop-commander/package.json');if(require(pkg).version!=='0.3.
|
|
42
|
+
const pkg=require.resolve('@wonderwhy-er/desktop-commander/package.json');if(require(pkg).version!=='0.3.1')fail();
|
|
43
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
44
|
stage='DC_CONNECT';startupStage('DC_CONNECT_BEGIN');
|
|
45
45
|
await client.connect(transport);
|
|
@@ -55,7 +55,7 @@ async function rollback(){
|
|
|
55
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
56
|
pending=null;
|
|
57
57
|
}
|
|
58
|
-
stage='REQUEST';startupStage('READY_SEND');send({type:'ready',version:'0.3.
|
|
58
|
+
stage='REQUEST';startupStage('READY_SEND');send({type:'ready',version:'0.3.1'});
|
|
59
59
|
const lines=createInterface({input:process.stdin,crlfDelay:Infinity});
|
|
60
60
|
try{
|
|
61
61
|
for await(const line of lines){
|
|
@@ -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
|
+
}
|