@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.
Files changed (35) hide show
  1. package/bin/device.mjs +139 -0
  2. package/bin/enrollment-client.mjs +105 -0
  3. package/bin/lifecycle.mjs +172 -0
  4. package/package.json +18 -4
  5. package/src/common/bounded-search-adapter.mjs +116 -0
  6. package/src/common/bounded-search-policy.mjs +24 -0
  7. package/src/common/config.mjs +14 -0
  8. package/src/common/contracts.mjs +26 -0
  9. package/src/common/errors.mjs +9 -0
  10. package/src/common/events.mjs +5 -0
  11. package/src/common/execution-policy.mjs +41 -0
  12. package/src/common/isolated-read-adapter.mjs +50 -0
  13. package/src/common/isolated-read-boundary.mjs +50 -0
  14. package/src/common/isolated-read-mount.mjs +27 -0
  15. package/src/common/isolated-read-policy.mjs +29 -0
  16. package/src/common/lifecycle-events.mjs +13 -0
  17. package/src/common/runtime-timing.mjs +9 -0
  18. package/src/common/synthetic-auxiliary-adapter.mjs +75 -0
  19. package/src/common/synthetic-auxiliary-policy.mjs +21 -0
  20. package/src/common/synthetic-file-adapter.mjs +26 -0
  21. package/src/common/synthetic-file-transaction.mjs +87 -0
  22. package/src/common/synthetic-write-adapter.mjs +152 -0
  23. package/src/common/synthetic-write-mount.mjs +23 -0
  24. package/src/common/synthetic-write-policy.mjs +53 -0
  25. package/src/common/tool-registry.mjs +58 -0
  26. package/src/common/verified-bounded-search.mjs +12 -0
  27. package/src/common/verified-isolated-read.mjs +15 -0
  28. package/src/common/verified-synthetic-write.mjs +14 -0
  29. package/src/device-agent/c1-dc-transport.mjs +26 -0
  30. package/src/device-agent/c1-startup.mjs +22 -0
  31. package/src/device-agent/c1-supervisor.mjs +109 -0
  32. package/src/device-agent/c1-worker.mjs +88 -0
  33. package/src/device-agent/fixture.txt +2 -0
  34. package/src/device-agent/main.mjs +230 -0
  35. package/README.md +0 -3
