@remoteshell/device 0.0.0-stage → 0.1.0-beta.1
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/bin/device.mjs +139 -0
- package/bin/enrollment-client.mjs +105 -0
- package/bin/lifecycle.mjs +172 -0
- package/package.json +18 -4
- package/src/common/bounded-search-adapter.mjs +116 -0
- package/src/common/bounded-search-policy.mjs +24 -0
- package/src/common/config.mjs +14 -0
- package/src/common/contracts.mjs +26 -0
- package/src/common/errors.mjs +9 -0
- package/src/common/events.mjs +5 -0
- package/src/common/execution-policy.mjs +41 -0
- package/src/common/isolated-read-adapter.mjs +50 -0
- package/src/common/isolated-read-boundary.mjs +50 -0
- package/src/common/isolated-read-mount.mjs +27 -0
- package/src/common/isolated-read-policy.mjs +29 -0
- package/src/common/lifecycle-events.mjs +13 -0
- package/src/common/runtime-timing.mjs +9 -0
- package/src/common/synthetic-auxiliary-adapter.mjs +75 -0
- package/src/common/synthetic-auxiliary-policy.mjs +21 -0
- package/src/common/synthetic-file-adapter.mjs +26 -0
- package/src/common/synthetic-file-transaction.mjs +87 -0
- package/src/common/synthetic-write-adapter.mjs +152 -0
- package/src/common/synthetic-write-mount.mjs +23 -0
- package/src/common/synthetic-write-policy.mjs +53 -0
- package/src/common/tool-registry.mjs +58 -0
- package/src/common/verified-bounded-search.mjs +12 -0
- package/src/common/verified-isolated-read.mjs +15 -0
- package/src/common/verified-synthetic-write.mjs +14 -0
- package/src/device-agent/c1-dc-transport.mjs +26 -0
- package/src/device-agent/c1-startup.mjs +22 -0
- package/src/device-agent/c1-supervisor.mjs +109 -0
- package/src/device-agent/c1-worker.mjs +88 -0
- package/src/device-agent/fixture.txt +2 -0
- package/src/device-agent/main.mjs +230 -0
- package/README.md +0 -3
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import {lstatSync,realpathSync,readFileSync} from 'node:fs';
|
|
2
|
+
import {isAbsolute,resolve} from 'node:path';
|
|
3
|
+
|
|
4
|
+
const deny=()=>{throw Object.assign(new Error('SYNTHETIC_WRITE_DISABLED'),{code:'SYNTHETIC_WRITE_DISABLED'});};
|
|
5
|
+
const decodeMount=value=>value.replace(/\\040/g,' ').replace(/\\011/g,'\t').replace(/\\012/g,'\n').replace(/\\134/g,'\\');
|
|
6
|
+
|
|
7
|
+
// The write root must be its own writable tmpfs mount. A chmod'd directory or
|
|
8
|
+
// caller-provided boolean is not evidence of filesystem isolation.
|
|
9
|
+
export function assertSyntheticWritableMount(root,{mountInfoPath='/proc/self/mountinfo',uid=process.geteuid?.()}={}){
|
|
10
|
+
if(process.platform!=='linux'||!Number.isInteger(uid)||typeof root!=='string'||!isAbsolute(root)||root==='/'||root.length>1024)deny();
|
|
11
|
+
let stat,canonical,content;
|
|
12
|
+
try{stat=lstatSync(root);canonical=realpathSync(root);content=readFileSync(mountInfoPath,'utf8');}catch{deny();}
|
|
13
|
+
if(!stat.isDirectory()||stat.isSymbolicLink()||canonical!==resolve(root)||stat.uid!==uid||(stat.mode&0o077)!==0)deny();
|
|
14
|
+
const found=content.split('\n').filter(Boolean).some(line=>{
|
|
15
|
+
const halves=line.split(' - ');if(halves.length!==2)return false;
|
|
16
|
+
const fields=halves[0].split(' '),mountpoint=decodeMount(fields[4]||'');
|
|
17
|
+
if(mountpoint!==canonical)return false;
|
|
18
|
+
const vfs=new Set((fields[5]||'').split(',')),fs=halves[1].split(' '),superblock=new Set((fs[2]||'').split(','));
|
|
19
|
+
return fs[0]==='tmpfs'&&vfs.has('rw')&&superblock.has('rw')&&['nosuid','nodev','noexec'].every(flag=>vfs.has(flag));
|
|
20
|
+
});
|
|
21
|
+
if(!found)deny();
|
|
22
|
+
return Object.freeze({root:canonical,uid,writable:true,filesystem:'tmpfs'});
|
|
23
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import {auxiliaryNames,isSyntheticAuxiliaryName,auxiliarySchema,validateAuxiliaryArguments} from './synthetic-auxiliary-policy.mjs';
|
|
2
|
+
import {RuntimeError,ERROR_CODES} from './errors.mjs';
|
|
3
|
+
|
|
4
|
+
export const SYNTHETIC_WRITE_LIMITS=Object.freeze({fileBytes:32768,requestBytes:65536,maxPathBytes:256,maxFiles:8,maxRootBytes:65536,maxRequests:16,maxOutputBytes:4096,timeoutMs:5000});
|
|
5
|
+
const names=Object.freeze(['write_file','edit_block','create_directory','move_file','write_pdf',...auxiliaryNames]);
|
|
6
|
+
const sensitive=/(?:^|[_-])(?:secret|credential|token|password|private|key)(?:[_-]|$)|^id_[a-z0-9]+$/i;
|
|
7
|
+
const deny=code=>{throw new RuntimeError(code,'Synthetic write denied');};
|
|
8
|
+
export const isSyntheticWriteName=name=>names.includes(name);
|
|
9
|
+
const pathSchema=Object.freeze({type:'string',minLength:1,maxLength:256,pattern:'^([A-Za-z0-9_-]+/)*[A-Za-z0-9_-]+\\.txt$'});
|
|
10
|
+
const directorySchema=Object.freeze({type:'string',minLength:1,maxLength:256,pattern:'^[A-Za-z0-9_-]+(/[A-Za-z0-9_-]+)*$'});
|
|
11
|
+
const fileSchema=Object.freeze({...pathSchema,pattern:'^([A-Za-z0-9_-]+/)*[A-Za-z0-9_-]+\\.(txt|pdf)$'});
|
|
12
|
+
const pdfSchema=Object.freeze({...pathSchema,pattern:'^([A-Za-z0-9_-]+/)*[A-Za-z0-9_-]+\\.pdf$'});
|
|
13
|
+
const textSchema=Object.freeze({type:'string',maxLength:32768});
|
|
14
|
+
const schema=(properties,required)=>Object.freeze({type:'object',properties:Object.freeze({...properties,device_id:{type:'string'}}),required:Object.freeze(required),additionalProperties:false});
|
|
15
|
+
const schemas=Object.freeze({
|
|
16
|
+
...Object.fromEntries(auxiliaryNames.map(name=>[name,auxiliarySchema(name)])),
|
|
17
|
+
create_directory:schema({path:directorySchema},['path']),
|
|
18
|
+
move_file:schema({source:fileSchema,destination:fileSchema},['source','destination']),
|
|
19
|
+
write_pdf:schema({path:pdfSchema,content:textSchema},['path','content']),
|
|
20
|
+
write_file:schema({path:pathSchema,content:textSchema},['path','content']),
|
|
21
|
+
edit_block:schema({path:pathSchema,old_string:{...textSchema,minLength:1},new_string:textSchema,expectedHash:{type:'string',pattern:'^[a-f0-9]{64}$'}},['path','old_string','new_string','expectedHash']),
|
|
22
|
+
});
|
|
23
|
+
export const syntheticWriteArgumentKeys=name=>Object.keys(schemas[name]?.properties??{}).filter(k=>k!=='device_id');
|
|
24
|
+
export function listSyntheticWriteTools(){
|
|
25
|
+
return names.map(name=>({name,description:({write_file:'Create an approved synthetic text file',edit_block:'Edit a synthetic text file with SHA-256 precondition',create_directory:'Create one empty synthetic directory',move_file:'Move one synthetic text/PDF file without overwriting',write_pdf:'Create a synthetic PDF from plain Markdown'})[name]??'Approved private DC configuration or redacted diagnostics',inputSchema:schemas[name],annotations:{readOnlyHint:['get_config','get_usage_stats','get_recent_tool_calls'].includes(name),destructiveHint:!['get_config','get_usage_stats','get_recent_tool_calls'].includes(name),idempotentHint:false,openWorldHint:false}}));
|
|
26
|
+
}
|
|
27
|
+
// Shared wire validation: device selection is stripped by MCP before this call.
|
|
28
|
+
// Consent, live revocation, audit and supervisor attestation are separate mandatory gates.
|
|
29
|
+
export function validateSyntheticWriteTool(call,{enabled=false}={}){
|
|
30
|
+
if(enabled!==true||!call||!isSyntheticWriteName(call.name))deny(ERROR_CODES.TOOL_DENIED);
|
|
31
|
+
if(isSyntheticAuxiliaryName(call.name))return Object.freeze({name:call.name,arguments:validateAuxiliaryArguments(call.name,call.arguments)});
|
|
32
|
+
const args=call.arguments,keys=syntheticWriteArgumentKeys(call.name);
|
|
33
|
+
if(!args||Object.getPrototypeOf(args)!==Object.prototype||Object.keys(args).some(key=>!keys.includes(key)))deny(ERROR_CODES.ARGUMENTS_DENIED);
|
|
34
|
+
if(keys.some(key=>args[key]===undefined))deny(ERROR_CODES.ARGUMENTS_DENIED);
|
|
35
|
+
if(['create_directory','move_file','write_pdf'].includes(call.name)){
|
|
36
|
+
for(const key of call.name==='move_file'?['source','destination']:['path']){
|
|
37
|
+
const value=args[key],pattern=schemas[call.name].properties[key].pattern;
|
|
38
|
+
if(typeof value!=='string'||Buffer.byteLength(value)>256||!(new RegExp(pattern)).test(value)||value.split('/').some(part=>sensitive.test(part.replace(/\.(txt|pdf)$/i,''))))deny(ERROR_CODES.ARGUMENTS_DENIED);
|
|
39
|
+
}
|
|
40
|
+
if(call.name==='move_file'&&(args.source===args.destination||args.source.split('.').pop()!==args.destination.split('.').pop()))deny(ERROR_CODES.ARGUMENTS_DENIED);
|
|
41
|
+
if(call.name==='write_pdf'&&(typeof args.content!=='string'||Buffer.byteLength(args.content)>32768||/[\x00-\x1f<>]/.test(args.content.replace(/[\r\n\t]/g,''))||/^\s*(?:---|\+\+\+)/.test(args.content)||/!\[|\]\(|(?:https?|file|data):|^\s*\[[^\]]+\]:/im.test(args.content)))deny(ERROR_CODES.ARGUMENTS_DENIED);
|
|
42
|
+
return Object.freeze({name:call.name,arguments:Object.freeze(Object.fromEntries(keys.map(key=>[key,args[key]])))});
|
|
43
|
+
}
|
|
44
|
+
const path=args.path;
|
|
45
|
+
if(typeof path!=='string'||Buffer.byteLength(path)>256||!/^([A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+\.txt$/.test(path)||path.split('/').some(part=>sensitive.test(part.replace(/\.txt$/i,''))))deny(ERROR_CODES.ARGUMENTS_DENIED);
|
|
46
|
+
const text=value=>typeof value==='string'&&Buffer.byteLength(value)<=32768&&!/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value);
|
|
47
|
+
if(call.name==='write_file'){
|
|
48
|
+
if(!text(args.content))deny(ERROR_CODES.ARGUMENTS_DENIED);
|
|
49
|
+
}else if(!text(args.old_string)||args.old_string.length===0||!text(args.new_string)||typeof args.expectedHash!=='string'||!(/^[a-f0-9]{64}$/).test(args.expectedHash))deny(ERROR_CODES.ARGUMENTS_DENIED);
|
|
50
|
+
if(Buffer.byteLength(JSON.stringify(args))>65536)deny(ERROR_CODES.ARGUMENTS_DENIED);
|
|
51
|
+
return Object.freeze({name:call.name,arguments:Object.freeze(Object.fromEntries(keys.map(key=>[key,args[key]])))});
|
|
52
|
+
}
|
|
53
|
+
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import {listSyntheticWriteTools,isSyntheticWriteName} from './synthetic-write-policy.mjs';
|
|
2
|
+
export {validateSyntheticWriteTool,isSyntheticWriteName} from './synthetic-write-policy.mjs';
|
|
3
|
+
import {RuntimeError,ERROR_CODES} from './errors.mjs';
|
|
4
|
+
import {validateReadArguments,validateReadPath} from './isolated-read-boundary.mjs';
|
|
5
|
+
const noArgs=Object.freeze({type:'object',properties:Object.freeze({}),additionalProperties:false});
|
|
6
|
+
const descriptors=Object.freeze([Object.freeze({name:'pwd',description:'Read remote working directory',inputSchema:noArgs}),Object.freeze({name:'read_fixture',description:'Read fixed test fixture',inputSchema:noArgs})]);
|
|
7
|
+
const isolatedNames=Object.freeze(['list_directory','get_file_info','read_file','read_multiple_files']);
|
|
8
|
+
const isolatedSchema=Object.freeze({type:'object',properties:{path:{type:'string',maxLength:256},device_id:{type:'string'}},required:['path'],additionalProperties:false});
|
|
9
|
+
const multipleReadSchema=Object.freeze({type:'object',properties:{paths:{type:'array',minItems:1,maxItems:8,items:{type:'string',maxLength:256}},device_id:{type:'string'}},required:['paths'],additionalProperties:false});
|
|
10
|
+
const boundedSearchNames=Object.freeze(['start_search','get_more_search_results','stop_search','list_searches']);
|
|
11
|
+
const BOUNDED_SEARCH_LIMITS_PAGE=50;
|
|
12
|
+
const searchStartSchema=Object.freeze({type:'object',properties:{path:{type:'string',maxLength:256},pattern:{type:'string',minLength:1,maxLength:256},searchType:{type:'string',enum:['files','content'],default:'files'},filePattern:{type:'string',maxLength:128},ignoreCase:{type:'boolean',default:true},maxResults:{type:'integer',minimum:1,maximum:200,default:200},literalSearch:{type:'boolean',default:false},device_id:{type:'string'}},required:['path','pattern'],additionalProperties:false});
|
|
13
|
+
const searchPageSchema=Object.freeze({type:'object',properties:{sessionId:{type:'string',minLength:47,maxLength:47},offset:{type:'integer',minimum:0},length:{type:'integer',minimum:1,maximum:50,default:50},device_id:{type:'string'}},required:['sessionId'],additionalProperties:false});
|
|
14
|
+
const searchStopSchema=Object.freeze({type:'object',properties:{sessionId:{type:'string',minLength:47,maxLength:47},device_id:{type:'string'}},required:['sessionId'],additionalProperties:false});
|
|
15
|
+
export function isIsolatedReadName(name){return isolatedNames.includes(name);}
|
|
16
|
+
export function isBoundedSearchName(name){return boundedSearchNames.includes(name);}
|
|
17
|
+
export function listTools({p2Mode=false,oauthEnabled=false,isolatedReadEnabled=false,boundedSearchEnabled=false,syntheticWriteEnabled=false}={}){
|
|
18
|
+
const tools=p2Mode?[...descriptors,{name:'list_devices',description:'List devices authorized for this connection',inputSchema:noArgs}]:[...descriptors];
|
|
19
|
+
if(p2Mode&&isolatedReadEnabled)for(const name of isolatedNames)tools.push({name,description:'Isolated test-only read',inputSchema:name==='read_multiple_files'?multipleReadSchema:isolatedSchema});
|
|
20
|
+
if(p2Mode&&boundedSearchEnabled)tools.push({name:'list_searches',description:'List only this connection and device search handles in the approved root',inputSchema:{...noArgs,properties:{device_id:{type:'string'}}}},{name:'start_search',description:'Start a bounded filename or content search in the approved isolated root',inputSchema:searchStartSchema},{name:'get_more_search_results',description:'Read the next bounded page from an authorized search session',inputSchema:searchPageSchema},{name:'stop_search',description:'Stop and invalidate an authorized search session',inputSchema:searchStopSchema});
|
|
21
|
+
if(p2Mode&&syntheticWriteEnabled)tools.push(...listSyntheticWriteTools());
|
|
22
|
+
const searchSchemas={list_searches:{...noArgs,properties:{device_id:{type:'string'}}},start_search:searchStartSchema,get_more_search_results:searchPageSchema,stop_search:searchStopSchema};
|
|
23
|
+
return tools.map(x=>({...x,inputSchema:p2Mode&&syntheticWriteEnabled&&isSyntheticWriteName(x.name)?x.inputSchema:boundedSearchEnabled&&isBoundedSearchName(x.name)?searchSchemas[x.name]:isolatedReadEnabled&&isIsolatedReadName(x.name)?(x.name==='read_multiple_files'?multipleReadSchema:isolatedSchema):p2Mode?(x.name==='list_devices'?noArgs:{type:'object',properties:{device_id:{type:'string',description:'Registered device ID; optional if only one authorized device'}},additionalProperties:false}):noArgs,...(oauthEnabled?{securitySchemes:[{type:'oauth2',scopes:['remoteshell:call']}],_meta:{securitySchemes:[{type:'oauth2',scopes:['remoteshell:call']}]}}:{})}));
|
|
24
|
+
}
|
|
25
|
+
export function validateActiveTool(call){if(!call||!descriptors.some(t=>t.name===call.name))throw new RuntimeError(ERROR_CODES.TOOL_DENIED,'Tool denied');if(!call.arguments||typeof call.arguments!=='object'||Array.isArray(call.arguments)||Object.keys(call.arguments).length)throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Arguments denied');return {name:call.name,arguments:{}};}
|
|
26
|
+
export function validateIsolatedReadTool(call,{enabled=false}={}){if(!enabled||!call||!isIsolatedReadName(call.name))throw new RuntimeError(ERROR_CODES.TOOL_DENIED,'Tool denied');try{return {name:call.name,arguments:validateReadArguments(call.name,call.arguments)};}catch{throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Arguments denied');}}
|
|
27
|
+
export function validateBoundedSearchTool(call,{enabled=false}={}){
|
|
28
|
+
if(!enabled||!call||!isBoundedSearchName(call.name))throw new RuntimeError(ERROR_CODES.TOOL_DENIED,'Tool denied');
|
|
29
|
+
const deny=()=>{throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Arguments denied');};
|
|
30
|
+
const args=call.arguments;if(!args||typeof args!=='object'||Array.isArray(args)||Object.getPrototypeOf(args)!==Object.prototype)deny();
|
|
31
|
+
const keys=Object.keys(args);
|
|
32
|
+
if(call.name==='list_searches'){if(keys.length)deny();return {name:call.name,arguments:Object.freeze({})};}
|
|
33
|
+
if(call.name==='start_search'){
|
|
34
|
+
if(keys.some(k=>!['path','pattern','searchType','filePattern','ignoreCase','maxResults','literalSearch'].includes(k))||typeof args.path!=='string'||args.path.length<1||args.path.length>256||typeof args.pattern!=='string'||args.pattern.length<1||args.pattern.length>256||/[\x00-\x1f\x7f]/.test(args.pattern))deny();
|
|
35
|
+
try{validateReadPath(args.path,{allowRoot:true});}catch{deny();}
|
|
36
|
+
const searchType=args.searchType??'files';if(!['files','content'].includes(searchType))deny();
|
|
37
|
+
const filePattern=args.filePattern;if(filePattern!==undefined&&(typeof filePattern!=='string'||filePattern.length>128||/[\\/\x00-\x1f\x7f]/.test(filePattern)||filePattern.startsWith('.')||filePattern.includes('..')))deny();
|
|
38
|
+
if(args.ignoreCase!==undefined&&typeof args.ignoreCase!=='boolean'||args.literalSearch!==undefined&&typeof args.literalSearch!=='boolean')deny();
|
|
39
|
+
const maxResults=args.maxResults??200;if(!Number.isSafeInteger(maxResults)||maxResults<1||maxResults>200)deny();
|
|
40
|
+
return {name:call.name,arguments:Object.freeze({path:args.path,pattern:args.pattern,searchType,...(filePattern===undefined?{}:{filePattern}),ignoreCase:args.ignoreCase??true,maxResults,literalSearch:args.literalSearch??false})};
|
|
41
|
+
}
|
|
42
|
+
if(keys.some(k=>!['sessionId','offset','length'].includes(k))||typeof args.sessionId!=='string'||!/^rsb_[A-Za-z0-9_-]{43}$/.test(args.sessionId))deny();
|
|
43
|
+
if(call.name==='stop_search')return {name:call.name,arguments:Object.freeze({sessionId:args.sessionId})};
|
|
44
|
+
const offset=args.offset??0,length=args.length??50;
|
|
45
|
+
if(!Number.isSafeInteger(offset)||offset<0||!Number.isSafeInteger(length)||length<1||length>50)deny();
|
|
46
|
+
return {name:call.name,arguments:Object.freeze({sessionId:args.sessionId,...(args.offset===undefined?{}:{offset}),length})};
|
|
47
|
+
}
|
|
48
|
+
export function validateAgentBoundedSearchTool(call,{enabled=false}={}){
|
|
49
|
+
if(!enabled||!call||!isBoundedSearchName(call.name))throw new RuntimeError(ERROR_CODES.TOOL_DENIED,'Tool denied');
|
|
50
|
+
if(['start_search','list_searches'].includes(call.name))return validateBoundedSearchTool(call,{enabled:true});
|
|
51
|
+
const args=call.arguments,keys=args&&typeof args==='object'&&!Array.isArray(args)?Object.keys(args):[];
|
|
52
|
+
if(!args||Object.getPrototypeOf(args)!==Object.prototype||keys.some(k=>!['sessionId','offset','length'].includes(k))||typeof args.sessionId!=='string'||!/^search_[A-Za-z0-9_-]{1,120}$/.test(args.sessionId))throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Arguments denied');
|
|
53
|
+
if(call.name==='stop_search')return {name:call.name,arguments:Object.freeze({sessionId:args.sessionId})};
|
|
54
|
+
const offset=args.offset,length=args.length;
|
|
55
|
+
if(!Number.isSafeInteger(offset)||offset<0||!Number.isSafeInteger(length)||length<1||length>BOUNDED_SEARCH_LIMITS_PAGE)throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Arguments denied');
|
|
56
|
+
return {name:call.name,arguments:Object.freeze({sessionId:args.sessionId,offset,length})};
|
|
57
|
+
}
|
|
58
|
+
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import {assertReadOnlyMount} from './isolated-read-mount.mjs';
|
|
2
|
+
import {makeBoundedSearchAdapter} from './bounded-search-adapter.mjs';
|
|
3
|
+
|
|
4
|
+
export function makeVerifiedBoundedSearchAdapter({root,rootScopeId,client}={}){
|
|
5
|
+
if(typeof root!=='string'||typeof rootScopeId!=='string'||!client||typeof client.callTool!=='function')throw Error('BOUNDED_SEARCH_DISABLED');
|
|
6
|
+
const initial=assertReadOnlyMount(root);
|
|
7
|
+
const run=makeBoundedSearchAdapter({root:initial.root,rootScopeId,client,verifyRoot:expected=>{
|
|
8
|
+
const current=assertReadOnlyMount(expected);
|
|
9
|
+
if(current.root!==initial.root||current.uid!==initial.uid||!current.readOnly)throw Error('BOUNDED_SEARCH_DISABLED');
|
|
10
|
+
}});
|
|
11
|
+
return run;
|
|
12
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import {assertReadOnlyMount} from './isolated-read-mount.mjs';
|
|
2
|
+
import {makeIsolatedReadAdapter} from './isolated-read-adapter.mjs';
|
|
3
|
+
|
|
4
|
+
// The Agent must use this entrypoint, not the low-level mock-friendly adapter.
|
|
5
|
+
// Recheck Linux mount isolation on each request; never trust caller booleans.
|
|
6
|
+
export function makeVerifiedIsolatedReadAdapter({root,client}={}){
|
|
7
|
+
if(typeof root!=='string'||!client||typeof client.callTool!=='function')throw Error('ISOLATED_READ_DISABLED');
|
|
8
|
+
const initial=assertReadOnlyMount(root);
|
|
9
|
+
const run=makeIsolatedReadAdapter({root:initial.root,readonlyMountVerified:true,client});
|
|
10
|
+
return async (name,args)=>{
|
|
11
|
+
const current=assertReadOnlyMount(initial.root);
|
|
12
|
+
if(current.root!==initial.root||current.uid!==initial.uid||!current.readOnly)throw Error('ISOLATED_READ_DISABLED');
|
|
13
|
+
return run(name,args);
|
|
14
|
+
};
|
|
15
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import {assertSyntheticWritableMount} from './synthetic-write-mount.mjs';
|
|
2
|
+
import {makeSyntheticWriteAdapter} from './synthetic-write-adapter.mjs';
|
|
3
|
+
|
|
4
|
+
// Production entrypoint is opt-in and re-attests the exact mount on every call.
|
|
5
|
+
// The low-level adapter remains useful for unit tests but is not a security proof.
|
|
6
|
+
export function makeVerifiedSyntheticWriteAdapter({enabled=false,root,client,authorized,onAudit}={}){
|
|
7
|
+
if(enabled!==true||typeof root!=='string'||!client||typeof client.callTool!=='function')throw Error('SYNTHETIC_WRITE_DISABLED');
|
|
8
|
+
const initial=assertSyntheticWritableMount(root);
|
|
9
|
+
return makeSyntheticWriteAdapter({enabled:true,root:initial.root,client,authorized,onAudit,verifySandbox:expected=>{
|
|
10
|
+
const current=assertSyntheticWritableMount(expected);
|
|
11
|
+
if(current.root!==initial.root||current.uid!==initial.uid||current.filesystem!=='tmpfs')throw Error('SYNTHETIC_WRITE_DISABLED');
|
|
12
|
+
return true;
|
|
13
|
+
}});
|
|
14
|
+
}
|
|
@@ -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,109 @@
|
|
|
1
|
+
import {spawn,execFileSync} from 'node:child_process';
|
|
2
|
+
import {mkdtempSync,mkdirSync,readdirSync,realpathSync,readlinkSync,rmSync} 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 '../common/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'));verifyTree(source);verifyTree(modules);
|
|
42
|
+
const dirs=new Set(['/app','/app/src','/app/node_modules','/scratch','/home']);
|
|
43
|
+
for(const [target] of files)for(let p=dirname(target);p!=='/';p=dirname(p))dirs.add(p);
|
|
44
|
+
const args=['--unshare-all','--die-with-parent','--new-session','--cap-drop','ALL'];
|
|
45
|
+
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');
|
|
47
|
+
for(const [target,host] of files)args.push('--ro-bind',host,target);
|
|
48
|
+
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
|
+
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');
|
|
51
|
+
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
|
+
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
|
+
}
|
|
54
|
+
|
|
55
|
+
export class C1Supervisor {
|
|
56
|
+
#child;#scratch;#waiting=null;#busy=false;#closed=false;#post;#ready;#bufferBytes=0;#startupCause='UNKNOWN';#startupStage='START';
|
|
57
|
+
constructor({runtime,post}={}){
|
|
58
|
+
if(typeof post!=='function')denied();this.#post=post;
|
|
59
|
+
this.#scratch=mkdtempSync(join(tmpdir(),'rs-c1-supervisor-'));mkdirSync(join(this.#scratch,'root'),{mode:0o700});mkdirSync(join(this.#scratch,'home'),{mode:0o700});
|
|
60
|
+
try{
|
|
61
|
+
const [command,args]=c1SandboxCommand(resolve(runtime),this.#scratch);
|
|
62
|
+
this.#child=spawn(command,args,{env:{PATH:'/usr/sbin:/usr/bin:/sbin:/bin'},stdio:['pipe','pipe','pipe']});
|
|
63
|
+
this.#child.stdin.on('error',()=>{this.#waiting?.reject(Error('C1_WORKER_PIPE_CLOSED'));this.#waiting=null;});
|
|
64
|
+
// Protocol stdout is bounded. stderr never contains Gateway credentials and
|
|
65
|
+
// is not forwarded into MCP responses.
|
|
66
|
+
let diagnostic='';
|
|
67
|
+
this.#child.stderr.on('data',chunk=>{
|
|
68
|
+
diagnostic=(diagnostic+chunk.toString()).slice(-2048);
|
|
69
|
+
// An allowlisted checkpoint; never retain or relay arbitrary child stderr.
|
|
70
|
+
const stages=[...diagnostic.matchAll(/C1_PROGRESS_(DC_CONNECT_BEGIN|DC_CONNECT_DONE|READY_SEND)/g)];
|
|
71
|
+
if(stages.length)this.#startupStage=stages.at(-1)[1];
|
|
72
|
+
const cause=classifyC1Startup(diagnostic);if(cause!=='UNKNOWN')this.#startupCause=cause;
|
|
73
|
+
});
|
|
74
|
+
const lines=createInterface({input:this.#child.stdout,crlfDelay:Infinity});
|
|
75
|
+
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();}});
|
|
76
|
+
// 'exit' may fire before the stdio streams finish draining. Wait for
|
|
77
|
+
// 'close' so the bounded, sanitized stderr classifier sees the final
|
|
78
|
+
// owned DC child diagnostic before reporting a startup failure.
|
|
79
|
+
this.#child.once('close',()=>{this.#waiting?.reject(Error('C1_WORKER_EXITED_'+this.#startupCause+'_LAST_'+this.#startupStage));this.#waiting=null;});
|
|
80
|
+
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.0')denied();});
|
|
82
|
+
}catch(error){this.close();throw error;}
|
|
83
|
+
}
|
|
84
|
+
#receive(timeout=7000){
|
|
85
|
+
return new Promise((resolve,reject)=>{
|
|
86
|
+
if(this.#closed||this.#waiting)return reject(Error('C1_PROTOCOL_STATE'));
|
|
87
|
+
const timer=setTimeout(()=>{
|
|
88
|
+
this.#waiting=null;
|
|
89
|
+
// A fixed, bounded diagnostic distinguishes a live worker stalled in
|
|
90
|
+
// DC connect from an exited one or a worker that never reached connect.
|
|
91
|
+
const alive=this.#child&&this.#child.exitCode===null&&this.#child.signalCode===null;
|
|
92
|
+
const stage=this.#startupStage;
|
|
93
|
+
reject(Error('C1_WORKER_TIMEOUT_'+(alive?'ALIVE_':'EXITED_')+stage));
|
|
94
|
+
},timeout);
|
|
95
|
+
this.#waiting={resolve:v=>{clearTimeout(timer);resolve(v);},reject:e=>{clearTimeout(timer);reject(e);}};
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
ready(){return this.#ready;}
|
|
99
|
+
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;}
|
|
100
|
+
async execute(value){
|
|
101
|
+
if(this.#busy||this.#closed)denied();this.#busy=true;
|
|
102
|
+
try{
|
|
103
|
+
await this.#ready;
|
|
104
|
+
return await executeC1Transaction(value,{command:(type,task)=>this.#command(type,task),post:this.#post});
|
|
105
|
+
}catch(error){if(/C1_(WORKER|ROLLBACK|COMMIT|PROTOCOL)/.test(error.message))this.close({uncertain:error.message==='C1_COMMIT_UNCERTAIN'});throw error;}
|
|
106
|
+
finally{this.#busy=false;}
|
|
107
|
+
}
|
|
108
|
+
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});}
|
|
109
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import {isSyntheticAuxiliaryName} from '../common/synthetic-auxiliary-policy.mjs';
|
|
2
|
+
import {prepareSyntheticAuxiliaryTransaction} from '../common/synthetic-auxiliary-adapter.mjs';
|
|
3
|
+
import {prepareSyntheticFileTransaction} from '../common/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 '../common/contracts.mjs';
|
|
13
|
+
import {makeVerifiedSyntheticWriteAdapter} from '../common/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.0')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.0'});
|
|
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
|
+
}
|