@remoteshell/device 0.0.0-stage → 0.1.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/LICENSE +26 -0
  2. package/NOTICE +20 -0
  3. package/bin/dev-agent-client.mjs +228 -0
  4. package/bin/dev-agent-runner.mjs +60 -0
  5. package/bin/dev-api-client.mjs +31 -0
  6. package/bin/dev-auto-worker.mjs +25 -0
  7. package/bin/dev-browser-open.mjs +12 -0
  8. package/bin/dev-dogfood-read.mjs +3 -0
  9. package/bin/dev-heartbeat-service.mjs +77 -0
  10. package/bin/dev-pairing-client.mjs +63 -0
  11. package/bin/dev-secrets.mjs +33 -0
  12. package/bin/dev-setup-recovery.mjs +34 -0
  13. package/bin/dev-signer-pin.mjs +22 -0
  14. package/bin/device.mjs +384 -0
  15. package/bin/direct-npx-runtime.mjs +150 -0
  16. package/bin/enrollment-client.mjs +105 -0
  17. package/bin/install-acquire.mjs +89 -0
  18. package/bin/install-integrity.mjs +74 -0
  19. package/bin/install-plan.mjs +43 -0
  20. package/bin/lifecycle.mjs +172 -0
  21. package/bin/native-path-contract.mjs +23 -0
  22. package/bin/remoteshell-device-install.cmd +17 -0
  23. package/bin/remoteshell-device-install.ps1 +17 -0
  24. package/bin/remoteshell-device-install.sh +15 -0
  25. package/bin/remoteshell-device-preflight.cmd +10 -0
  26. package/bin/remoteshell-device-preflight.ps1 +10 -0
  27. package/bin/remoteshell-easy-diagnose.ps1 +32 -0
  28. package/bin/remoteshell-easy-install.ps1 +292 -0
  29. package/bin/remoteshell-easy-install.sh +71 -0
  30. package/bin/remoteshell-easy-uninstall.ps1 +128 -0
  31. package/bin/windows-acl-wmi-client.mjs +50 -0
  32. package/bin/windows-acl-wmi.js +43 -0
  33. package/bin/windows-credential-boundary.mjs +113 -0
  34. package/bin/windows-direct-autostart-runner.mjs +50 -0
  35. package/bin/windows-direct-autostart.mjs +110 -0
  36. package/bin/windows-install-layout.mjs +28 -0
  37. package/bin/windows-native-installer.mjs +91 -0
  38. package/bin/windows-private-store.mjs +176 -0
  39. package/bin/windows-user-lifecycle.mjs +34 -0
  40. package/npm-shrinkwrap.json +8591 -0
  41. package/package.json +27 -4
  42. package/shared/lib/bounded-search-contract.mjs +5 -0
  43. package/shared/lib/bounded-search-policy.mjs +24 -0
  44. package/shared/lib/config.mjs +14 -0
  45. package/shared/lib/contracts.mjs +26 -0
  46. package/shared/lib/dc-generic-policy.mjs +102 -0
  47. package/shared/lib/dc-relay-contract.mjs +42 -0
  48. package/shared/lib/dc-tool-catalog.mjs +67 -0
  49. package/shared/lib/dev-dc-relay-contract.mjs +20 -0
  50. package/shared/lib/dev-paged-output.mjs +32 -0
  51. package/shared/lib/dev-root-exclusions.mjs +56 -0
  52. package/shared/lib/errors.mjs +9 -0
  53. package/shared/lib/events.mjs +5 -0
  54. package/shared/lib/execution-policy.mjs +41 -0
  55. package/shared/lib/isolated-read-boundary.mjs +50 -0
  56. package/shared/lib/isolated-read-policy.mjs +29 -0
  57. package/shared/lib/lifecycle-events.mjs +13 -0
  58. package/shared/lib/runtime-timing.mjs +9 -0
  59. package/shared/lib/synthetic-auxiliary-policy.mjs +21 -0
  60. package/shared/lib/synthetic-write-policy.mjs +52 -0
  61. package/shared/lib/tool-registry.mjs +58 -0
  62. package/src/config/l2-dev-oci-credential.mjs +39 -0
  63. package/src/config/p2-private-credential.mjs +15 -0
  64. package/src/connection/dev-dogfood-processes.mjs +25 -0
  65. package/src/connection/dev-dogfood-read.mjs +64 -0
  66. package/src/connection/dev-dogfood-task.mjs +113 -0
  67. package/src/connection/dev-dogfood-write.mjs +62 -0
  68. package/src/connection/dev-file-task.mjs +119 -0
  69. package/src/connection/dev-r4-file-task.mjs +56 -0
  70. package/src/connection/dev-read-tools.mjs +134 -0
  71. package/src/connection/dev-root-scopes.mjs +82 -0
  72. package/src/core/c1-dc-transport.mjs +26 -0
  73. package/src/core/c1-startup.mjs +22 -0
  74. package/src/core/c1-supervisor.mjs +111 -0
  75. package/src/core/c1-worker.mjs +88 -0
  76. package/src/core/fixture.txt +2 -0
  77. package/src/dc/dc-access-readiness.mjs +31 -0
  78. package/src/dc/dev-dc-relay.mjs +47 -0
  79. package/src/device-agent/main.mjs +1 -0
  80. package/src/gateway-keepalive.mjs +73 -0
  81. package/src/main.mjs +436 -0
  82. package/src/policy/bounded-search-adapter.mjs +115 -0
  83. package/src/policy/isolated-read-adapter.mjs +50 -0
  84. package/src/policy/isolated-read-mount.mjs +27 -0
  85. package/src/policy/synthetic-auxiliary-adapter.mjs +75 -0
  86. package/src/policy/synthetic-file-adapter.mjs +26 -0
  87. package/src/policy/synthetic-file-transaction.mjs +87 -0
  88. package/src/policy/synthetic-write-adapter.mjs +151 -0
  89. package/src/policy/synthetic-write-mount.mjs +23 -0
  90. package/src/policy/verified-bounded-search.mjs +12 -0
  91. package/src/policy/verified-isolated-read.mjs +15 -0
  92. package/src/policy/verified-synthetic-write.mjs +14 -0
  93. package/README.md +0 -3