@@ -0,0 +1,9 @@
1
+ export const ERROR_CODES=Object.freeze({CONFIG_ERROR:'CONFIG_ERROR',AUTH_DENIED:'AUTH_DENIED',TOOL_DENIED:'TOOL_DENIED',ARGUMENTS_DENIED:'ARGUMENTS_DENIED',DEVICE_OFFLINE:'DEVICE_OFFLINE',DEVICE_RECONNECTED:'DEVICE_RECONNECTED',QUEUE_FULL:'QUEUE_FULL',REQUEST_TIMEOUT:'REQUEST_TIMEOUT',UPSTREAM_TOOL_ERROR:'UPSTREAM_TOOL_ERROR',INTERNAL_ERROR:'INTERNAL_ERROR',SESSION_DENIED:'SESSION_DENIED'});
2
+ export class RuntimeError extends Error {
3
+ constructor(code,publicMessage='Request failed',{cause}={}) {
4
+ if(!Object.values(ERROR_CODES).includes(code))throw new TypeError('Unknown error code');
5
+ super(publicMessage,{cause});this.name='RuntimeError';this.code=code;this.publicMessage=publicMessage;
6
+ }
7
+ toPublic(){return {error:{code:this.code,message:this.publicMessage}};}
8
+ }
9
+ export function safeError(error){return error instanceof RuntimeError?error.toPublic():{error:{code:ERROR_CODES.INTERNAL_ERROR,message:'Internal error'}};}
@@ -0,0 +1,5 @@
1
+ import {redact} from './config.mjs';
2
+ import {RuntimeError,ERROR_CODES} from './errors.mjs';
3
+ const names=['request_id','session_id','tool_name','event_type','time','duration_ms','outcome','error_code'];
4
+ export function event(value){if(!value||typeof value!=='object'||Array.isArray(value))throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Invalid event');const out={};for(const k of names){if(value[k]!==undefined){if(k==='duration_ms'){if(!Number.isFinite(value[k])||value[k]<0)throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Invalid duration_ms');}else if(typeof value[k]!=='string'||!value[k])throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Invalid event field: '+k);out[k]=value[k];}}for(const k of ['request_id','event_type','time'])if(!out[k])throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Missing event field: '+k);if(Number.isNaN(Date.parse(out.time)))throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Invalid event time');return Object.freeze(out);}
5
+ export function createEmitter(emit=()=>{}){if(typeof emit!=='function')throw new TypeError('Invalid emitter');return {emit(value){const e=event(redact(value));emit(e);return e;}};}
@@ -0,0 +1,41 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {RuntimeError, ERROR_CODES} from './errors.mjs';
3
+ import {validateActiveTool} from './tool-registry.mjs';
4
+
5
+ // P3-A: server-owned, versioned allowlist. P2 connection/device authorization remains mandatory.
6
+ export const EXECUTION_POLICY_VERSION = 'p3-a-1';
7
+ const supported = Object.freeze(['pwd', 'read_fixture']);
8
+ const deny = (code=ERROR_CODES.TOOL_DENIED) => {throw new RuntimeError(code, 'Execution policy denied');};
9
+ const uuid = value => typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
10
+
11
+ // Canonical arguments are exactly {}; no extension fields, inherited keys or prototype tricks.
12
+ export function canonicalExecutionTool(value) {
13
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
14
+ Object.getPrototypeOf(value) !== Object.prototype ||
15
+ Object.keys(value).some(key => key !== 'name' && key !== 'arguments')) return deny(ERROR_CODES.ARGUMENTS_DENIED);
16
+ const call = validateActiveTool(value);
17
+ if (!supported.includes(call.name) || Object.keys(value.arguments).length !== 0 ||
18
+ Object.getPrototypeOf(value.arguments) !== Object.prototype) return deny(ERROR_CODES.ARGUMENTS_DENIED);
19
+ return Object.freeze({name:call.name, arguments:Object.freeze({})});
20
+ }
21
+
22
+ // Evaluate only trusted Gateway principal and P2-authorized device decision, not client claims.
23
+ export function authorizeGatewayExecution({principal, device, tool}) {
24
+ if (!principal || !device || !uuid(principal.owner_id) || !uuid(principal.connection_id) ||
25
+ !uuid(device.device_id) || principal.owner_id !== device.user_id ||
26
+ principal.connection_id !== device.connection_id) return deny();
27
+ const canonicalTool = canonicalExecutionTool(tool);
28
+ const arguments_hash = createHash('sha256').update(JSON.stringify(canonicalTool.arguments)).digest('hex');
29
+ return Object.freeze({policy_version:EXECUTION_POLICY_VERSION,tool:canonicalTool,arguments_hash});
30
+ }
31
+
32
+ // Independent Agent allowlist recheck; no remote verdict can introduce new executables.
33
+ export function authorizeAgentExecution(tool) {
34
+ return canonicalExecutionTool(tool);
35
+ }
36
+
37
+ // Discovery is a scoped read operation, not an unguarded metadata endpoint.
38
+ export function authorizeDiscovery(principal) {
39
+ if (!principal || !uuid(principal.owner_id) || !uuid(principal.connection_id)) return deny();
40
+ return Object.freeze({policy_version:EXECUTION_POLICY_VERSION,tool:'list_devices'});
41
+ }
@@ -0,0 +1,50 @@
1
+ import {openSync,readSync,closeSync,lstatSync} from 'node:fs';
2
+ import {relative} from 'node:path';
3
+ import {resolveReadTarget,validateReadArguments,READ_ONLY_CAPS} from './isolated-read-boundary.mjs';
4
+
5
+ // Only usable by an isolated test Agent with an OS-enforced read-only mount.
6
+ // A JS pre-check cannot protect Desktop Commander's separate pathname open against races.
7
+ export function makeIsolatedReadAdapter({root,readonlyMountVerified=false,client}={}){
8
+ if(!readonlyMountVerified||!client||typeof client.callTool!=='function')throw Error('ISOLATED_READ_DISABLED');
9
+ const max=READ_ONLY_CAPS.maxOutputBytes;
10
+ return async function execute(name,args){
11
+ const {path}=validateReadArguments(name,args);
12
+ if(name==='read_multiple_files'){
13
+ const paths=args.paths.map(value=>resolveReadTarget(root,value,{type:'file'}));
14
+ if(paths.some(target=>target.size>READ_ONLY_CAPS.maxFileBytes)||paths.reduce((sum,target)=>sum+target.size,0)>max)throw Error('READ_SCOPE_DENIED');
15
+ for(const target of paths){const fd=openSync(target.path,'r');try{const st=lstatSync(target.path);if(st.size!==target.size||st.size>READ_ONLY_CAPS.maxFileBytes)throw Error('READ_SCOPE_DENIED');const buf=Buffer.alloc(st.size),n=readSync(fd,buf,0,st.size,0);if(n!==st.size||buf.includes(0))throw Error('READ_SCOPE_DENIED');new TextDecoder('utf-8',{fatal:true}).decode(buf);}finally{closeSync(fd);}}
16
+ const result=await client.callTool({name,arguments:{paths:paths.map(target=>target.path)}});
17
+ if(result.isError)throw Error('UPSTREAM_TOOL_ERROR');
18
+ const parts=result.content;if(!Array.isArray(parts)||parts.length>4||parts.some(item=>item.type!=='text'||typeof item.text!=='string'))throw Error('READ_SCOPE_DENIED');
19
+ let value=parts.map(item=>item.text).join('\n');if(Buffer.byteLength(value,'utf8')>max)throw Error('READ_SCOPE_DENIED');
20
+ for(const target of paths)value=value.split(target.path).join(relative(root,target.path));
21
+ return value;
22
+ }
23
+ const type=name==='list_directory'?'directory':name==='read_file'?'file':'metadata';
24
+ const target=resolveReadTarget(root,path,{type});
25
+ if(name==='read_file'){
26
+ if(target.size>READ_ONLY_CAPS.maxFileBytes)throw Error('READ_SCOPE_DENIED');
27
+ // Reopening through the DC pathname requires the root be immutable/read-only at OS level.
28
+ const fd=openSync(target.path,'r');
29
+ try{
30
+ const st=lstatSync(target.path);
31
+ if(st.size!==target.size||st.size>READ_ONLY_CAPS.maxFileBytes)throw Error('READ_SCOPE_DENIED');
32
+ const buf=Buffer.alloc(st.size),bytes=readSync(fd,buf,0,st.size,0);
33
+ if(bytes!==st.size||buf.includes(0)||new TextDecoder('utf-8',{fatal:true}).decode(buf).includes('\ufffd'))throw Error('READ_SCOPE_DENIED');
34
+ }finally{closeSync(fd);}
35
+ }
36
+ const upstream=name==='list_directory'?{path:target.path,depth:1}:{path:target.path};
37
+ const result=await client.callTool({name,arguments:upstream});
38
+ if(result.isError)throw Error('UPSTREAM_TOOL_ERROR');
39
+ const parts=result.content;
40
+ if(!Array.isArray(parts)||parts.length>4||parts.some(item=>item.type!=='text'||typeof item.text!=='string'))throw Error('READ_SCOPE_DENIED');
41
+ const value=parts.map(item=>item.text).join('\n');
42
+ if(Buffer.byteLength(value,'utf8')>max)throw Error('READ_SCOPE_DENIED');
43
+ if(name==='list_directory'){
44
+ const lines=value?value.split('\n'):[];
45
+ if(lines.length>READ_ONLY_CAPS.maxEntries||lines.some(line=>!/^\[(?:FILE|DIR)\] [^\r\n]+$/.test(line)))throw Error('READ_SCOPE_DENIED');
46
+ for(const line of lines){const entry=line.replace(/^\[(?:FILE|DIR)\] /,'');if(entry.includes('/')||entry.includes('\\\\')||entry.startsWith('.')||/(?:secret|credential|token|password|private)/i.test(entry))throw Error('READ_SCOPE_DENIED');}
47
+ }
48
+ return value;
49
+ };
50
+ }
@@ -0,0 +1,50 @@
1
+ import {lstatSync,realpathSync,readdirSync} from 'node:fs';
2
+ import {isAbsolute,relative,resolve,sep,basename} from 'node:path';
3
+
4
+ const SECRET=/(?:^|[._-])(?:secret|credential|token|password|private|key)(?:[._-]|$)|^id_[a-z0-9]+$|\.(?:pem|key|p12|pfx|kdbx)$/i;
5
+ const hidden=x=>x.startsWith('.')||SECRET.test(x);
6
+ const deny=()=>{throw new Error('READ_SCOPE_DENIED');};
7
+ export function validateReadPath(value,{allowRoot=false}={}){
8
+ if(typeof value!=='string'||value.length>256||value.length===0||value.includes('\\')||value.includes('%')||/[\x00-\x1f\x7f]/.test(value)||isAbsolute(value)||value.startsWith('/')||value.startsWith('~')||/^[a-zA-Z]:/.test(value))deny();
9
+ if(value==='.'&&allowRoot)return '.';
10
+ const parts=value.split('/');
11
+ if(parts.some(p=>!p||p==='.'||p==='..'||hidden(p)||p.normalize('NFKC')!==p))deny();
12
+ return parts.join('/');
13
+ }
14
+ export function validateReadRoot(root){
15
+ if(typeof root!=='string'||!isAbsolute(root)||root==='/'||root.length>1024)deny();
16
+ const stat=lstatSync(root);if(!stat.isDirectory()||stat.isSymbolicLink())deny();
17
+ const real=realpathSync(root);if(real!==resolve(root))deny();
18
+ if((stat.mode&0o022)!==0)deny();
19
+ return real;
20
+ }
21
+ export function resolveReadTarget(root,requested,{type='file',maxEntries=128}={}){
22
+ const canonical=validateReadRoot(root);
23
+ const rel=validateReadPath(requested,{allowRoot:type==='directory'});
24
+ const parts=rel==='.'?[]:rel.split('/');
25
+ let path=canonical;
26
+ for(const part of parts){path=resolve(path,part);const stat=lstatSync(path);if(stat.isSymbolicLink()||!stat.isFile()&&!stat.isDirectory())deny();}
27
+ const real=realpathSync(path);
28
+ const delta=relative(canonical,real);
29
+ if(delta==='..'||delta.startsWith('..'+sep)||isAbsolute(delta))deny();
30
+ const stat=lstatSync(path);
31
+ if(type==='directory'&&!stat.isDirectory()||type==='file'&&!stat.isFile()||type==='metadata'&&!stat.isFile()&&!stat.isDirectory())deny();
32
+ if(type==='directory'){
33
+ const names=readdirSync(path);
34
+ if(names.length>maxEntries||names.some(hidden))deny();
35
+ // Fail closed rather than return entries which DC would render as safe-looking directories.
36
+ for(const name of names){const child=lstatSync(resolve(path,name));if(child.isSymbolicLink()||!child.isFile()&&!child.isDirectory())deny();}
37
+ }
38
+ return {root:canonical,path:real,size:stat.size,type:stat.isDirectory()?'directory':'file'};
39
+ }
40
+ export function validateReadArguments(name,args){
41
+ if(name==='read_multiple_files'){
42
+ if(!args||Object.getPrototypeOf(args)!==Object.prototype||Object.keys(args).some(k=>k!=='paths')||!Array.isArray(args.paths)||args.paths.length<1||args.paths.length>8)deny();
43
+ const paths=args.paths.map(path=>validateReadPath(path));
44
+ if(new Set(paths).size!==paths.length)deny();
45
+ return Object.freeze({paths:Object.freeze(paths)});
46
+ }
47
+ if(!['list_directory','get_file_info','read_file'].includes(name)||!args||Object.getPrototypeOf(args)!==Object.prototype||Object.keys(args).some(k=>k!=='path'))deny();
48
+ return Object.freeze({path:validateReadPath(args.path,{allowRoot:name==='list_directory'})});
49
+ }
50
+ export const READ_ONLY_CAPS=Object.freeze({maxFileBytes:65536,maxOutputBytes:32768,maxEntries:128});
@@ -0,0 +1,27 @@
1
+ import {readFileSync,statSync} from 'node:fs';
2
+ import {validateReadRoot} from './isolated-read-boundary.mjs';
3
+
4
+ const deny=()=>{throw new Error('ISOLATED_READ_DISABLED');};
5
+ const decodeMount=s=>s.replace(/\\040/g,' ').replace(/\\011/g,'\t').replace(/\\012/g,'\n').replace(/\\134/g,'\\');
6
+ export function assertReadOnlyMount(root,{mountInfoPath='/proc/self/mountinfo',uid=process.geteuid?.()}={}){
7
+ if(process.platform!=='linux'||!Number.isInteger(uid))deny();
8
+ const canonical=validateReadRoot(root);
9
+ const stat=statSync(canonical);
10
+ if(stat.uid!==uid || (stat.mode&0o077)!==0)deny();
11
+ let content;
12
+ try{content=readFileSync(mountInfoPath,'utf8');}catch{deny();}
13
+ const found=content.split('\n').filter(Boolean).some(line=>{
14
+ const halves=line.split(' - ');
15
+ if(halves.length!==2)return false;
16
+ const fields=halves[0].split(' ');
17
+ const mounted=decodeMount(fields[4]||'');
18
+ // Require an exact mountpoint, not merely a read-only parent directory.
19
+ if(mounted!==canonical)return false;
20
+ const vfs=fields[5]?.split(',')||[];
21
+ const fs=halves[1].split(' ');
22
+ const superblock=fs[2]?.split(',')||[];
23
+ return vfs.includes('ro')&&superblock.includes('ro');
24
+ });
25
+ if(!found)deny();
26
+ return Object.freeze({root:canonical,uid,readOnly:true});
27
+ }
@@ -0,0 +1,29 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {RuntimeError,ERROR_CODES} from './errors.mjs';
3
+ import {validateReadArguments} from './isolated-read-boundary.mjs';
4
+ const deny=(code=ERROR_CODES.TOOL_DENIED)=>{throw new RuntimeError(code,'Isolated read denied');};
5
+ const uuid=x=>typeof x==='string'&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(x);
6
+ const names=Object.freeze(['list_directory','get_file_info','read_file','read_multiple_files']);
7
+ const plain=x=>x!==null&&typeof x==='object'&&!Array.isArray(x)&&Object.getPrototypeOf(x)===Object.prototype;
8
+ export const ISOLATED_READ_POLICY_VERSION='55-a-test-1';
9
+
10
+ export function canonicalIsolatedReadTool(value){
11
+ if(!plain(value)||Object.keys(value).some(k=>!['name','arguments'].includes(k))||!names.includes(value.name))deny();
12
+ let args;
13
+ try{args=validateReadArguments(value.name,value.arguments);}catch{deny(ERROR_CODES.ARGUMENTS_DENIED);}
14
+ return Object.freeze({name:value.name,arguments:args});
15
+ }
16
+ // Requires a server-owned opt-in scope, not a user-supplied argument.
17
+ export function authorizeIsolatedGatewayRead({principal,device,tool,scope}={}){
18
+ if(!plain(principal)||!plain(device)||!plain(scope)||scope.enabled!==true
19
+ ||!uuid(principal.owner_id)||!uuid(principal.connection_id)||!uuid(device.device_id)
20
+ ||principal.owner_id!==device.user_id||principal.connection_id!==device.connection_id
21
+ ||scope.owner_id!==principal.owner_id||scope.connection_id!==principal.connection_id||scope.device_id!==device.device_id)deny();
22
+ const canonical=canonicalIsolatedReadTool(tool);
23
+ return Object.freeze({policy_version:ISOLATED_READ_POLICY_VERSION,tool:canonical,
24
+ arguments_hash:createHash('sha256').update(JSON.stringify(canonical.arguments)).digest('hex')});
25
+ }
26
+ export function authorizeIsolatedAgentRead({tool,enabled=false}={}){
27
+ if(enabled!==true)deny();
28
+ return canonicalIsolatedReadTool(tool);
29
+ }
@@ -0,0 +1,13 @@
1
+ import {createEmitter} from './events.mjs';
2
+ let injectedSink = null;
3
+ // In-process test seam only. Production remains no-op; no environment or persistent sink.
4
+ export function setLifecycleEventSinkForTest(sink) {
5
+ if (sink !== null && typeof sink !== 'function') throw new TypeError('Invalid event sink');
6
+ injectedSink = sink;
7
+ }
8
+ export function createLifecycleReporter(emit=createEmitter(e => injectedSink?.(e))){
9
+ return function lifecycle({request_id,session_id,tool_name,event_type,outcome,error_code,duration_ms}){
10
+ if(!request_id||!event_type)return;
11
+ emit.emit({request_id,session_id,tool_name,event_type,time:new Date().toISOString(),...(duration_ms===undefined?{}:{duration_ms:Number.isFinite(duration_ms)?Math.max(0,duration_ms):0}),...(outcome===undefined?{}:{outcome}),...(error_code===undefined?{}:{error_code})});
12
+ };
13
+ }
@@ -0,0 +1,9 @@
1
+ import {performance} from 'node:perf_hooks';
2
+ const phases=new Set(['queued','task_sent','poll_received','native_begin','native_done','result_begin','result_done','result_accepted','deadline']);
3
+ export function createRuntimeTiming(component,{enabled=process.env.RS_RUNTIME_DIAGNOSTICS==='true',sink=line=>process.stderr.write(line+'\n')}={}){
4
+ if(!['gateway','agent'].includes(component))throw Error('Invalid timing component');
5
+ return ({request_id,tool_name,phase})=>{
6
+ if(!enabled||!phases.has(phase)||!['pwd','read_fixture'].includes(tool_name)||typeof request_id!=='string'||!/^[-a-zA-Z0-9_]{1,128}$/.test(request_id))return;
7
+ sink('RS_TIMING '+JSON.stringify({component,request_id,tool_name,phase,monotonic_ms:Math.round(performance.now()*1000)/1000}));
8
+ };
9
+ }
@@ -0,0 +1,75 @@
1
+ import {validateAuxiliaryArguments} from './synthetic-auxiliary-policy.mjs';
2
+ const deny=()=>{throw Object.assign(Error('SYNTHETIC_AUXILIARY_DENIED'),{code:'SYNTHETIC_AUXILIARY_DENIED'});};
3
+ const rollbackDenied=()=>{throw Object.assign(Error('SYNTHETIC_WRITE_ROLLBACK_UNVERIFIED'),{code:'SYNTHETIC_WRITE_ROLLBACK_UNVERIFIED'});};
4
+ const textOf=result=>{
5
+ if(result?.isError||!Array.isArray(result?.content)||result.content.length>8||result.content.some(x=>x.type!=='text'||typeof x.text!=='string'))deny();
6
+ const text=result.content.map(x=>x.text).join('\n');if(Buffer.byteLength(text)>262144)deny();return text;
7
+ };
8
+ const call=async(client,name,args)=>{
9
+ const result=await client.callTool({name,arguments:args},undefined,{signal:AbortSignal.timeout(5000)});textOf(result);return result;
10
+ };
11
+ async function config(client){
12
+ const result=await call(client,'get_config',{});let value=result.structuredContent?.config;
13
+ if(!value){const text=textOf(result);if(!text.startsWith('Current configuration:\n'))deny();try{value=JSON.parse(text.slice('Current configuration:\n'.length));}catch{deny();}}
14
+ const out={};for(const key of ['fileReadLineLimit','fileWriteLineLimit']){
15
+ if(!Number.isSafeInteger(value?.[key])||value[key]<1||value[key]>100000)deny();out[key]=value[key];
16
+ }
17
+ if(typeof value.telemetryEnabled==='boolean')out.telemetryEnabled=value.telemetryEnabled;
18
+ return out;
19
+ }
20
+
21
+ // Production is restricted to a private DC process/HOME, bound to one
22
+ // owner + connection + device for its lifetime by the C1 worker.
23
+ export async function prepareSyntheticAuxiliaryTransaction(client,tool,{feedbackAuthorized=false}={}){
24
+ const name=tool.name,args=validateAuxiliaryArguments(name,tool.arguments);
25
+ const previous=name==='set_config_value'?await config(client):null;
26
+ let changed=false;
27
+ return {
28
+ async execute(){
29
+ if(name==='get_config')return JSON.stringify({scope:'synthetic_dc_instance',config:await config(client)});
30
+ if(name==='set_config_value'){
31
+ changed=true;await call(client,name,args);await this.verify();return JSON.stringify({scope:'synthetic_dc_instance',updated:true,key:args.key,value:args.value});
32
+ }
33
+ if(name==='get_usage_stats'){
34
+ const text=textOf(await call(client,name,{}));
35
+ const match=/Total calls:\s*(\d+)\s*\((\d+) successful,\s*(\d+) failed\)/.exec(text);if(!match)deny();
36
+ const [totalCalls,successfulCalls,failedCalls]=match.slice(1).map(Number);
37
+ if(![totalCalls,successfulCalls,failedCalls].every(Number.isSafeInteger)||successfulCalls+failedCalls!==totalCalls)deny();
38
+ return JSON.stringify({scope:'synthetic_dc_instance',totalCalls,successfulCalls,failedCalls});
39
+ }
40
+ if(name==='get_recent_tool_calls'){
41
+ const text=textOf(await call(client,name,args)),start=text.indexOf('\n\n');let entries;
42
+ try{entries=JSON.parse(text.slice(start+2));}catch{deny();}
43
+ if(start<0||!Array.isArray(entries)||entries.length>args.maxResults)deny();
44
+ const calls=entries.map(entry=>{
45
+ if(!/^[a-z][a-z0-9_]{0,63}$/.test(entry?.toolName??'')||!Number.isFinite(entry.duration)||entry.duration<0)deny();
46
+ return {toolName:entry.toolName,durationMs:Math.min(Math.round(entry.duration),3600000)};
47
+ });
48
+ return JSON.stringify({scope:'synthetic_dc_instance',calls});
49
+ }
50
+ // The product worker never grants this flag. Do not open an external
51
+ // feedback form or submit telemetry while publication remains on HOLD.
52
+ if(name==='give_feedback_to_desktop_commander'){
53
+ if(feedbackAuthorized!==true)deny();
54
+ await call(client,name,{});return JSON.stringify({feedbackInvoked:true});
55
+ }
56
+ deny();
57
+ },
58
+ async verify(){if(name==='set_config_value'){if((await config(client))[args.key]!==args.value)deny();changed=true;}},
59
+ async rollback(){
60
+ if(!changed)return;
61
+ try{await call(client,'set_config_value',{key:args.key,value:previous[args.key]});if((await config(client))[args.key]!==previous[args.key])deny();changed=false;}
62
+ catch{rollbackDenied();}
63
+ },
64
+ };
65
+ }
66
+
67
+ export function makeSyntheticAuxiliaryAdapter({root,client,verifySandbox,authorized,onAudit}){
68
+ return async(name,args,context)=>{
69
+ const uuid=x=>typeof x==='string'&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(x);
70
+ if(!context||!['owner_id','connection_id','device_id','consent_id','requestId'].every(k=>uuid(context[k]))||context.permission!==name||context.consent!==true||context.revoked===true||await authorized(context,name)!==true||verifySandbox(root)!==true)deny();
71
+ const plan=await prepareSyntheticAuxiliaryTransaction(client,{name,arguments:args});
72
+ try{const result=await plan.execute();if(Buffer.byteLength(result)>4096)deny();await onAudit({request_id:context.requestId,tool:name,decision:'allow',outcome:'verified'});return result;}
73
+ catch(error){await plan.rollback();throw error;}
74
+ };
75
+ }
@@ -0,0 +1,21 @@
1
+ export const auxiliaryNames=Object.freeze(['get_config','set_config_value','get_usage_stats','get_recent_tool_calls','give_feedback_to_desktop_commander']);
2
+ export const isSyntheticAuxiliaryName=name=>auxiliaryNames.includes(name);
3
+ const configKeys=Object.freeze(['fileReadLineLimit','fileWriteLineLimit']);
4
+ export function auxiliarySchema(name){
5
+ const properties=name==='set_config_value'?{key:{type:'string',enum:configKeys},value:{type:'integer',minimum:1,maximum:2000}}:name==='get_recent_tool_calls'?{maxResults:{type:'integer',minimum:1,maximum:10,default:10}}:{};
6
+ return {type:'object',properties:{...properties,device_id:{type:'string'}},required:name==='set_config_value'?['key','value']:[],additionalProperties:false};
7
+ }
8
+ export function validateAuxiliaryArguments(name,args){
9
+ const deny=()=>{throw Object.assign(Error('ARGUMENTS_DENIED'),{code:'ARGUMENTS_DENIED'});};
10
+ if(!isSyntheticAuxiliaryName(name)||!args||Object.getPrototypeOf(args)!==Object.prototype)deny();
11
+ const keys=Object.keys(auxiliarySchema(name).properties).filter(k=>k!=='device_id');
12
+ if(Object.keys(args).some(k=>!keys.includes(k)))deny();
13
+ if(name==='set_config_value'){
14
+ if(!configKeys.includes(args.key)||!Number.isSafeInteger(args.value)||args.value<1||args.value>2000)deny();
15
+ return Object.freeze({key:args.key,value:args.value});
16
+ }
17
+ if(name==='get_recent_tool_calls'){
18
+ const maxResults=args.maxResults??10;if(!Number.isSafeInteger(maxResults)||maxResults<1||maxResults>10)deny();return Object.freeze({maxResults});
19
+ }
20
+ return Object.freeze({});
21
+ }
@@ -0,0 +1,26 @@
1
+ import {openSync,closeSync,fstatSync,lstatSync,unlinkSync,constants} from 'node:fs';
2
+ import {join} from 'node:path';
3
+ import {validateSyntheticWriteTool,SYNTHETIC_WRITE_LIMITS as limits} from './synthetic-write-policy.mjs';
4
+ import {prepareSyntheticFileTransaction} from './synthetic-file-transaction.mjs';
5
+
6
+ const deny=()=>{throw Object.assign(Error('SYNTHETIC_WRITE_DENIED'),{code:'SYNTHETIC_WRITE_DENIED'});};
7
+ const uuid=value=>typeof value==='string'&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
8
+ export function makeSyntheticFileAdapter({root,client,verifySandbox,authorized,onAudit}){
9
+ let requests=0;
10
+ return async (name,args,context)=>{
11
+ const tool=validateSyntheticWriteTool({name,arguments:args},{enabled:true});
12
+ if(!['create_directory','move_file','write_pdf'].includes(name)||++requests>limits.maxRequests||!context||!['owner_id','connection_id','device_id','consent_id'].every(key=>uuid(context[key]))||!/^[-A-Za-z0-9_]{8,64}$/.test(context.requestId??'')||context.consent!==true||context.revoked===true||context.permission!==name||await authorized(context,name)!==true||verifySandbox(root)!==true)deny();
13
+ const lock=join(root,'.rs-c1-writer.lock');let fd,owned,plan;
14
+ try{
15
+ fd=openSync(lock,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);owned=fstatSync(fd);
16
+ plan=prepareSyntheticFileTransaction(root,tool);
17
+ const result=await client.callTool({name,arguments:plan.arguments},undefined,{signal:AbortSignal.timeout(limits.timeoutMs)});
18
+ if(result?.isError||!Array.isArray(result?.content)||result.content.length>8||result.content.some(item=>item.type!=='text'||typeof item.text!=='string')||Buffer.byteLength(result.content.map(item=>item.text).join('\n'))>limits.maxOutputBytes)deny();
19
+ const output=plan.verify();await onAudit({request_id:context.requestId,tool:name,decision:'allow',outcome:'verified'});return output;
20
+ }catch(error){
21
+ plan?.rollback();if(error?.code==='SYNTHETIC_WRITE_ROLLBACK_UNVERIFIED')throw error;deny();
22
+ }finally{
23
+ if(fd!==undefined){try{const st=lstatSync(lock);if(st.dev!==owned.dev||st.ino!==owned.ino||st.isSymbolicLink())deny();unlinkSync(lock);}finally{closeSync(fd);}}
24
+ }
25
+ };
26
+ }
@@ -0,0 +1,87 @@
1
+ import {lstatSync,realpathSync,readdirSync,readFileSync,renameSync,unlinkSync,rmdirSync} from 'node:fs';
2
+ import {join,dirname,relative,isAbsolute} from 'node:path';
3
+ import {createHash} from 'node:crypto';
4
+ import {validateSyntheticWriteTool,SYNTHETIC_WRITE_LIMITS as limits} from './synthetic-write-policy.mjs';
5
+
6
+ const deny=()=>{throw Object.assign(Error('SYNTHETIC_FILE_DENIED'),{code:'SYNTHETIC_FILE_DENIED'});};
7
+ const rollbackDenied=()=>{throw Object.assign(Error('SYNTHETIC_WRITE_ROLLBACK_UNVERIFIED'),{code:'SYNTHETIC_WRITE_ROLLBACK_UNVERIFIED'});};
8
+ const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
9
+ const exists=path=>{try{return lstatSync(path);}catch(e){if(e.code!=='ENOENT')throw e;return null;}};
10
+ const same=(path,expected)=>{const st=exists(path);if(!st||st.isSymbolicLink()||st.dev!==expected.dev||st.ino!==expected.ino||st.nlink!==expected.nlink)deny();return st;};
11
+
12
+ export function inspectSyntheticFileTree(root){
13
+ const canonical=realpathSync(root),st=lstatSync(root);if(canonical!==root||!st.isDirectory()||st.isSymbolicLink()||(st.mode&0o077)!==0)deny();
14
+ let files=0,bytes=0,entries=0;
15
+ // File names are checked separately to avoid inventing a move destination.
16
+ const scan=(dir,depth)=>{
17
+ if(depth>8)deny();
18
+ for(const name of readdirSync(dir)){
19
+ if(dir===root&&name==='.rs-c1-writer.lock')continue;
20
+ const path=join(dir,name),st=lstatSync(path);
21
+ if(dir===root&&name==='.dc-home'&&st.isDirectory()&&!st.isSymbolicLink()&&(st.mode&0o077)===0&&realpathSync(path)===path)continue;
22
+ if(++entries>64||st.isSymbolicLink()||realpathSync(path)!==path||st.uid!==process.geteuid())deny();
23
+ if(st.isDirectory()){validateSyntheticWriteTool({name:'create_directory',arguments:{path:relative(root,path)}},{enabled:true});scan(path,depth+1);}
24
+ else if(st.isFile()&&st.nlink===1){
25
+ const rel=relative(root,path),ext=rel.endsWith('.pdf')?'pdf':'txt';
26
+ validateSyntheticWriteTool({name:'move_file',arguments:{source:rel,destination:rel==='probe.'+ext?'other.'+ext:'probe.'+ext}},{enabled:true});
27
+ if(++files>limits.maxFiles||st.size>limits.fileBytes||(bytes+=st.size)>limits.maxRootBytes)deny();
28
+ const data=readFileSync(path);
29
+ if(ext==='pdf'){if(data.subarray(0,5).toString()!=='%PDF-')deny();}
30
+ else if(data.includes(0)||/[\x01-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(new TextDecoder('utf-8',{fatal:true}).decode(data)))deny();
31
+ }else deny();
32
+ }
33
+ };
34
+ scan(root,0);return {files,bytes,entries};
35
+ }
36
+
37
+ // The production caller owns an attested private tmpfs and a single-writer lock.
38
+ // This plan is also held by the worker until the Gateway's finalize handshake.
39
+ export function prepareSyntheticFileTransaction(root,tool){
40
+ const {name,arguments:args}=validateSyntheticWriteTool(tool,{enabled:true});
41
+ if(!['create_directory','move_file','write_pdf'].includes(name))deny();
42
+ const inventory=inspectSyntheticFileTree(root);
43
+ const target=rel=>{
44
+ const path=join(root,rel),delta=relative(root,path);
45
+ if(!delta||delta.startsWith('..')||isAbsolute(delta))deny();
46
+ let current=root;
47
+ for(const part of relative(root,dirname(path)).split('/').filter(Boolean)){
48
+ current=join(current,part);const st=lstatSync(current);
49
+ if(!st.isDirectory()||st.isSymbolicLink()||realpathSync(current)!==current)deny();
50
+ }
51
+ return path;
52
+ };
53
+ const path=target(name==='move_file'?args.destination:args.path);
54
+ if(exists(path)||inventory.entries>=64||name==='write_pdf'&&inventory.files>=limits.maxFiles)deny();
55
+ const source=name==='move_file'?target(args.source):null;
56
+ const before=source?lstatSync(source):null;
57
+ if(before&&(!before.isFile()||before.isSymbolicLink()||before.nlink!==1||before.size>limits.fileBytes))deny();
58
+ const digest=source?hash(readFileSync(source)):null;
59
+ let after=null;
60
+ return {
61
+ arguments:name==='move_file'?{source,destination:path}:name==='write_pdf'?{path,content:args.content}:{path},
62
+ verify(){
63
+ const st=lstatSync(path);
64
+ if(st.isSymbolicLink()||st.uid!==process.geteuid()||realpathSync(path)!==path)deny();
65
+ if(name==='create_directory'){if(!st.isDirectory()||readdirSync(path).length)deny();}
66
+ else if(!st.isFile()||st.nlink!==1||st.size>limits.fileBytes)deny();
67
+ if(name==='move_file'&&(exists(source)||st.dev!==before.dev||st.ino!==before.ino||hash(readFileSync(path))!==digest))deny();
68
+ inspectSyntheticFileTree(root);after=st;
69
+ return JSON.stringify(name==='create_directory'?{created:true,type:'directory'}:name==='move_file'?{moved:true,sha256:digest}:{created:true,type:'pdf',bytes:st.size,sha256:hash(readFileSync(path))});
70
+ },
71
+ rollback(){
72
+ try{
73
+ const st=exists(path);
74
+ if(name==='move_file'){
75
+ if(st){same(path,before);if(exists(source)||hash(readFileSync(path))!==digest)deny();renameSync(path,source);}
76
+ same(source,before);if(hash(readFileSync(source))!==digest)deny();
77
+ }else if(st){
78
+ if(after)same(path,after);
79
+ if(st.isSymbolicLink()||st.uid!==process.geteuid()||realpathSync(path)!==path)deny();
80
+ if(name==='create_directory'){if(!st.isDirectory()||readdirSync(path).length)deny();rmdirSync(path);}
81
+ else {if(!st.isFile()||st.nlink!==1)deny();unlinkSync(path);}
82
+ }
83
+ if(exists(path))deny();
84
+ }catch{rollbackDenied();}
85
+ },
86
+ };
87
+ }
@@ -0,0 +1,152 @@
1
+ import {makeSyntheticAuxiliaryAdapter} from './synthetic-auxiliary-adapter.mjs';
2
+ import {isSyntheticAuxiliaryName} from './synthetic-auxiliary-policy.mjs';
3
+ import {makeSyntheticFileAdapter} from './synthetic-file-adapter.mjs';
4
+ import {inspectSyntheticFileTree} from './synthetic-file-transaction.mjs';
5
+ import {validateSyntheticWriteTool,SYNTHETIC_WRITE_LIMITS} from './synthetic-write-policy.mjs';
6
+ import {createHash,randomUUID} from 'node:crypto';
7
+ import {constants} from 'node:fs';
8
+ import {openSync,closeSync,fstatSync,fsyncSync,lstatSync,realpathSync,readFileSync,writeFileSync,renameSync,unlinkSync,readdirSync} from 'node:fs';
9
+ import {resolve,join,relative,isAbsolute,dirname,sep} from 'node:path';
10
+
11
+ const deny=()=>{throw Object.assign(new Error('SYNTHETIC_WRITE_DENIED'),{code:'SYNTHETIC_WRITE_DENIED'});};
12
+ const rollbackDeny=()=>{throw Object.assign(new Error('SYNTHETIC_WRITE_ROLLBACK_UNVERIFIED'),{code:'SYNTHETIC_WRITE_ROLLBACK_UNVERIFIED'});};
13
+ export const C1_LIMITS=SYNTHETIC_WRITE_LIMITS;
14
+ const LOCK='.rs-c1-writer.lock';
15
+ const sensitive=/(?:^|[_-])(?:secret|credential|token|password|private|key)(?:[_-]|$)|^id_[a-z0-9]+$/i;
16
+ const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
17
+ const uuid=value=>typeof value==='string'&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
18
+
19
+ function safeName(value){
20
+ if(typeof value!=='string'||Buffer.byteLength(value)>C1_LIMITS.maxPathBytes||!/^([A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]+\.txt$/.test(value))deny();
21
+ const parts=value.split('/');if(parts.some(x=>x==='.'||x==='..'||x.startsWith('.')||sensitive.test(x.replace(/\.txt$/i,''))))deny();
22
+ return value;
23
+ }
24
+ function safeRoot(root,verifySandbox){
25
+ if(typeof root!=='string'||!isAbsolute(root)||typeof verifySandbox!=='function')deny();
26
+ let current,stat;try{current=realpathSync(root);stat=lstatSync(current);}catch{deny();}
27
+ if(!stat.isDirectory()||stat.isSymbolicLink()||(stat.mode&0o077)!==0||verifySandbox(current)!==true)deny();
28
+ return current;
29
+ }
30
+ function resolveTarget(root,rel,{existing}){
31
+ const parts=rel.split('/'),file=parts.pop();let dir=root;
32
+ for(const part of parts){
33
+ dir=join(dir,part);let st;try{st=lstatSync(dir);}catch{deny();}
34
+ if(!st.isDirectory()||st.isSymbolicLink()||realpathSync(dir)!==dir)deny();
35
+ }
36
+ const abs=resolve(dir,file),delta=relative(root,abs);
37
+ if(delta==='..'||delta.startsWith('..'+sep)||isAbsolute(delta))deny();
38
+ let st;try{st=lstatSync(abs);}catch(e){if(e?.code!=='ENOENT')deny();}
39
+ if(existing&&(!st||!st.isFile()||st.isSymbolicLink()||st.nlink!==1||realpathSync(abs)!==abs))deny();
40
+ if(!existing&&st)deny();
41
+ return abs;
42
+ }
43
+ function decodeText(bytes){
44
+ let value;try{value=new TextDecoder('utf-8',{fatal:true}).decode(bytes);}catch{deny();}
45
+ if(value.includes('\0')||/[\x01-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value))deny();
46
+ return value;
47
+ }
48
+ function text(value){
49
+ if(typeof value!=='string'||Buffer.byteLength(value)>C1_LIMITS.fileBytes||/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value))deny();
50
+ return value;
51
+ }
52
+ function snapshot(abs){
53
+ let fd;try{fd=openSync(abs,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_CLOEXEC);}catch{deny();}
54
+ try{
55
+ const opened=fstatSync(fd),named=lstatSync(abs);
56
+ if(!opened.isFile()||opened.uid!==process.geteuid?.()||opened.nlink!==1||named.isSymbolicLink()||named.dev!==opened.dev||named.ino!==opened.ino||realpathSync(abs)!==abs||opened.size>C1_LIMITS.fileBytes)deny();
57
+ const bytes=readFileSync(fd);if(bytes.length!==opened.size)deny();
58
+ return {dev:opened.dev,ino:opened.ino,bytes,content:decodeText(bytes),mode:opened.mode&0o777};
59
+ }finally{closeSync(fd);}
60
+ }
61
+ function sameInode(abs,expected){
62
+ let st;try{st=lstatSync(abs);}catch{deny();}
63
+ if(!st.isFile()||st.isSymbolicLink()||st.nlink!==1||st.dev!==expected.dev||st.ino!==expected.ino||realpathSync(abs)!==abs)deny();
64
+ return st;
65
+ }
66
+ function syncDirectory(path){let fd;try{fd=openSync(path,constants.O_RDONLY|constants.O_DIRECTORY);fsyncSync(fd);}finally{if(fd!==undefined)closeSync(fd);}}
67
+ function restore(abs,root,rel,original){
68
+ let temp,fd;
69
+ try{
70
+ const parent=dirname(abs);resolveTarget(root,rel,{existing:true});
71
+ temp=join(parent,`.rs-rollback-${randomUUID()}`);
72
+ fd=openSync(temp,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);
73
+ writeFileSync(fd,original.bytes);fsyncSync(fd);closeSync(fd);fd=undefined;
74
+ resolveTarget(root,rel,{existing:true});
75
+ renameSync(temp,abs);temp=undefined;syncDirectory(parent);
76
+ const restored=snapshot(abs);
77
+ if(!restored.bytes.equals(original.bytes)||sha(restored.bytes)!==sha(original.bytes))rollbackDeny();
78
+ }catch{rollbackDeny();}
79
+ finally{if(fd!==undefined)closeSync(fd);if(temp)try{unlinkSync(temp);}catch{}}
80
+ }
81
+ function removeCreated(abs,root,rel,owned){
82
+ try{
83
+ const stat=sameInode(abs,owned);resolveTarget(root,rel,{existing:true});
84
+ if(stat.dev!==owned.dev||stat.ino!==owned.ino)rollbackDeny();
85
+ unlinkSync(abs);syncDirectory(dirname(abs));
86
+ try{lstatSync(abs);rollbackDeny();}catch(e){if(e?.code!=='ENOENT')throw e;}
87
+ }catch{rollbackDeny();}
88
+ }
89
+ const inspectRoot=inspectSyntheticFileTree;
90
+ const exactKeys=(obj,keys)=>!!obj&&Object.getPrototypeOf(obj)===Object.prototype&&Object.keys(obj).every(k=>keys.includes(k));
91
+ function checkResult(result){
92
+ if(result?.isError===true||!Array.isArray(result?.content)||result.content.length>8||result.content.some(item=>item?.type!=='text'||typeof item.text!=='string'))deny();
93
+ const output=result.content.map(item=>item.text).join('\n');if(Buffer.byteLength(output)>C1_LIMITS.maxOutputBytes)deny();
94
+ }
95
+ function takeLock(root){
96
+ let fd;try{fd=openSync(join(root,LOCK),constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);}catch{deny();}
97
+ const st=fstatSync(fd);if(!st.isFile()||st.nlink!==1){closeSync(fd);deny();}
98
+ return ()=>{try{const named=lstatSync(join(root,LOCK));if(named.dev!==st.dev||named.ino!==st.ino||named.isSymbolicLink())rollbackDeny();unlinkSync(join(root,LOCK));syncDirectory(root);}finally{closeSync(fd);}};
99
+ }
100
+ const nativeCall=(client,name,args)=>client.callTool({name,arguments:args},undefined,{signal:AbortSignal.timeout(C1_LIMITS.timeoutMs)});
101
+
102
+ // This is a low-level adapter. Production code must use the verified wrapper,
103
+ // which checks a kernel-reported exact tmpfs mount; never trust a caller boolean.
104
+ export function makeSyntheticWriteAdapter({enabled=false,root,client,verifySandbox,authorized=()=>false,onAudit}={}){
105
+ if(enabled!==true||!client||typeof client.callTool!=='function'||typeof authorized!=='function'||typeof onAudit!=='function')deny();
106
+ const canonical=safeRoot(root,verifySandbox);let requests=0;
107
+ const runAuxiliary=makeSyntheticAuxiliaryAdapter({root:canonical,client,verifySandbox,authorized,onAudit});
108
+ const runFiles=makeSyntheticFileAdapter({root:canonical,client,verifySandbox,authorized,onAudit});
109
+ async function execute(name,args,context){
110
+ if(isSyntheticAuxiliaryName(name))return runAuxiliary(name,args,context);
111
+ if(['create_directory','move_file','write_pdf'].includes(name))return runFiles(name,args,context);
112
+ try{args=validateSyntheticWriteTool({name,arguments:args},{enabled:true}).arguments;}catch{deny();}
113
+ if(name!=='write_file'&&name!=='edit_block'||!exactKeys(args,name==='write_file'?['path','content']:['path','old_string','new_string','expectedHash']))deny();
114
+ if(++requests>C1_LIMITS.maxRequests||!uuid(context?.owner_id)||!uuid(context?.connection_id)||!uuid(context?.device_id)||!uuid(context?.consent_id)||typeof context?.requestId!=='string'||!/^[-A-Za-z0-9_]{8,64}$/.test(context.requestId)||context?.consent!==true||context?.revoked===true||context?.permission!==name||Buffer.byteLength(JSON.stringify(args))>C1_LIMITS.requestBytes)deny();
115
+ if(await authorized(context,name)!==true)deny();
116
+ if(safeRoot(root,verifySandbox)!==canonical)deny();
117
+ const rel=safeName(args.path),release=takeLock(canonical);let abs,owned,original,created=false;
118
+ try{
119
+ const inventory=inspectRoot(canonical),existing=name==='edit_block';
120
+ abs=resolveTarget(canonical,rel,{existing});
121
+ if(name==='write_file'){
122
+ const desired=text(args.content),desiredBytes=Buffer.from(desired,'utf8');
123
+ if(inventory.files>=C1_LIMITS.maxFiles||inventory.bytes+desiredBytes.length>C1_LIMITS.maxRootBytes)deny();
124
+ // Reserve with O_EXCL before the native pathname-based tool call. This
125
+ // closes create races between our absence check and write_file's open.
126
+ let fd;try{fd=openSync(abs,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);created=true;owned=fstatSync(fd);writeFileSync(fd,desiredBytes);fsyncSync(fd);}catch{deny();}finally{if(fd!==undefined)closeSync(fd);}
127
+ sameInode(abs,owned);const result=await nativeCall(client,name,{path:abs,content:desired,mode:'rewrite',origin:'llm'});checkResult(result);
128
+ const after=snapshot(abs);if(after.dev!==owned.dev||after.ino!==owned.ino||!after.bytes.equals(desiredBytes))deny();
129
+ try{await onAudit({request_id:context.requestId,tool:name,decision:'allow',outcome:'verified'});}catch{deny();}
130
+ return JSON.stringify({created:true,bytes:desiredBytes.length,sha256:sha(desiredBytes)});
131
+ }
132
+ const old=text(args.old_string),replacement=text(args.new_string);
133
+ if(!old.length||typeof args.expectedHash!=='string'||!/^([a-f0-9]{64})$/.test(args.expectedHash))deny();
134
+ original=snapshot(abs);if(sha(original.bytes)!==args.expectedHash||original.content.split(old).length!==2)deny();
135
+ const expected=original.content.replace(old,replacement),expectedBytes=Buffer.from(expected,'utf8');
136
+ if(expectedBytes.length>C1_LIMITS.fileBytes||inventory.bytes-original.bytes.length+expectedBytes.length>C1_LIMITS.maxRootBytes)deny();
137
+ const result=await nativeCall(client,'edit_block',{file_path:abs,old_string:old,new_string:replacement,expected_replacements:1,origin:'llm'});checkResult(result);
138
+ const after=snapshot(abs);if(after.dev!==original.dev||after.ino!==original.ino||!after.bytes.equals(expectedBytes))deny();
139
+ try{await onAudit({request_id:context.requestId,tool:name,decision:'allow',outcome:'verified'});}catch{deny();}
140
+ return JSON.stringify({edited:true,sha256:sha(expectedBytes),previous_sha256:sha(original.bytes),bytes:expectedBytes.length});
141
+ }catch(error){
142
+ try{
143
+ if(created&&abs&&owned)removeCreated(abs,canonical,rel,owned);
144
+ else if(name==='edit_block'&&abs&&original)restore(abs,canonical,rel,original);
145
+ }catch{rollbackDeny();}
146
+ if(error?.code==='SYNTHETIC_WRITE_ROLLBACK_UNVERIFIED')throw error;
147
+ deny();
148
+ }finally{release();}
149
+ }
150
+ return execute;
151
+ }
152
+