@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
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@remoteshell/device",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-beta.10",
4
+ "description": "RemoteShell public beta device agent",
5
+ "type": "module",
6
+ "bin": {
7
+ "remoteshell-device": "./bin/device.mjs"
8
+ },
9
+ "files": [
10
+ "bin/",
11
+ "src/",
12
+ "shared/",
13
+ "npm-shrinkwrap.json",
14
+ "LICENSE",
15
+ "NOTICE"
16
+ ],
17
+ "engines": {
18
+ "node": ">=22"
19
+ },
20
+ "dependencies": {
21
+ "@modelcontextprotocol/sdk": "1.32.1",
22
+ "@wonderwhy-er/desktop-commander": "0.3.1"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/lkhkhk/RemoteShell.git"
27
+ },
28
+ "license": "SEE LICENSE IN LICENSE"
29
+ }
@@ -0,0 +1,5 @@
1
+ export const BOUNDED_SEARCH_LIMITS=Object.freeze({
2
+ maxSessions:2,maxDepth:3,maxEntries:128,maxFileBytes:65536,maxTreeBytes:4*1024*1024,
3
+ maxPatternBytes:256,maxFilePatternBytes:128,maxResults:200,maxPage:50,maxPathBytes:256,
4
+ maxSnippetBytes:256,maxPageBytes:32768,maxSessionBytes:131072,searchTimeoutMs:30000
5
+ });
@@ -0,0 +1,24 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {RuntimeError,ERROR_CODES} from './errors.mjs';
3
+ import {validateAgentBoundedSearchTool,validateBoundedSearchTool} from './tool-registry.mjs';
4
+
5
+ export const BOUNDED_SEARCH_POLICY_VERSION='55-b-test-1';
6
+ 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);
7
+ const plain=value=>value!==null&&typeof value==='object'&&!Array.isArray(value)&&Object.getPrototypeOf(value)===Object.prototype;
8
+ const deny=(code=ERROR_CODES.TOOL_DENIED)=>{throw new RuntimeError(code,'Bounded search denied');};
9
+
10
+ export function authorizeGatewayBoundedSearch({principal,device,tool,scope}={}){
11
+ if(!plain(principal)||!plain(device)||!plain(scope)||scope.enabled!==true||
12
+ !uuid(principal.owner_id)||!uuid(principal.connection_id)||!uuid(device.device_id)||
13
+ principal.owner_id!==device.user_id||principal.connection_id!==device.connection_id||
14
+ scope.owner_id!==principal.owner_id||scope.connection_id!==principal.connection_id||scope.device_id!==device.device_id||
15
+ typeof scope.root_scope_id!=='string'||!/^[A-Za-z0-9_-]{16,128}$/.test(scope.root_scope_id))deny();
16
+ const canonical=validateBoundedSearchTool(tool,{enabled:true});
17
+ const arguments_hash=createHash('sha256').update(JSON.stringify(canonical.arguments)).digest('hex');
18
+ return Object.freeze({policy_version:BOUNDED_SEARCH_POLICY_VERSION,tool:canonical,arguments_hash,root_scope_id:scope.root_scope_id});
19
+ }
20
+
21
+ export function authorizeAgentBoundedSearch({tool,enabled=false}={}){
22
+ if(enabled!==true)deny();
23
+ return validateAgentBoundedSearchTool(tool,{enabled:true});
24
+ }
@@ -0,0 +1,14 @@
1
+ import {isAbsolute} from 'node:path';
2
+ import {RuntimeError,ERROR_CODES} from './errors.mjs';
3
+ function invalid(name){throw new RuntimeError(ERROR_CODES.CONFIG_ERROR,'Invalid configuration: '+name);}
4
+ export function integer(value,name,{min=0,max=Number.MAX_SAFE_INTEGER}={}){if(typeof value!=='string'||!/^(0|[1-9][0-9]*)$/.test(value))invalid(name);const n=Number(value);if(!Number.isSafeInteger(n)||n<min||n>max)invalid(name);return n;}
5
+ export function port(value,name){return integer(value,name,{min:1,max:65535});}
6
+ export function boolean(value,name){if(value==='true')return true;if(value==='false')return false;invalid(name);}
7
+ export function url(value,name,{protocols=['https:']}={}){try{const u=new URL(value);if(!protocols.includes(u.protocol)||u.username||u.password||u.hash||u.search)invalid(name);return u;}catch{invalid(name);}}
8
+ export function absolutePath(value,name){if(typeof value!=='string'||!isAbsolute(value)||value.includes('\0'))invalid(name);return value;}
9
+ export function secret(value,name){if(typeof value!=='string'||value.length<24||!value.trim()||value.includes('\n')||value.includes('\r')||value.includes('\0'))invalid(name);return value;}
10
+ export function distinctSecrets(named){const vals=Object.entries(named);for(let i=0;i<vals.length;i++)for(let j=i+1;j<vals.length;j++)if(vals[i][1]===vals[j][1])invalid('secret collision: '+vals[i][0]+'/'+vals[j][0]);return true;}
11
+ export function redact(value){if(Array.isArray(value))return value.map(redact);if(value&&typeof value==='object')return Object.fromEntries(Object.entries(value).map(([k,v])=>[k,/token|secret|password|authorization|api[_-]?key|credential/i.test(k)?'[REDACTED]':redact(v)]));return value;}
12
+ export function parseGatewayConfig(env){const credentials={client:secret(env.RS_TOKEN,'RS_TOKEN'),device:secret(env.RS_DEVICE_TOKEN,'RS_DEVICE_TOKEN')};distinctSecrets(credentials);return Object.freeze({port:port(env.RS_PORT??'18765','RS_PORT'),timeoutMs:integer(env.RS_TIMEOUT_MS??'10000','RS_TIMEOUT_MS',{min:100,max:60000}),pendingLimit:integer(env.RS_PENDING_LIMIT??'16','RS_PENDING_LIMIT',{min:1,max:1024}),remoteEnabled:boolean(env.RS_ENABLE_REMOTE??'false','RS_ENABLE_REMOTE'),credentials:Object.freeze(credentials)});}
13
+ export function parseDeviceConfig(env){return Object.freeze({gatewayUrl:url(env.RS_GATEWAY_URL??'https://localhost:18765','RS_GATEWAY_URL',{protocols:['http:','https:']}).toString(),credentials:Object.freeze({device:secret(env.RS_DEVICE_TOKEN,'RS_DEVICE_TOKEN')})});}
14
+ export function parseMcpConfig(env){const credentials={mcp:secret(env.RS_MCP_TOKEN,'RS_MCP_TOKEN'),gateway:secret(env.RS_TOKEN,'RS_TOKEN')};distinctSecrets(credentials);return Object.freeze({gatewayUrl:url(env.RS_GATEWAY_URL??'http://127.0.0.1:18765','RS_GATEWAY_URL',{protocols:['http:','https:']}).toString(),credentials:Object.freeze(credentials)});}
@@ -0,0 +1,26 @@
1
+ import {RuntimeError,ERROR_CODES} from './errors.mjs';
2
+ import {createHash} from 'node:crypto';
3
+ import {isSyntheticWriteName,validateSyntheticWriteTool} from './synthetic-write-policy.mjs';
4
+ const plain=x=>x!==null&&typeof x==='object'&&!Array.isArray(x)&&Object.getPrototypeOf(x)===Object.prototype;
5
+ function check(value,label){if(!plain(value))throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Invalid '+label);return value;}
6
+ const ident=(x,label)=>{if(typeof x!=='string'||!x||x.length>128)throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Invalid '+label);return x;};
7
+ export function toolCall(value){check(value,'tool');const keys=Object.keys(value);if(keys.some(k=>!['name','arguments'].includes(k)))throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Invalid tool fields');ident(value.name,'tool name');check(value.arguments,'arguments');return {name:value.name,arguments:value.arguments};}
8
+ export function requestEnvelope(value){check(value,'request');return Object.freeze({request_id:ident(value.request_id,'request_id'),session_id:ident(value.session_id,'session_id'),tool:toolCall(value.tool),...(value.context===undefined?{}:{context:check(value.context,'context')})});}
9
+ export function resultEnvelope(value){check(value,'result');if(typeof value.ok!=='boolean')throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Invalid result');return Object.freeze({request_id:ident(value.request_id,'request_id'),ok:value.ok,...(value.result===undefined?{}:{result:value.result}),...(value.error_code===undefined?{}:{error_code:ident(value.error_code,'error_code')})});}
10
+ export function sessionEnvelope(value){check(value,'session');return Object.freeze({session_id:ident(value.session_id,'session_id'),...(value.context===undefined?{}:{context:check(value.context,'context')})});}
11
+ export function syntheticWriteContext(value,{request_id,session_id,tool,now=Date.now()}={}){
12
+ check(value,'C1 context');
13
+ const keys=['consent_id','owner_id','connection_id','device_id','session_id','tool','args_hash','requestId','permission','consent','expires_at'];
14
+ 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);
15
+ const canonical=validateSyntheticWriteTool(tool,{enabled:true});
16
+ if(Object.keys(value).length!==keys.length||Object.keys(value).some(k=>!keys.includes(k))||!['consent_id','owner_id','connection_id','device_id','session_id','requestId'].every(k=>uuid(value[k]))||value.requestId!==request_id||value.session_id!==session_id||value.tool!==canonical.name||value.permission!==canonical.name||value.consent!==true||!Number.isSafeInteger(value.expires_at)||value.expires_at<=now||value.args_hash!==createHash('sha256').update(JSON.stringify(canonical.arguments)).digest('hex'))throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Invalid C1 context');
17
+ return Object.freeze({...value});
18
+ }
19
+ export function taskEnvelope(value){
20
+ check(value,'task');if(!['queued','dispatched','completed','cancelled','timed_out'].includes(value.state))throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Invalid task state');
21
+ const result={request_id:ident(value.request_id,'request_id'),session_id:ident(value.session_id,'session_id'),state:value.state,tool:toolCall(value.tool)};
22
+ if(isSyntheticWriteName(result.tool.name))result.context=syntheticWriteContext(value.context,result);
23
+ else if(value.context!==undefined)throw new RuntimeError(ERROR_CODES.ARGUMENTS_DENIED,'Unexpected task context');
24
+ return Object.freeze(result);
25
+ }
26
+
@@ -0,0 +1,102 @@
1
+ import {realpathSync,existsSync} from 'node:fs';
2
+ import {resolve,relative,dirname,isAbsolute,sep} from 'node:path';
3
+
4
+ export const DC_PROVIDER_ONLY='give_feedback_to_desktop_commander';
5
+ export const DC_USER_TOOLS=Object.freeze([
6
+ 'get_config','set_config_value','read_file','read_multiple_files','write_file','write_pdf',
7
+ 'create_directory','list_directory','move_file','start_search','get_more_search_results',
8
+ 'stop_search','list_searches','get_file_info','edit_block','start_process',
9
+ 'read_process_output','interact_with_process','force_terminate','list_sessions',
10
+ 'list_processes','kill_process','get_usage_stats','get_recent_tool_calls'
11
+ ]);
12
+ const names=new Set(DC_USER_TOOLS);
13
+ const readNames=new Set(['get_config','read_file','read_multiple_files','list_directory',
14
+ 'start_search','get_more_search_results','list_searches','get_file_info',
15
+ 'read_process_output','list_sessions','list_processes','get_usage_stats','get_recent_tool_calls']);
16
+ const pathNames=new Set(['read_file','read_multiple_files','write_file','write_pdf',
17
+ 'create_directory','list_directory','move_file','start_search','get_file_info','edit_block']);
18
+ const plain=x=>x!==null&&typeof x==='object'&&!Array.isArray(x)&&Object.getPrototypeOf(x)===Object.prototype;
19
+ const deny=()=>{throw Error('DC_GENERIC_DENIED')};
20
+ export const isDcPublic=name=>names.has(name);
21
+ export const dcIsReadonly=name=>readNames.has(name);
22
+ export const dcHasPath=name=>pathNames.has(name);
23
+ export const dcPermissionBase=name=>readNames.has(name)?'read_file':name==='start_process'?'start_process':name;
24
+ // A user-owned Root grants its existing read permission to comparable read tools.
25
+ // All non-read tools must be explicitly granted by the current Root policy.
26
+ export function dcRootToolAllowed(name,allowedTools){
27
+ if(!isDcPublic(name)||!Array.isArray(allowedTools))return false;
28
+ return allowedTools.includes(name)||(readNames.has(name)&&allowedTools.includes('read_file'));
29
+ }
30
+ function schemaCheck(schema,value,level=0){
31
+ if(level>12||!plain(schema))return false;
32
+ if(schema.anyOf)return Array.isArray(schema.anyOf)&&schema.anyOf.some(x=>schemaCheck(x,value,level+1));
33
+ if(schema.oneOf)return Array.isArray(schema.oneOf)&&schema.oneOf.filter(x=>schemaCheck(x,value,level+1)).length===1;
34
+ if(Object.hasOwn(schema,'const')&&JSON.stringify(value)!==JSON.stringify(schema.const))return false;
35
+ if(schema.enum&&!schema.enum.some(x=>JSON.stringify(x)===JSON.stringify(value)))return false;
36
+ const types=Array.isArray(schema.type)?schema.type:[schema.type];
37
+ if(types[0]&& !types.some(t=>t==='object'?plain(value):
38
+ t==='array'?Array.isArray(value):t==='integer'?Number.isSafeInteger(value):
39
+ t==='number'?typeof value==='number'&&Number.isFinite(value):
40
+ t==='string'?typeof value==='string':
41
+ t==='boolean'?typeof value==='boolean':t==='null'?value===null:false))return false;
42
+ if(typeof value==='string'){
43
+ if(value.length>32768||schema.maxLength!==undefined&&value.length>schema.maxLength||
44
+ schema.minLength!==undefined&&value.length<schema.minLength)return false;
45
+ if(schema.pattern){try{if(!new RegExp(schema.pattern).test(value))return false}catch{return false}}
46
+ }
47
+ if(typeof value==='number'){
48
+ if(schema.minimum!==undefined&&value<schema.minimum||
49
+ schema.maximum!==undefined&&value>schema.maximum)return false;
50
+ }
51
+ if(Array.isArray(value)){
52
+ if(value.length>256||schema.maxItems!==undefined&&value.length>schema.maxItems||
53
+ schema.minItems!==undefined&&value.length<schema.minItems)return false;
54
+ if(schema.items&&!value.every(x=>schemaCheck(schema.items,x,level+1)))return false;
55
+ }
56
+ if(plain(value)){
57
+ if(Object.keys(value).length>64)return false;
58
+ const properties=schema.properties||{},required=schema.required||[];
59
+ if(!Array.isArray(required)||!required.every(k=>Object.hasOwn(value,k)))return false;
60
+ for(const [key,item] of Object.entries(value)){
61
+ if(['__proto__','constructor','prototype'].includes(key))return false;
62
+ if(Object.hasOwn(properties,key)){if(!schemaCheck(properties[key],item,level+1))return false}
63
+ else if(!Object.hasOwn(schema,'additionalProperties')||schema.additionalProperties===false)return false;
64
+ else if(plain(schema.additionalProperties)&&!schemaCheck(schema.additionalProperties,item,level+1))return false;
65
+ }
66
+ }
67
+ return true;
68
+ }
69
+ export function validateDcGenericArgs(name,args,catalog){
70
+ if(!isDcPublic(name)||!plain(args)||JSON.stringify(args).length>32768||!Array.isArray(catalog))deny();
71
+ const tool=catalog.find(t=>t.name===name);
72
+ if(!tool||!plain(tool.inputSchema)||!schemaCheck(tool.inputSchema,args))deny();
73
+ return args;
74
+ }
75
+ export function parseDcGenericMcpArgs(name,input,catalog){
76
+ if(!plain(input)||typeof input.device_id!=='string'||
77
+ Object.hasOwn(input,'root_id')||
78
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(input.device_id))deny();
79
+ const {device_id,...args}=input;
80
+ validateDcGenericArgs(name,args,catalog);
81
+ return {deviceId:device_id,name,args};
82
+ }
83
+ export function dcFilePaths(name,args){
84
+ if(!dcHasPath(name))return [];
85
+ if(name==='read_multiple_files')return args.paths||[];
86
+ if(name==='move_file')return [args.source,args.destination];
87
+ if(name==='edit_block')return args.file_path===undefined?[]:[args.file_path];
88
+ if(name==='write_pdf')return [args.path,...(typeof args.outputPath==='string'?[args.outputPath]:[]),...(Array.isArray(args.content)?args.content.filter(x=>x&&typeof x.sourcePdfPath==='string').map(x=>x.sourcePdfPath):[])];
89
+ return args.path===undefined?[]:[args.path];
90
+ }
91
+ export function validateDcPathScope(name,args,root,{requireExisting=false}={}){
92
+ const base=realpathSync(root);
93
+ for(const path of dcFilePaths(name,args)){
94
+ if(typeof path!=='string'||path.length>4096||!isAbsolute(path))deny();
95
+ const full=resolve(path),present=existsSync(full),target=present?realpathSync(full):
96
+ (requireExisting?deny():resolve(realpathSync(dirname(full)),full.split(sep).at(-1)));
97
+ const rel=relative(base,target);
98
+ if(rel==='..'||rel.startsWith('..'+sep)||isAbsolute(rel))deny();
99
+ }
100
+ if(dcHasPath(name)&&dcFilePaths(name,args).length===0)deny();
101
+ return true;
102
+ }
@@ -0,0 +1,42 @@
1
+ import {isAbsolute} from 'node:path';
2
+
3
+ const DENIED=()=>Object.assign(new Error('DC_RELAY_DENIED'),{code:'DC_RELAY_DENIED'});
4
+ const plain=x=>x&&typeof x==='object'&&!Array.isArray(x)&&Object.getPrototypeOf(x)===Object.prototype;
5
+ const schemas={
6
+ read_file:{required:['path'],optional:['isUrl','offset','length','sheet','range','options','origin']},
7
+ list_directory:{required:['path'],optional:['depth','origin']},
8
+ start_process:{required:['command','timeout_ms'],optional:['shell','verbose_timing','origin']},
9
+ read_process_output:{required:['pid'],optional:['timeout_ms','offset','length','verbose_timing']}
10
+ };
11
+ const keys=(o,required,optional)=>plain(o)&&required.every(k=>Object.hasOwn(o,k))&&
12
+ Object.keys(o).every(k=>required.includes(k)||optional.includes(k));
13
+ const nonnegative=n=>Number.isSafeInteger(n)&&n>=0;
14
+
15
+ // Shared argument contract. Only Device Agent invokes the original DC MCP tool.
16
+ export function validateDcRelayArgs(name,args){
17
+ const schema=schemas[name];
18
+ if(!schema||!keys(args,schema.required,schema.optional))throw DENIED();
19
+ if(name==='read_file'){
20
+ if(typeof args.path!=='string'||!isAbsolute(args.path)||args.path.length>4096||
21
+ args.isUrl!==undefined&&args.isUrl!==false||
22
+ args.offset!==undefined&&!nonnegative(args.offset)||
23
+ args.length!==undefined&&(!nonnegative(args.length)||args.length>10000)||
24
+ args.sheet!==undefined&&typeof args.sheet!=='string'||
25
+ args.range!==undefined&&typeof args.range!=='string'||
26
+ args.options!==undefined&&!plain(args.options))throw DENIED();
27
+ }else if(name==='list_directory'){
28
+ if(typeof args.path!=='string'||!isAbsolute(args.path)||args.path.length>4096||
29
+ args.depth!==undefined&&(!Number.isSafeInteger(args.depth)||args.depth<1||args.depth>5))throw DENIED();
30
+ }else if(name==='start_process'){
31
+ if(typeof args.command!=='string'||!args.command.trim()||args.command.length>32768||
32
+ /[\x00-\x08\x0b-\x1f\x7f]/.test(args.command)||
33
+ !Number.isSafeInteger(args.timeout_ms)||args.timeout_ms<1||args.timeout_ms>120000||
34
+ args.shell!==undefined&&typeof args.shell!=='string')throw DENIED();
35
+ }else if(!Number.isSafeInteger(args.pid)||args.pid<=0||
36
+ args.timeout_ms!==undefined&&(!nonnegative(args.timeout_ms)||args.timeout_ms>120000)||
37
+ args.offset!==undefined&&!nonnegative(args.offset)||
38
+ args.length!==undefined&&(!nonnegative(args.length)||args.length>10000))throw DENIED();
39
+ if(args.verbose_timing!==undefined&&typeof args.verbose_timing!=='boolean'||
40
+ args.origin!==undefined&&!['ui','llm'].includes(args.origin))throw DENIED();
41
+ return args;
42
+ }
@@ -0,0 +1,67 @@
1
+ import {createHash} from 'node:crypto';
2
+
3
+ const MAX_TOOLS=128;
4
+ const MAX_PAGES=16;
5
+ const validName=name=>typeof name==='string'&&/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(name);
6
+ const record=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
7
+ function ordered(value){
8
+ if(Array.isArray(value))return value.map(ordered);
9
+ if(record(value))return Object.fromEntries(Object.keys(value).sort().map(k=>[k,ordered(value[k])]));
10
+ return value;
11
+ }
12
+ const stable=value=>JSON.stringify(ordered(value));
13
+ export function normalizeDcCatalog(tools){
14
+ if(!Array.isArray(tools)||tools.length>MAX_TOOLS)throw Error('DC_CATALOG_INVALID');
15
+ const names=new Set();
16
+ return Object.freeze(tools.map(tool=>{
17
+ if(!record(tool)||!validName(tool.name)||names.has(tool.name)||
18
+ typeof tool.description!=='string'||!record(tool.inputSchema)||
19
+ tool.inputSchema.type!=='object'||!record(tool.inputSchema.properties)||
20
+ tool.annotations!==undefined&&!record(tool.annotations))throw Error('DC_CATALOG_INVALID');
21
+ names.add(tool.name);
22
+ // The original DC definitions are authoritative. Do not copy its
23
+ // client-specific UI resource metadata into the RemoteShell MCP catalog.
24
+ return Object.freeze({name:tool.name,description:tool.description,
25
+ inputSchema:structuredClone(tool.inputSchema),
26
+ ...(tool.annotations?{annotations:structuredClone(tool.annotations)}:{})});
27
+ }));
28
+ }
29
+ export async function discoverDcCatalog(client,{requestTimeoutMs=12000}={}){
30
+ if(!Number.isSafeInteger(requestTimeoutMs)||requestTimeoutMs<1000||requestTimeoutMs>60000)
31
+ throw Error('DC_CATALOG_TIMEOUT_INVALID');
32
+ if(!client||typeof client.listTools!=='function')throw Error('DC_CATALOG_UNAVAILABLE');
33
+ let cursor,tools=[],pages=0;
34
+ do{
35
+ if(++pages>MAX_PAGES)throw Error('DC_CATALOG_PAGINATION_LIMIT');
36
+ const result=await client.listTools(cursor?{cursor}:{},{timeout:requestTimeoutMs});
37
+ if(!record(result)||!Array.isArray(result.tools))throw Error('DC_CATALOG_INVALID');
38
+ tools.push(...result.tools);
39
+ if(tools.length>MAX_TOOLS)throw Error('DC_CATALOG_SIZE_LIMIT');
40
+ cursor=result.nextCursor;
41
+ if(cursor!==undefined&&(typeof cursor!=='string'||!cursor))throw Error('DC_CATALOG_INVALID');
42
+ }while(cursor);
43
+ return normalizeDcCatalog(tools);
44
+ }
45
+ export function dcCatalogFingerprint(catalog){
46
+ return createHash('sha256').update(stable(catalog)).digest('hex');
47
+ }
48
+ export function diffDcCatalog(previous,current){
49
+ const old=new Map(previous.map(t=>[t.name,t]));
50
+ const now=new Map(current.map(t=>[t.name,t]));
51
+ const added=[...now.keys()].filter(n=>!old.has(n)).sort();
52
+ const removed=[...old.keys()].filter(n=>!now.has(n)).sort();
53
+ const changed=[...now.keys()].filter(n=>old.has(n)&&stable(old.get(n))!==stable(now.get(n))).sort();
54
+ return Object.freeze({added,removed,changed,hasChanges:!!(added.length||removed.length||changed.length)});
55
+ }
56
+ export function wrapDcTool(tool,{expose=false}={}){
57
+ if(!expose)return null; // Discovery never confers execution rights.
58
+ const schema=structuredClone(tool.inputSchema);
59
+ if(schema.type!=='object'||!record(schema.properties)||!validName(tool.name)||
60
+ Object.hasOwn(schema.properties,'device_id')||Object.hasOwn(schema.properties,'root_id'))
61
+ throw Error('DC_CATALOG_SCHEMA_CONFLICT');
62
+ schema.properties.device_id={type:'string',format:'uuid'};
63
+ schema.properties.root_id={type:'string',format:'uuid'};
64
+ schema.required=[...new Set([...(schema.required||[]),'device_id','root_id'])];
65
+ return {name:tool.name,description:tool.description,inputSchema:schema,
66
+ ...(tool.annotations?{annotations:structuredClone(tool.annotations)}:{})};
67
+ }
@@ -0,0 +1,20 @@
1
+ // #249 - DC invocation identity and one-call consent contract (no execution).
2
+ import {createHash} from 'node:crypto';
3
+ import {DC_USER_TOOLS} from './dc-generic-policy.mjs';
4
+ 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;
5
+ const fail=()=>{throw Error('DC_RELAY_CONSENT_DENIED')};
6
+ export const DC_RELAY_TOOLS=DC_USER_TOOLS;
7
+ export const dcArgsSha256=args=>createHash('sha256').update(JSON.stringify(args)).digest('hex');
8
+ export function verifyDcConsent({grant,name,args,owner_user_id,connection_id,device_id,root_id,credential_version,grant_version,now=Date.now()}={}){
9
+ if(!grant||typeof grant!=='object'||grant.contract_version!=='rs-dc-relay-v1'||grant.decision!=='ALLOW'||
10
+ grant.executable!==true||!DC_RELAY_TOOLS.includes(name)||grant.tool_id!==name||
11
+ ![owner_user_id,connection_id,device_id,root_id].every(x=>UUID.test(x||''))||
12
+ !Number.isSafeInteger(credential_version)||credential_version<0||
13
+ !Number.isSafeInteger(grant_version)||grant_version<0||
14
+ grant.owner_user_id!==owner_user_id||grant.connection_id!==connection_id||
15
+ grant.device_id!==device_id||grant.root_id!==root_id||
16
+ grant.credential_version!==credential_version||grant.grant_version!==grant_version||
17
+ grant.args_sha256!==dcArgsSha256(args)||!Number.isSafeInteger(grant.expires_at)||
18
+ grant.expires_at<=now||grant.expires_at>now+86400000||!UUID.test(grant.consent_id||''))fail();
19
+ return grant;
20
+ }
@@ -0,0 +1,32 @@
1
+ import {createHash} from 'node:crypto';
2
+
3
+ // Stateless byte offsets over exact UTF-8 snapshot bytes. No server-side cursor to expire.
4
+ const DENY=()=>{throw Error('DEV_PAGE_DENIED');};
5
+ const MAX_TOTAL=1024*1024;
6
+ export function validPageArgs({offset,max_bytes,version}={}){
7
+ if(offset===undefined&&max_bytes===undefined&&version===undefined)return null;
8
+ if(!Number.isSafeInteger(offset)||offset<0||offset>MAX_TOTAL||
9
+ !Number.isSafeInteger(max_bytes)||max_bytes<1||max_bytes>4096||
10
+ (version!==undefined&&(typeof version!=='string'||!/^[a-f0-9]{64}$/.test(version)))||
11
+ offset>0&&version===undefined)DENY();
12
+ return {offset,max_bytes,version};
13
+ }
14
+ export function boundedSnapshotPage(text,{offset,max_bytes,version},policy=0){
15
+ const scope=typeof policy==='number'?{revision:policy}:policy;
16
+ if(typeof text!=='string'||!scope||!Number.isSafeInteger(scope.revision)||scope.revision<0)DENY();
17
+ const identity=JSON.stringify(['owner_user_id','connection_id','device_id','root_id',
18
+ 'credential_version','grant_version','revision'].map(k=>scope[k]??null));
19
+ const bytes=Buffer.from(text,'utf8');
20
+ if(bytes.length>MAX_TOTAL||offset>bytes.length)DENY();
21
+ const digest=createHash('sha256').update('rs-page-v1\0').update(identity).update('\0').update(bytes).digest('hex');
22
+ if(version!==undefined&&version!==digest)throw Error('DEV_PAGE_STALE');
23
+ // Byte offsets must be exact UTF-8 boundaries; don't silently skip bytes.
24
+ if(offset>0&&offset<bytes.length&&(bytes[offset]&0xc0)===0x80)DENY();
25
+ let end=Math.min(bytes.length,offset+max_bytes);
26
+ if(end<bytes.length)while(end>offset&&(bytes[end]&0xc0)===0x80)end--;
27
+ if(end===offset&&offset<bytes.length)DENY();
28
+ const next=end<bytes.length?end:null;
29
+ return Object.freeze({text:bytes.subarray(offset,end).toString('utf8'),offset,
30
+ next_offset:next,total_bytes:bytes.length,version:digest,
31
+ truncated:next!==null,complete:next===null});
32
+ }
@@ -0,0 +1,56 @@
1
+ // #242: CP is the owner-bound source of exclusion rules. No cache: every task
2
+ // receives the current revision or is refused before Agent dispatch.
3
+ const UUID=x=>typeof x==='string'&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(x);
4
+ const version=x=>Number.isSafeInteger(x)&&x>=0;
5
+ export const DEFAULT_EXCLUSIONS=Object.freeze(['.ssh','.gnupg','.aws','.kube','.config/gcloud','.config/gh','.env','.npmrc','.git-credentials']);
6
+ export const excludedRule=x=>typeof x==='string'&&x.length>0&&x.length<=256&&
7
+ /^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(x)&&
8
+ !x.split('/').some(s=>s==='.'||s==='..');
9
+ const match=(path,rule)=>path===rule||path.startsWith(rule+'/')||path.includes('/'+rule+'/')||path.endsWith('/'+rule);
10
+ export function validateExclusionPolicy(policy,scope){
11
+ if(!policy||policy.contract_version!=='dev-root-exclusions-v1'||policy.decision!=='ALLOW'||
12
+ !UUID(policy.owner_user_id)||!UUID(policy.connection_id)||!UUID(policy.device_id)||!UUID(policy.root_id)||
13
+ !version(policy.credential_version)||!version(policy.grant_version)||
14
+ !version(policy.revision)||policy.semantics!=='exact-and-descendants'||
15
+ policy.glob_supported!==false||policy.negation_supported!==false||
16
+ !Array.isArray(policy.rules)||policy.rules.length>64||
17
+ !Array.isArray(policy.defaults)||JSON.stringify(policy.defaults)!==JSON.stringify(DEFAULT_EXCLUSIONS)||
18
+ policy.rules.some(x=>!excludedRule(x))||new Set(policy.rules).size!==policy.rules.length||
19
+ scope&&Object.entries(scope).some(([k,v])=>policy[k]!==v))throw Error('EXCLUSION_POLICY_DENIED');
20
+ return Object.freeze({...policy,rules:Object.freeze([...policy.rules]),defaults:DEFAULT_EXCLUSIONS});
21
+ }
22
+ export function excludedPath(path,policy){
23
+ if(path==='.')return false;
24
+ // Filesystem entries may have spaces/Unicode or Git quoted names; omit them
25
+ // instead of failing an otherwise permitted directory search/listing.
26
+ if(!excludedRule(path))return true;
27
+ const p=validateExclusionPolicy(policy);
28
+ return [...p.defaults,...p.rules].some(r=>match(path,r));
29
+ }
30
+ export function assertAllowedPath(path,policy){
31
+ if(excludedPath(path,policy))throw Error('EXCLUSION_PATH_DENIED');
32
+ return true;
33
+ }
34
+ export function createGatewayExclusionConsumer({baseUrl,secret,fetchImpl=fetch}={}){
35
+ let endpoint;
36
+ try{const url=new URL(baseUrl);if(url.protocol!=='https:'||url.pathname!=='/'||url.search||url.hash||url.username||url.password)throw Error();
37
+ // DEV-only CP listener shares this OCI host with Gateway; Nginx blocks public access.
38
+ endpoint='http://127.0.0.1:18766/dev/api/internal/gateway/root-exclusions';
39
+ }catch{throw Error('EXCLUSION_CONFIG_DENIED');}
40
+ if(typeof secret!=='string'||secret.length<32||typeof fetchImpl!=='function')throw Error('EXCLUSION_CONFIG_DENIED');
41
+ return Object.freeze({async get(scope){
42
+ if(!scope||!['owner_user_id','connection_id','device_id','root_id'].every(k=>UUID(scope[k]))||
43
+ !version(scope.credential_version)||!version(scope.grant_version))throw Error('EXCLUSION_POLICY_DENIED');
44
+ const d={owner_user_id:scope.owner_user_id,connection_id:scope.connection_id,
45
+ device_id:scope.device_id,root_id:scope.root_id,
46
+ credential_version:scope.credential_version,grant_version:scope.grant_version};
47
+ try{
48
+ const res=await fetchImpl(endpoint,{method:'POST',redirect:'manual',
49
+ headers:{authorization:'Bearer '+secret,'content-type':'application/json',accept:'application/json'},
50
+ body:JSON.stringify(d),signal:AbortSignal.timeout(2000)});
51
+ if(res.status!==200||!/^application\/json(?:\s*;|\s*$)/i.test(res.headers.get('content-type')||''))throw Error();
52
+ const body=await res.text();if(body.length>8000)throw Error();
53
+ return validateExclusionPolicy(JSON.parse(body),d);
54
+ }catch{throw Error('EXCLUSION_POLICY_UNAVAILABLE');}
55
+ }});
56
+ }
@@ -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 {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,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
+ }