@@ -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,52 @@
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
+ }
@@ -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,39 @@
1
+ // Read the private credential created by the OCI DEV pairing flow.
2
+ // This adapter is opt-in to the L2 DEV agent; it never copies or rewrites it.
3
+ import {lstatSync,readFileSync} from 'node:fs';
4
+ import {dirname,resolve} from 'node:path';
5
+ import {homedir} from 'node:os';
6
+ import {inspectWindowsCredentialAcl} from '../../bin/windows-credential-boundary.mjs';
7
+
8
+ const OCI_DEV_BASE='https://ailab-remoteshell.duckdns.org/dev/';
9
+ 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;
10
+ const TOKEN=/^[A-Za-z0-9._~-]{24,2048}$/;
11
+ const deny=()=>{throw Error('L2_DEV_CREDENTIAL_DENIED');};
12
+
13
+ export function readL2DevOciCredential(file,{lstat=lstatSync,readFile=readFileSync,uid=process.getuid?.(),
14
+ os=process.platform,home=homedir(),inspectWindows=inspectWindowsCredentialAcl}={}){
15
+ let raw;
16
+ try{
17
+ if(os==='win32'){
18
+ // NTFS mode bits and Unix UID are not access controls on Windows.
19
+ // Never silently skip validation or fall back to permissive POSIX checks.
20
+ if(inspectWindows({file,home,os})?.restrictedAcl!==true)deny();
21
+ }else{
22
+ if(os!=='linux'&&os!=='darwin'||typeof file!=='string'||!file.startsWith('/')||
23
+ resolve(file)!==file||file.includes('\0'))deny();
24
+ const parent=lstat(dirname(file)),stat=lstat(file);
25
+ if(!parent.isDirectory()||parent.isSymbolicLink()||parent.uid!==uid||
26
+ (parent.mode&0o777)!==0o700||!stat.isFile()||stat.isSymbolicLink()||
27
+ stat.uid!==uid||(stat.mode&0o777)!==0o600||stat.size>8192)deny();
28
+ }
29
+ raw=readFile(file,'utf8');
30
+ }catch{deny();}
31
+ let data;
32
+ try{data=JSON.parse(raw);}catch{deny();}
33
+ const keys=Object.keys(data||{}).sort();
34
+ if(!data||Array.isArray(data)||Object.getPrototypeOf(data)!==Object.prototype||
35
+ keys.join(',')!=='base,device_credential,device_id,sequence,version'||
36
+ data.version!==1||data.base!==OCI_DEV_BASE||!UUID.test(data.device_id||'')||
37
+ !TOKEN.test(data.device_credential||'')||!Number.isSafeInteger(data.sequence)||data.sequence<0)deny();
38
+ return Object.freeze({device_id:data.device_id,credential:data.device_credential});
39
+ }
@@ -0,0 +1,15 @@
1
+ import {lstatSync,readFileSync} from 'node:fs';
2
+ import {dirname} from 'node:path';
3
+ import {secret} from '../../shared/lib/config.mjs';
4
+
5
+ export function readPrivateP2Credential(filename){
6
+ const credentialFile = filename;
7
+ const fileStat = lstatSync(credentialFile);
8
+ if (!fileStat.isFile() || fileStat.isSymbolicLink() || (fileStat.mode & 0o777) !== 0o600) throw new Error('P2 device credential file must be private');
9
+ const parentStat = lstatSync(dirname(credentialFile));
10
+ if (!parentStat.isDirectory() || parentStat.isSymbolicLink() || (parentStat.mode & 0o777) !== 0o700) throw new Error('P2 device credential directory must be private');
11
+ const parsed = JSON.parse(readFileSync(credentialFile, 'utf8'));
12
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || Object.keys(parsed).some(key => !['device_id', 'credential'].includes(key))) throw new Error('Invalid P2 device provisioning');
13
+ if (typeof parsed.device_id !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(parsed.device_id)) throw new Error('Invalid P2 device provisioning');
14
+ return {device_id: parsed.device_id, credential: secret(parsed.credential, 'P2 device credential')};
15
+ }
@@ -0,0 +1,25 @@
1
+ import {spawn} from 'node:child_process';
2
+ const DENY=()=>{throw Error('DEV_DOGFOOD_PROCESS_DENIED');};
3
+ 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);
4
+ export function createDevDogfoodProcesses({rootId,maxProcesses=4,maxRunMs=120000,maxOutputBytes=8192,spawnImpl=spawn}={}){
5
+ if(!uuid(rootId)||!Number.isSafeInteger(maxProcesses)||maxProcesses<1||maxProcesses>8||!Number.isSafeInteger(maxRunMs)||maxRunMs<1000||maxRunMs>300000||!Number.isSafeInteger(maxOutputBytes)||maxOutputBytes<256||maxOutputBytes>16384)DENY();
6
+ const rows=new Map(),activeByKey=new Map();
7
+ const MAX_ROWS=128,RETAIN_MS=5*60*1000;
8
+ const clean=()=>{const t=Date.now();
9
+ for(const [id,row] of rows){
10
+ if(row.state!=='running'&&t-row.finishedAt>RETAIN_MS){
11
+ row.workspace?.cleanup();rows.delete(id);if(activeByKey.get(row.workKey)===id)activeByKey.delete(row.workKey);
12
+ }
13
+ }
14
+ if(rows.size>MAX_ROWS)for(const [id,row] of rows){
15
+ if(row.state!=='running'){row.workspace?.cleanup();rows.delete(id);if(activeByKey.get(row.workKey)===id)activeByKey.delete(row.workKey);}
16
+ if(rows.size<=MAX_ROWS)break;
17
+ }
18
+ };
19
+ function key({deviceId,sessionId}){if(!uuid(deviceId)||!uuid(sessionId))DENY();return `${deviceId}:${sessionId}`;}
20
+ return Object.freeze({
21
+ close({deviceId,sessionId}={}){const owner=key({deviceId,sessionId});for(const row of rows.values())if(row.owner===owner&&row.state==='running'){row.state='stopped';row.finishedAt=Date.now();clearTimeout(row.timer);
22
+ try{if(row.child.pid&&process.platform!=='win32')process.kill(-row.child.pid,'SIGTERM');else row.child.kill('SIGTERM');}catch{}}},
23
+ count(){return rows.size;}
24
+ });
25
+ }
@@ -0,0 +1,64 @@
1
+ import {excludedPath,assertAllowedPath} from '../../shared/lib/dev-root-exclusions.mjs';
2
+ // L3 D1 DEV-only local file operations. This module does not grant a remote user
3
+ // access; Gateway/CP must authorize owner, device, approved root and tool first.
4
+ import {lstatSync,realpathSync,readdirSync} from 'node:fs';
5
+ import {resolve,relative,sep,join} from 'node:path';
6
+ const DENY=()=>{throw Error('DEV_DOGFOOD_ROOT_DENIED');};
7
+ const CHECK=/^[A-Za-z0-9._/-]{1,256}$/;
8
+ function rootPath(root){
9
+ if(typeof root!=='string'||!root.startsWith('/')||root==='/'||root.includes('\0'))DENY();
10
+ const p=resolve(root);
11
+ if(p!==root||p==='/'||lstatSync(p).isSymbolicLink())DENY();
12
+ const s=lstatSync(p);
13
+ if(!s.isDirectory()||s.uid!==process.getuid?.())DENY();
14
+ const canonical=realpathSync(p);
15
+ if(canonical!==p)DENY();
16
+ return canonical;
17
+ }
18
+ function at(root,name){
19
+ if(typeof name!=='string'||!CHECK.test(name)||name.startsWith('/')||
20
+ name.split('/').some(x=>x==='..'||x===''))DENY();
21
+ const p=resolve(root,name),r=relative(root,p);
22
+ if(r==='..'||r.startsWith('..'+sep)||r.startsWith('/'))DENY();
23
+ let cur=root;
24
+ for(const part of name.split('/')){
25
+ if(part==='.')continue;
26
+ cur=join(cur,part);
27
+ const st=lstatSync(cur);
28
+ if(st.isSymbolicLink()||!st.isDirectory()&&!st.isFile())DENY();
29
+ }
30
+ return p;
31
+ }
32
+ export function devDogfoodRead({root,path,tool='list_directory',exclusion_policy}={}){
33
+ const base=rootPath(root),p=at(base,path);
34
+ if(exclusion_policy)assertAllowedPath(path,exclusion_policy);
35
+ if(tool==='list_directory'){
36
+ if(!lstatSync(p).isDirectory())DENY();
37
+ return readdirSync(p,{withFileTypes:true}).slice(0,101).map(d=>{
38
+ if(d.isSymbolicLink()||exclusion_policy&&excludedPath(path==='.'?d.name:path+'/'+d.name,exclusion_policy))return null;
39
+ return {name:d.name,type:d.isDirectory()?'directory':d.isFile()?'file':'other'};
40
+ }).filter(Boolean).slice(0,100);
41
+ }
42
+ DENY();
43
+ }
44
+ export function devDogfoodSearch({root,path='.',pattern,maxResults=20,exclusion_policy}={}){
45
+ if(typeof pattern!=='string'||pattern.length<1||pattern.length>128||
46
+ /[\x00-\x1f\x7f]/.test(pattern)||!Number.isInteger(maxResults)||maxResults<1||maxResults>50)DENY();
47
+ const base=rootPath(root),start=at(base,path);
48
+ if(exclusion_policy)assertAllowedPath(path,exclusion_policy);
49
+ if(!lstatSync(start).isDirectory())DENY();
50
+ const results=[],pending=[{dir:start,depth:0}];let scanned=0;
51
+ while(pending.length&&scanned<200&&results.length<maxResults){
52
+ const {dir,depth}=pending.pop();
53
+ const entries=readdirSync(dir,{withFileTypes:true});
54
+ for(const entry of entries){
55
+ if(++scanned>200||results.length>=maxResults)break;
56
+ if(entry.isSymbolicLink())continue;
57
+ const full=join(dir,entry.name),rel=relative(base,full);
58
+ if(exclusion_policy&&excludedPath(rel,exclusion_policy))continue;
59
+ if(entry.isDirectory()&&depth<3)pending.push({dir:full,depth:depth+1});
60
+ if(entry.isFile()&&entry.name.toLowerCase().includes(pattern.toLowerCase()))results.push({path:rel});
61
+ }
62
+ }
63
+ return {matches:results,scanned,truncated:pending.length>0||scanned>=200};
64
+ }
@@ -0,0 +1,113 @@
1
+ import {verifyDcConsent} from '../../shared/lib/dev-dc-relay-contract.mjs';
2
+ import {isDcPublic} from '../../shared/lib/dc-generic-policy.mjs';
3
+ import {validateDcRelayArgs} from '../dc/dev-dc-relay.mjs';
4
+ import {validPageArgs} from '../../shared/lib/dev-paged-output.mjs';
5
+ import {validateExclusionPolicy,assertAllowedPath} from '../../shared/lib/dev-root-exclusions.mjs';
6
+ import {devDogfoodRead,devDogfoodSearch} from './dev-dogfood-read.mjs';
7
+ import {executeDevDogfoodWrite} from './dev-dogfood-write.mjs';
8
+ import {devReadTools} from './dev-read-tools.mjs';
9
+ import {validateR4AgentTool,executeR4AgentTool} from './dev-r4-file-task.mjs';
10
+ import {validateDevFileAgentTool,executeDevFileAgentTool} from './dev-file-task.mjs';
11
+ const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
12
+ const plain=x=>!!x&&typeof x==='object'&&!Array.isArray(x)&&Object.getPrototypeOf(x)===Object.prototype;
13
+ const pathAllowedForGit=p=>typeof p==='string'&&p.length<=256&&
14
+ (p==='.'||/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(p))&&
15
+ (p==='.'||!p.split('/').some(x=>x==='..'||x==='.'));
16
+
17
+ export function devDogfoodTaskEnvelope(value,{sessionId,rootId,deviceId}={}){
18
+ if(!plain(value)||Object.keys(value).sort().join(',')!=='request_id,session_id,state,tool'||
19
+ !UUID.test(value.request_id||'')||value.session_id!==sessionId||value.state!=='dispatched'||
20
+ !plain(value.tool)||Object.keys(value.tool).sort().join(',')!=='arguments,name'||!plain(value.tool.arguments)||
21
+ value.tool.arguments.root_id!==rootId||!UUID.test(rootId||''))throw Error('DEV_DOGFOOD_TASK_DENIED');
22
+ const a=value.tool.arguments,name=value.tool.name;
23
+ if(a.dc_relay===true){
24
+ if(!isDcPublic(name)||Object.keys(a).sort().join(',')!=='dc_args,dc_relay,root_id'||
25
+ !plain(a.dc_args)||rootId!==deviceId)throw Error('DC_RELAY_DENIED');
26
+ // Device identity and MCP tool arguments are already validated at the Gateway.
27
+ // The Agent forwards them without a second RS command approval.
28
+ return Object.freeze({request_id:value.request_id,session_id:value.session_id,state:value.state,
29
+ tool:Object.freeze({name,arguments:Object.freeze({...a})})});
30
+ }
31
+ if(a.file_authorization){
32
+ validateDevFileAgentTool(value.tool,{rootId,sessionId,deviceId:deviceId||a.file_authorization.device_id});
33
+ return Object.freeze({request_id:value.request_id,session_id:value.session_id,
34
+ state:value.state,tool:Object.freeze({name,arguments:Object.freeze({...a})})});
35
+ }
36
+ if(a.r4_authorization){
37
+ validateR4AgentTool(value.tool,{rootId,sessionId,deviceId:a.r4_authorization.device_id});
38
+ return Object.freeze({request_id:value.request_id,session_id:value.session_id,
39
+ state:value.state,tool:Object.freeze({name,arguments:Object.freeze({...a})})});
40
+ }
41
+
42
+ const r3=['write_file','edit_block','delete_file'].includes(name);
43
+ const fixture=/^r3-e2e-fixture\/[A-Za-z0-9_-][A-Za-z0-9_.-]*\.(?:mjs|js|cjs|json|md|txt)$/.test(a.path||'');
44
+ if(r3&&!fixture)
45
+ throw Error('DEV_DOGFOOD_TASK_DENIED');
46
+ const schemas={
47
+ list_directory:{required:['path','root_id'],optional:[]},
48
+ start_search:{required:['path','pattern','root_id'],optional:['searchType']},
49
+ search_content:{required:['path','query','regex','limit','offset','root_id'],optional:[]},
50
+ git_status:{required:['path','root_id'],optional:[]},
51
+ git_diff:{required:['path','root_id'],optional:['file','offset','max_bytes','version']},
52
+ write_file:{required:['content','path','root_id'],optional:[]},
53
+ edit_block:{required:['expectedHash','new_string','old_string','path','root_id'],optional:[]},
54
+ delete_file:{required:['expectedHash','path','root_id'],optional:[]}
55
+ };
56
+ const schema=schemas[name];
57
+ if(name==='git_diff')validPageArgs({offset:a.offset,max_bytes:a.max_bytes,version:a.version});
58
+ if(!schema||schema.required.some(k=>a[k]===undefined)||
59
+ Object.keys(a).some(k=>!schema.required.includes(k)&&!schema.optional.includes(k))||
60
+ name==='start_search'&&a.searchType!==undefined&&a.searchType!=='files'||
61
+ name==='git_status'&&(!pathAllowedForGit(a.path))||name==='git_diff'&&(
62
+ !pathAllowedForGit(a.path)||a.file!==undefined&&(
63
+ typeof a.file!=='string'||a.file.length>256||a.file.startsWith('/')||
64
+ !/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(a.file)||
65
+ a.file.split('/').includes('..')))||
66
+ name==='search_content'&&(
67
+ typeof a.query!=='string'||a.query.length>128||a.query.length===0||
68
+ /[\x00-\x1f\x7f]/.test(a.query)||typeof a.regex!=='boolean'||
69
+ !Number.isInteger(a.limit)||a.limit<1||a.limit>100||
70
+ !Number.isInteger(a.offset)||a.offset<0||a.offset>10000))throw Error('DEV_DOGFOOD_TASK_DENIED');
71
+ const args=Object.freeze({...a});return Object.freeze({request_id:value.request_id,session_id:value.session_id,state:value.state,tool:Object.freeze({name,arguments:args})});
72
+ }
73
+
74
+ // Called only for tasks delivered over the authenticated L2 DEV Agent session.
75
+ // root_id is compared with a local mapping; absolute paths never travel on wire.
76
+ export async function executeDevDogfoodTask({tool,rootId,root,client,deviceId,sessionId,processes,exclusion_policy,requirePolicy=false}={}){
77
+ if(!tool||!tool.arguments||tool.arguments.root_id!==rootId)return null;
78
+ const a=tool.arguments;
79
+ if(requirePolicy&&!exclusion_policy)throw Error('EXCLUSION_POLICY_DENIED');
80
+ if(exclusion_policy){
81
+ validateExclusionPolicy(exclusion_policy,{device_id:deviceId,root_id:rootId});
82
+ assertAllowedPath(a.path??a.repo_path,exclusion_policy);
83
+ if(a.test_path)assertAllowedPath(a.test_path,exclusion_policy);
84
+ if(tool.name==='git_diff'&&a.file)
85
+ assertAllowedPath(a.path==='.'?a.file:a.path+'/'+a.file,exclusion_policy);
86
+ }
87
+ if(a.file_authorization)
88
+ return executeDevFileAgentTool({tool,root,rootId,deviceId,sessionId});
89
+ if(a.r4_authorization)return executeR4AgentTool({tool,root,rootId,client,deviceId,sessionId,processes});
90
+ if(tool.name==='list_directory'){
91
+ if(typeof a.path!=='string'||tool.name==='list_directory'&&
92
+ Object.keys(a).sort().join(',')!=='path,root_id')throw Error('ARGUMENTS_DENIED');
93
+ return JSON.stringify(devDogfoodRead({root,path:a.path,tool:tool.name,exclusion_policy}));
94
+ }
95
+ if(['search_content','git_status','git_diff'].includes(tool.name)){
96
+ if(tool.name==='search_content'&&(
97
+ typeof a.query!=='string'||a.query.length===0||a.query.length>128||
98
+ typeof a.regex!=='boolean'||!Number.isSafeInteger(a.limit)||a.limit<1||a.limit>100||
99
+ !Number.isSafeInteger(a.offset)||a.offset<0||a.offset>10000)||
100
+ tool.name!=='search_content'&&!pathAllowedForGit(a.path))throw Error('ARGUMENTS_DENIED');
101
+ return JSON.stringify(await devReadTools({root,name:tool.name,path:a.path,
102
+ ...(tool.name==='search_content'?{query:a.query,regex:a.regex,limit:a.limit,offset:a.offset}:{}),
103
+ ...(tool.name==='git_diff'?{file:a.file,page:validPageArgs(a)}:{}),exclusion_policy}));
104
+ }
105
+ if(tool.name==='start_search'){
106
+ if(!['path,pattern,root_id','path,pattern,root_id,searchType'].includes(Object.keys(a).sort().join(','))||
107
+ typeof a.path!=='string'||a.searchType!==undefined&&a.searchType!=='files')throw Error('ARGUMENTS_DENIED');
108
+ return JSON.stringify(devDogfoodSearch({root,path:a.path,pattern:a.pattern,maxResults:50,exclusion_policy}));
109
+ }
110
+ if(['write_file','edit_block','delete_file'].includes(tool.name))
111
+ return executeDevDogfoodWrite({root,tool,client});
112
+ throw Error('TOOL_DENIED');
113
+ }
@@ -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
+ }