@remoteshell/device 0.0.0-stage → 0.1.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/device.mjs +139 -0
- package/bin/enrollment-client.mjs +105 -0
- package/bin/lifecycle.mjs +172 -0
- package/package.json +18 -4
- package/src/common/bounded-search-adapter.mjs +116 -0
- package/src/common/bounded-search-policy.mjs +24 -0
- package/src/common/config.mjs +14 -0
- package/src/common/contracts.mjs +26 -0
- package/src/common/errors.mjs +9 -0
- package/src/common/events.mjs +5 -0
- package/src/common/execution-policy.mjs +41 -0
- package/src/common/isolated-read-adapter.mjs +50 -0
- package/src/common/isolated-read-boundary.mjs +50 -0
- package/src/common/isolated-read-mount.mjs +27 -0
- package/src/common/isolated-read-policy.mjs +29 -0
- package/src/common/lifecycle-events.mjs +13 -0
- package/src/common/runtime-timing.mjs +9 -0
- package/src/common/synthetic-auxiliary-adapter.mjs +75 -0
- package/src/common/synthetic-auxiliary-policy.mjs +21 -0
- package/src/common/synthetic-file-adapter.mjs +26 -0
- package/src/common/synthetic-file-transaction.mjs +87 -0
- package/src/common/synthetic-write-adapter.mjs +152 -0
- package/src/common/synthetic-write-mount.mjs +23 -0
- package/src/common/synthetic-write-policy.mjs +53 -0
- package/src/common/tool-registry.mjs +58 -0
- package/src/common/verified-bounded-search.mjs +12 -0
- package/src/common/verified-isolated-read.mjs +15 -0
- package/src/common/verified-synthetic-write.mjs +14 -0
- package/src/device-agent/c1-dc-transport.mjs +26 -0
- package/src/device-agent/c1-startup.mjs +22 -0
- package/src/device-agent/c1-supervisor.mjs +109 -0
- package/src/device-agent/c1-worker.mjs +88 -0
- package/src/device-agent/fixture.txt +2 -0
- package/src/device-agent/main.mjs +230 -0
- package/README.md +0 -3
package/bin/device.mjs
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Device-local bootstrap only. No CP credential creation, privileged setup, shell,
|
|
3
|
+
// systemd enablement, npm publication or server source shipped in this package.
|
|
4
|
+
import {existsSync,lstatSync,mkdirSync,readFileSync,renameSync,rmSync,writeFileSync} from 'node:fs';
|
|
5
|
+
import {homedir,platform} from 'node:os';
|
|
6
|
+
import {join,dirname,resolve} from 'node:path';
|
|
7
|
+
import {fileURLToPath} from 'node:url';
|
|
8
|
+
import {randomUUID} from 'node:crypto';
|
|
9
|
+
import {spawnSync} from 'node:child_process';
|
|
10
|
+
import {createRequire} from 'node:module';
|
|
11
|
+
import {foreground,installUserUnit,userService,gatewayStatus} from './lifecycle.mjs';
|
|
12
|
+
import {readDeviceCredential} from './enrollment-client.mjs';
|
|
13
|
+
const require=createRequire(import.meta.url);
|
|
14
|
+
const pkg=require('../package.json');
|
|
15
|
+
const packageRoot=resolve(dirname(fileURLToPath(import.meta.url)),'..');
|
|
16
|
+
const action=process.argv[2];
|
|
17
|
+
const deny=(code='DEVICE_INSTALL_DENIED')=>{throw Error(code);};
|
|
18
|
+
const currentUid=process.getuid?.();
|
|
19
|
+
function checkDir(path,{privateMode=false}={}){
|
|
20
|
+
const stat=lstatSync(path);
|
|
21
|
+
if(!stat.isDirectory()||stat.isSymbolicLink()||(currentUid!==undefined&&stat.uid!==currentUid)||(privateMode&&(stat.mode&0o777)!==0o700))deny();
|
|
22
|
+
}
|
|
23
|
+
function ensureDir(path,{privateMode=false}={}){
|
|
24
|
+
if(!existsSync(path))mkdirSync(path,{mode:0o700});
|
|
25
|
+
checkDir(path,{privateMode});
|
|
26
|
+
}
|
|
27
|
+
function paths(){
|
|
28
|
+
const home=homedir();
|
|
29
|
+
if(!home||!home.startsWith('/')||resolve(home)==='/')deny();
|
|
30
|
+
checkDir(home);
|
|
31
|
+
const local=join(home,'.local'),share=join(local,'share');
|
|
32
|
+
const base=join(share,'remoteshell-device');
|
|
33
|
+
return {local,share,base,install:join(base,'install')};
|
|
34
|
+
}
|
|
35
|
+
function checkReceipt(root){
|
|
36
|
+
const receiptPath=join(root,'receipt.json');
|
|
37
|
+
if(!existsSync(receiptPath))deny();
|
|
38
|
+
const st=lstatSync(receiptPath);
|
|
39
|
+
if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o777)!==0o600||(currentUid!==undefined&&st.uid!==currentUid)||st.size>2048)deny();
|
|
40
|
+
const data=JSON.parse(readFileSync(receiptPath,'utf8'));
|
|
41
|
+
if(data?.schema!==1||data.version!==pkg.version||data.distribution!=='synthetic-private'||data.registered!==false||data.serviceEnabled!==false)deny();
|
|
42
|
+
const runtimePkg=join(root,'node_modules','@remoteshell','device','package.json');
|
|
43
|
+
const dcPkg=join(root,'node_modules','@wonderwhy-er','desktop-commander','package.json');
|
|
44
|
+
for(const file of [runtimePkg,dcPkg]){
|
|
45
|
+
const s=lstatSync(file);
|
|
46
|
+
if(!s.isFile()||s.isSymbolicLink())deny();
|
|
47
|
+
}
|
|
48
|
+
const installed=JSON.parse(readFileSync(runtimePkg,'utf8'));
|
|
49
|
+
const dc=JSON.parse(readFileSync(dcPkg,'utf8'));
|
|
50
|
+
if(installed.name!==pkg.name||installed.version!==pkg.version||dc.version!=='0.3.0')deny('DEVICE_DEPENDENCY_INVALID');
|
|
51
|
+
return data;
|
|
52
|
+
}
|
|
53
|
+
async function status(p){
|
|
54
|
+
if(!existsSync(p.base))return {installed:false,registered:false,connected:false};
|
|
55
|
+
checkDir(p.base,{privateMode:true});
|
|
56
|
+
if(!existsSync(p.install))return {installed:false,registered:false,connected:false};
|
|
57
|
+
checkDir(p.install,{privateMode:true});
|
|
58
|
+
const receipt=checkReceipt(p.install);
|
|
59
|
+
const store=join(p.base,'credentials'),credential=join(store,'device.json');
|
|
60
|
+
const hasMock=existsSync(credential);
|
|
61
|
+
if(hasMock)readDeviceCredential({storageDir:store}); // refuse tampered credentials
|
|
62
|
+
let verified=false,connected=false;
|
|
63
|
+
if(hasMock&&process.env.RS_GATEWAY_URL){
|
|
64
|
+
try{
|
|
65
|
+
const online=await gatewayStatus({gatewayUrl:process.env.RS_GATEWAY_URL,caFile:process.env.RS_CA_FILE});
|
|
66
|
+
verified=online.gatewayVerified;connected=online.connected;
|
|
67
|
+
}catch{verified=false;connected=false;}
|
|
68
|
+
}
|
|
69
|
+
const unit=join(homedir(),'.config/systemd/user/remoteshell-device.service');
|
|
70
|
+
const service=existsSync(unit)?userService({action:'status'}):{unitInstalled:false,active:false};
|
|
71
|
+
return {installed:true,version:receipt.version,registered:false,mockCredentialStored:hasMock,
|
|
72
|
+
connected,gatewayVerified:verified,serviceEnabled:service.enabled===true,serviceActive:service.active===true};
|
|
73
|
+
}
|
|
74
|
+
function install(p){
|
|
75
|
+
if(platform()!=='linux')deny('DEVICE_PLATFORM_UNSUPPORTED');
|
|
76
|
+
for(const d of [p.local,p.share])ensureDir(d);
|
|
77
|
+
ensureDir(p.base,{privateMode:true});
|
|
78
|
+
if(existsSync(p.install))deny('DEVICE_ALREADY_INSTALLED');
|
|
79
|
+
const staging=join(p.base,'.install-'+randomUUID());
|
|
80
|
+
mkdirSync(staging,{mode:0o700});
|
|
81
|
+
try{
|
|
82
|
+
// Package is fetched by npx before this command. Dependencies are pinned;
|
|
83
|
+
// ignore lifecycle scripts and do not execute any downloaded program.
|
|
84
|
+
// Installing directly from a directory makes npm link the ephemeral npx
|
|
85
|
+
// cache. Pack first to ensure the installed Agent survives npx cache cleanup.
|
|
86
|
+
const packed=spawnSync('npm',['pack',packageRoot,'--ignore-scripts','--json','--pack-destination',staging],{
|
|
87
|
+
encoding:'utf8',timeout:30000,maxBuffer:1048576,stdio:'pipe'
|
|
88
|
+
});
|
|
89
|
+
if(packed.error||packed.signal||packed.status!==0)deny('DEVICE_INSTALL_PACKAGE_FAILED');
|
|
90
|
+
let meta;
|
|
91
|
+
try{meta=JSON.parse(packed.stdout);}catch{deny('DEVICE_INSTALL_PACKAGE_FAILED');}
|
|
92
|
+
const entry=Array.isArray(meta)?meta[0]:meta['@remoteshell/device'];
|
|
93
|
+
if(entry?.filename!==`remoteshell-device-${pkg.version}.tgz`)deny('DEVICE_INSTALL_PACKAGE_FAILED');
|
|
94
|
+
const archive=join(staging,entry.filename);
|
|
95
|
+
const result=spawnSync('npm',['install','--prefix',staging,'--ignore-scripts','--no-audit','--no-fund','--no-package-lock','--no-save',archive],{
|
|
96
|
+
encoding:'utf8',timeout:120000,maxBuffer:65536,stdio:'pipe'
|
|
97
|
+
});
|
|
98
|
+
if(result.error||result.signal||result.status!==0)deny('DEVICE_INSTALL_DEPENDENCY_FAILED');
|
|
99
|
+
rmSync(archive,{force:true});
|
|
100
|
+
writeFileSync(join(staging,'receipt.json'),JSON.stringify({
|
|
101
|
+
schema:1,version:pkg.version,distribution:'synthetic-private',registered:false,serviceEnabled:false
|
|
102
|
+
})+'\n',{flag:'wx',mode:0o600});
|
|
103
|
+
checkReceipt(staging);
|
|
104
|
+
if(existsSync(p.install))deny('DEVICE_ALREADY_INSTALLED');
|
|
105
|
+
renameSync(staging,p.install);
|
|
106
|
+
return {installed:true,version:pkg.version,registered:false,connected:false,serviceEnabled:false,
|
|
107
|
+
next:'enrollment-not-yet-implemented'};
|
|
108
|
+
}finally{if(existsSync(staging))rmSync(staging,{recursive:true,force:true});}
|
|
109
|
+
}
|
|
110
|
+
function uninstall(p){
|
|
111
|
+
if(!existsSync(p.base))return {removed:false};
|
|
112
|
+
checkDir(p.base,{privateMode:true});
|
|
113
|
+
if(!existsSync(p.install))return {removed:false};
|
|
114
|
+
checkDir(p.install,{privateMode:true});
|
|
115
|
+
checkReceipt(p.install);
|
|
116
|
+
const unit=join(homedir(),'.config/systemd/user/remoteshell-device.service');
|
|
117
|
+
if(existsSync(unit))deny('DEVICE_UNIT_MUST_BE_REMOVED_FIRST');
|
|
118
|
+
// No service was installed by this CLI version. No other product folder,
|
|
119
|
+
// credentials, existing P4 unit or release is touched.
|
|
120
|
+
rmSync(p.install,{recursive:true,force:false});
|
|
121
|
+
return {removed:true,credentialsPreserved:true,systemdUntouched:true};
|
|
122
|
+
}
|
|
123
|
+
try{
|
|
124
|
+
if(action==='version'||action==='--version'){console.log(pkg.version);}
|
|
125
|
+
else if(action==='install'&&process.argv.length===3)console.log(JSON.stringify(install(paths())));
|
|
126
|
+
else if(action==='status'&&process.argv.length===3)console.log(JSON.stringify(await status(paths())));
|
|
127
|
+
else if(action==='uninstall'&&process.argv.length===3)console.log(JSON.stringify(uninstall(paths())));
|
|
128
|
+
else if(action==='service-install'&&process.argv.length===3)console.log(JSON.stringify(installUserUnit({gatewayUrl:process.env.RS_GATEWAY_URL,caFile:process.env.RS_CA_FILE})));
|
|
129
|
+
else if(['service-start','service-stop','service-restart','service-status','service-enable','service-disable','service-uninstall'].includes(action)&&process.argv.length===3)console.log(JSON.stringify(userService({action:action.slice('service-'.length)})));
|
|
130
|
+
else if(action==='remote'&&process.argv.length===3)console.log(JSON.stringify(await foreground({gatewayUrl:process.env.RS_GATEWAY_URL,caFile:process.env.RS_CA_FILE})));
|
|
131
|
+
else if(['update','register'].includes(action)){
|
|
132
|
+
console.error('DEVICE_ONBOARDING_NOT_READY');
|
|
133
|
+
process.exitCode=2;
|
|
134
|
+
}else{console.error('Usage: remoteshell-device version|install|status|uninstall');process.exitCode=2;}
|
|
135
|
+
}catch(e){
|
|
136
|
+
const codes=new Set(['DEVICE_INSTALL_DENIED','DEVICE_PLATFORM_UNSUPPORTED','DEVICE_ALREADY_INSTALLED','DEVICE_DEPENDENCY_INVALID','DEVICE_INSTALL_DEPENDENCY_FAILED','DEVICE_INSTALL_PACKAGE_FAILED','DEVICE_LIFECYCLE_DENIED','DEVICE_ENROLLMENT_DENIED','DEVICE_UNIT_MUST_BE_REMOVED_FIRST']);
|
|
137
|
+
console.error(codes.has(e.message)?e.message:'DEVICE_INSTALL_DENIED');
|
|
138
|
+
process.exitCode=1;
|
|
139
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// Device-side enrollment CONSUMER. Local synthetic fixture only until #123
|
|
2
|
+
// specifies/ships an authenticated Agent-credential envelope API.
|
|
3
|
+
// Does not implement a Control Plane, owner approval, a database, or a token issuer.
|
|
4
|
+
import {generateKeyPairSync,sign,verify,createHash,randomBytes,createPublicKey,createPrivateKey} from 'node:crypto';
|
|
5
|
+
import {existsSync,lstatSync,mkdirSync,writeFileSync,readFileSync,renameSync,rmSync} from 'node:fs';
|
|
6
|
+
import {join} from 'node:path';
|
|
7
|
+
const FAIL='DEVICE_ENROLLMENT_DENIED';
|
|
8
|
+
const deny=()=>{throw Error(FAIL);};
|
|
9
|
+
const b64=b=>Buffer.from(b).toString('base64url');
|
|
10
|
+
const sha=b=>createHash('sha256').update(b).digest('hex');
|
|
11
|
+
const validId=id=>typeof id==='string'&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id);
|
|
12
|
+
const canonical=data=>JSON.stringify(data);
|
|
13
|
+
const own=(path,mode)=>{
|
|
14
|
+
const s=lstatSync(path);
|
|
15
|
+
if(!s.isFile()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(s.mode&0o777)!==mode)deny();
|
|
16
|
+
};
|
|
17
|
+
function privateDir(path){
|
|
18
|
+
if(!existsSync(path))mkdirSync(path,{mode:0o700});
|
|
19
|
+
const s=lstatSync(path);
|
|
20
|
+
if(!s.isDirectory()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(s.mode&0o777)!==0o700)deny();
|
|
21
|
+
}
|
|
22
|
+
function atomicFile(path,data){
|
|
23
|
+
if(existsSync(path))deny();
|
|
24
|
+
const temp=path+'.tmp-'+b64(randomBytes(12));
|
|
25
|
+
try{writeFileSync(temp,data,{mode:0o600,flag:'wx'});renameSync(temp,path);}finally{rmSync(temp,{force:true});}
|
|
26
|
+
}
|
|
27
|
+
export function prepareDeviceProof({enrollmentId,challenge,consumer='remoteshell-device.v0.1',keypair}={}){
|
|
28
|
+
// PROPOSED v0.1 proof: canonical JSON + Ed25519. Real wire contract is unapproved.
|
|
29
|
+
if(!validId(enrollmentId)||typeof challenge!=='string'||challenge.length<24||challenge.length>2048||
|
|
30
|
+
consumer!=='remoteshell-device.v0.1')deny();
|
|
31
|
+
const keys=keypair||generateKeyPairSync('ed25519');
|
|
32
|
+
const publicKey=keys.publicKey.export({type:'spki',format:'der'});
|
|
33
|
+
const nonce=b64(randomBytes(32));
|
|
34
|
+
const payload={v:'rs-device-proof-mock-v0.1',enrollment_id:enrollmentId,challenge_hash:sha(challenge),consumer,public_key:b64(publicKey),nonce};
|
|
35
|
+
const message=canonical(payload);
|
|
36
|
+
const signature=b64(sign(null,Buffer.from(message),keys.privateKey));
|
|
37
|
+
return {payload,signature,privateKey:keys.privateKey,publicKey:keys.publicKey};
|
|
38
|
+
}
|
|
39
|
+
export function verifyPreparedProof(proof){
|
|
40
|
+
if(proof?.payload?.v!=='rs-device-proof-mock-v0.1'||typeof proof.signature!=='string')deny();
|
|
41
|
+
const publicKey=createPublicKey({key:Buffer.from(proof.payload.public_key,'base64url'),type:'spki',format:'der'});
|
|
42
|
+
if(!verify(null,Buffer.from(canonical(proof.payload)),publicKey,Buffer.from(proof.signature,'base64url')))deny();
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
export function acceptMockCredential({proof,response,fixtureIssuerPublicKey,storageDir,now=Date.now()}={}){
|
|
46
|
+
// Fail closed: a raw/unverified credential or real CP v4 metadata response is
|
|
47
|
+
// never accepted. This fixture format is NOT the supplier API contract.
|
|
48
|
+
if(!proof?.privateKey||!fixtureIssuerPublicKey||!response||response.format!=='rs-device-credential-mock-v0.1')deny();
|
|
49
|
+
try{
|
|
50
|
+
const actualKey=b64(createPublicKey(proof.privateKey).export({type:'spki',format:'der'}));
|
|
51
|
+
if(actualKey!==proof.payload?.public_key||!verifyPreparedProof(proof))deny();
|
|
52
|
+
}catch{deny();}
|
|
53
|
+
if(!validId(response.device_id)||typeof response.credential!=='string'||response.credential.length<32||
|
|
54
|
+
response.credential.length>512||response.approved!==true||
|
|
55
|
+
response.public_key!==proof.payload.public_key||response.enrollment_id!==proof.payload.enrollment_id||
|
|
56
|
+
!Number.isSafeInteger(response.expires_at)||response.expires_at<=now||
|
|
57
|
+
typeof response.signature!=='string')deny();
|
|
58
|
+
const {signature,...body}=response;
|
|
59
|
+
if(!verify(null,Buffer.from(canonical(body)),fixtureIssuerPublicKey,Buffer.from(signature,'base64url')))deny();
|
|
60
|
+
// This path is a disposable synthetic credential store. Never place the
|
|
61
|
+
// credential in stdout, command arguments, web session, npm package, or logs.
|
|
62
|
+
privateDir(storageDir);
|
|
63
|
+
const file=join(storageDir,'device.json');
|
|
64
|
+
atomicFile(file,JSON.stringify({device_id:response.device_id,credential:response.credential})+'\n');
|
|
65
|
+
own(file,0o600);
|
|
66
|
+
return {saved:true,device_id:response.device_id,credentialReturned:false,provider:'mock'};
|
|
67
|
+
}
|
|
68
|
+
export function readDeviceCredential({storageDir}={}){
|
|
69
|
+
const stat=lstatSync(storageDir);
|
|
70
|
+
if(!stat.isDirectory()||stat.isSymbolicLink()||(stat.mode&0o777)!==0o700||stat.uid!==process.getuid?.())deny();
|
|
71
|
+
const file=join(storageDir,'device.json');
|
|
72
|
+
own(file,0o600);
|
|
73
|
+
const value=JSON.parse(readFileSync(file,'utf8'));
|
|
74
|
+
if(Object.keys(value).sort().join(',')!=='credential,device_id'||!validId(value.device_id)||
|
|
75
|
+
typeof value.credential!=='string'||value.credential.length<32)deny();
|
|
76
|
+
return value;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function loadOrCreateMockDeviceKey({storageDir}={}){
|
|
80
|
+
if(!storageDir||typeof storageDir!=='string'||!storageDir.startsWith('/'))deny();
|
|
81
|
+
privateDir(storageDir);
|
|
82
|
+
const file=join(storageDir,'device-key.pem');
|
|
83
|
+
if(!existsSync(file)){
|
|
84
|
+
const pair=generateKeyPairSync('ed25519');
|
|
85
|
+
atomicFile(file,pair.privateKey.export({type:'pkcs8',format:'pem'}));
|
|
86
|
+
}
|
|
87
|
+
own(file,0o600);
|
|
88
|
+
const pem=readFileSync(file,'utf8');
|
|
89
|
+
if(pem.length>8192||!pem.includes('BEGIN PRIVATE KEY'))deny();
|
|
90
|
+
try{
|
|
91
|
+
const privateKey=createPrivateKey(pem);
|
|
92
|
+
if(privateKey.asymmetricKeyType!=='ed25519')deny();
|
|
93
|
+
return {privateKey,publicKey:createPublicKey(privateKey)};
|
|
94
|
+
}catch{deny();}
|
|
95
|
+
}
|
|
96
|
+
// Local mock-only credential revocation; real CP revoke must be confirmed
|
|
97
|
+
// by the authoritative provider before invoking this cleanup.
|
|
98
|
+
export function clearMockCredentialAfterRevoke({storageDir}={}){
|
|
99
|
+
privateDir(storageDir);
|
|
100
|
+
const file=join(storageDir,'device.json');
|
|
101
|
+
if(!existsSync(file))return {cleared:false,provider:'mock'};
|
|
102
|
+
own(file,0o600);
|
|
103
|
+
rmSync(file);
|
|
104
|
+
return {cleared:true,provider:'mock',deviceKeyPreserved:true};
|
|
105
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// #126 device-local lifecycle. Does not implement CP credential issuance.
|
|
2
|
+
// Commands are limited to the current user's dedicated private installation.
|
|
3
|
+
import {existsSync,lstatSync,mkdirSync,readFileSync,writeFileSync,rmSync} from 'node:fs';
|
|
4
|
+
import {homedir} from 'node:os';
|
|
5
|
+
import {dirname,join,resolve} from 'node:path';
|
|
6
|
+
import {spawnSync,spawn} from 'node:child_process';
|
|
7
|
+
import https from 'node:https';
|
|
8
|
+
import {readDeviceCredential} from './enrollment-client.mjs';
|
|
9
|
+
|
|
10
|
+
const ERROR='DEVICE_LIFECYCLE_DENIED';
|
|
11
|
+
const fail=()=>{throw Error(ERROR);};
|
|
12
|
+
const SERVICE='remoteshell-device.service';
|
|
13
|
+
function requireDir(path,mode=null){
|
|
14
|
+
const s=lstatSync(path);
|
|
15
|
+
if(!s.isDirectory()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(mode!==null&&(s.mode&0o777)!==mode))fail();
|
|
16
|
+
}
|
|
17
|
+
function requireFile(path,mode=null){
|
|
18
|
+
const s=lstatSync(path);
|
|
19
|
+
if(!s.isFile()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(mode!==null&&(s.mode&0o777)!==mode))fail();
|
|
20
|
+
}
|
|
21
|
+
function safeGateway({gatewayUrl,caFile}={}){
|
|
22
|
+
try{
|
|
23
|
+
const u=new URL(gatewayUrl);
|
|
24
|
+
if(u.pathname!=='/'||u.username||u.password||u.hash||u.search)fail();
|
|
25
|
+
if(!['http:','https:'].includes(u.protocol)||u.href!==u.protocol+'//'+u.host+'/'||u.host.length>255||[...u.host].some(c=>!'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.:-[]'.includes(c)))fail();
|
|
26
|
+
const local=['127.0.0.1','localhost','[::1]'].includes(u.hostname);
|
|
27
|
+
if(!local&&u.protocol!=='https:')fail();
|
|
28
|
+
if(u.protocol==='https:'){
|
|
29
|
+
if(typeof caFile!=='string'||!/^\/[A-Za-z0-9._/@+-]+$/.test(caFile))fail();
|
|
30
|
+
requireFile(caFile,0o600);requireDir(dirname(caFile),0o700);
|
|
31
|
+
}else if(caFile)fail();
|
|
32
|
+
return {origin:u.href,caFile:u.protocol==='https:'?caFile:null,remote:!local};
|
|
33
|
+
}catch{fail();}
|
|
34
|
+
}
|
|
35
|
+
function paths(home){
|
|
36
|
+
if(typeof home!=='string'||!home.startsWith('/')||resolve(home)==='/')fail();
|
|
37
|
+
requireDir(home);
|
|
38
|
+
const base=join(home,'.local/share/remoteshell-device'),install=join(base,'install');
|
|
39
|
+
requireDir(base,0o700);requireDir(install,0o700);
|
|
40
|
+
const runtime=join(install,'node_modules/@remoteshell/device/src/device-agent/main.mjs');
|
|
41
|
+
requireFile(runtime);
|
|
42
|
+
const credentials=join(base,'credentials');
|
|
43
|
+
const unitDir=join(home,'.config/systemd/user');
|
|
44
|
+
const unit=join(unitDir,SERVICE);
|
|
45
|
+
return {base,install,runtime,credentials,unitDir,unit};
|
|
46
|
+
}
|
|
47
|
+
function credentialPath(p){
|
|
48
|
+
const credential=readDeviceCredential({storageDir:p.credentials});
|
|
49
|
+
if(!credential?.device_id)fail();
|
|
50
|
+
return join(p.credentials,'device.json');
|
|
51
|
+
}
|
|
52
|
+
function checkUnitFile(file){
|
|
53
|
+
if(existsSync(file))requireFile(file,0o600);
|
|
54
|
+
}
|
|
55
|
+
function unitContent(p,gateway,nodeBin){
|
|
56
|
+
// No shell expansion, secrets, or environment from untrusted callers.
|
|
57
|
+
for(const path of [p.runtime,p.credentials,nodeBin,p.install]){
|
|
58
|
+
if(!/^\/[A-Za-z0-9._/@+-]+$/.test(path))fail();
|
|
59
|
+
}
|
|
60
|
+
return [
|
|
61
|
+
'[Unit]','Description=RemoteShell Device Agent (user)','After=network-online.target',
|
|
62
|
+
'Wants=network-online.target','','[Service]','Type=simple',
|
|
63
|
+
'ExecStart='+nodeBin+' '+p.runtime,'Environment=RS_P2_MODE=true',
|
|
64
|
+
'Environment=RS_P2_DEVICE_CREDENTIAL_FILE='+join(p.credentials,'device.json'),
|
|
65
|
+
'Environment=RS_GATEWAY_URL='+gateway.origin,
|
|
66
|
+
...(gateway.caFile?['Environment=RS_CA_FILE='+gateway.caFile]:[]),
|
|
67
|
+
...(gateway.remote?['Environment=RS_ENABLE_REMOTE=true']:[]),
|
|
68
|
+
'WorkingDirectory='+p.install,
|
|
69
|
+
'Restart=on-failure','RestartSec=5','UMask=0077','NoNewPrivileges=yes',
|
|
70
|
+
'PrivateTmp=yes','','[Install]','WantedBy=default.target',''
|
|
71
|
+
].join('\n');
|
|
72
|
+
}
|
|
73
|
+
function systemctl(args,run=spawnSync){
|
|
74
|
+
const result=run('systemctl',['--user',...args],{encoding:'utf8',timeout:5000,maxBuffer:16384,stdio:'pipe'});
|
|
75
|
+
if(result.error||result.signal||result.status!==0)fail();
|
|
76
|
+
return String(result.stdout||'');
|
|
77
|
+
}
|
|
78
|
+
export function installUserUnit({home=homedir(),gatewayUrl,caFile,nodeBin=process.execPath,run=spawnSync}={}){
|
|
79
|
+
const p=paths(home);credentialPath(p);const gateway=safeGateway({gatewayUrl,caFile});
|
|
80
|
+
if(existsSync(p.unit))fail();
|
|
81
|
+
const config=join(home,'.config'),systemd=join(config,'systemd');
|
|
82
|
+
for(const path of [config,systemd,p.unitDir]){
|
|
83
|
+
if(!existsSync(path))mkdirSync(path,{mode:0o700});
|
|
84
|
+
requireDir(path);
|
|
85
|
+
}
|
|
86
|
+
writeFileSync(p.unit,unitContent(p,gateway,nodeBin),{flag:'wx',mode:0o600});
|
|
87
|
+
try{systemctl(['daemon-reload'],run);}catch(e){rmSync(p.unit);throw e;}
|
|
88
|
+
return {unitInstalled:true,enabled:false,started:false,connected:false};
|
|
89
|
+
}
|
|
90
|
+
export function userService({action,home=homedir(),run=spawnSync}={}){
|
|
91
|
+
const p=paths(home);
|
|
92
|
+
if(action==='status'){
|
|
93
|
+
if(!existsSync(p.unit))return {unitInstalled:false,connected:false};
|
|
94
|
+
checkUnitFile(p.unit);
|
|
95
|
+
const r=run('systemctl',['--user','is-active',SERVICE],{encoding:'utf8',timeout:3000,stdio:'pipe'});
|
|
96
|
+
const enabled=run('systemctl',['--user','is-enabled',SERVICE],{encoding:'utf8',timeout:3000,stdio:'pipe'});
|
|
97
|
+
return {unitInstalled:true,active:r.status===0,enabled:enabled.status===0,connected:false};
|
|
98
|
+
}
|
|
99
|
+
checkUnitFile(p.unit);
|
|
100
|
+
if(!existsSync(p.unit))fail();
|
|
101
|
+
if(action==='start'){credentialPath(p);systemctl(['start',SERVICE],run);return {started:true,connected:false};}
|
|
102
|
+
if(action==='stop'){systemctl(['stop',SERVICE],run);return {stopped:true,connected:false};}
|
|
103
|
+
if(action==='restart'){credentialPath(p);systemctl(['restart',SERVICE],run);return {restarted:true,connected:false};}
|
|
104
|
+
if(action==='enable'){credentialPath(p);systemctl(['enable',SERVICE],run);return {enabled:true,connected:false};}
|
|
105
|
+
if(action==='disable'){systemctl(['disable',SERVICE],run);return {enabled:false,connected:false};}
|
|
106
|
+
if(action==='uninstall'){
|
|
107
|
+
// Stop/disable first, fail closed if either operation fails.
|
|
108
|
+
systemctl(['stop',SERVICE],run);systemctl(['disable',SERVICE],run);
|
|
109
|
+
const state=run('systemctl',['--user','is-active',SERVICE],{encoding:'utf8',timeout:3000,stdio:'pipe'});
|
|
110
|
+
if(state.status===0)fail();
|
|
111
|
+
rmSync(p.unit);systemctl(['daemon-reload'],run);
|
|
112
|
+
return {removed:true,credentialsPreserved:true,connected:false};
|
|
113
|
+
}
|
|
114
|
+
fail();
|
|
115
|
+
}
|
|
116
|
+
export async function foreground({home=homedir(),gatewayUrl,caFile,spawnImpl=spawn}={}){
|
|
117
|
+
const p=paths(home),file=credentialPath(p),gateway=safeGateway({gatewayUrl,caFile});
|
|
118
|
+
const child=spawnImpl(process.execPath,[p.runtime],{
|
|
119
|
+
cwd:p.install,stdio:['ignore','ignore','ignore'],
|
|
120
|
+
env:{PATH:process.env.PATH||'/usr/bin:/bin',HOME:home,
|
|
121
|
+
RS_P2_MODE:'true',RS_GATEWAY_URL:gateway.origin,RS_P2_DEVICE_CREDENTIAL_FILE:file,
|
|
122
|
+
...(gateway.caFile?{RS_CA_FILE:gateway.caFile}:{}),
|
|
123
|
+
...(gateway.remote?{RS_ENABLE_REMOTE:'true'}:{}),
|
|
124
|
+
RS_55C1_TEST_MODE:'false',RS_55D_TEST_MODE:'false'}
|
|
125
|
+
});
|
|
126
|
+
return await new Promise((done,reject)=>{
|
|
127
|
+
let exited=false;
|
|
128
|
+
child.once('error',reject);
|
|
129
|
+
child.once('exit',(code,signal)=>{exited=true;done({exited:true,code,signal,connected:false});});
|
|
130
|
+
const stop=()=>{if(!exited)child.kill('SIGTERM');};
|
|
131
|
+
process.once('SIGINT',stop);process.once('SIGTERM',stop);
|
|
132
|
+
child.once('exit',()=>{process.removeListener('SIGINT',stop);process.removeListener('SIGTERM',stop);});
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export async function gatewayStatus({home=homedir(),gatewayUrl,caFile,timeoutMs=3000}={}){
|
|
137
|
+
const p=paths(home);
|
|
138
|
+
const credential=readDeviceCredential({storageDir:p.credentials});
|
|
139
|
+
const gateway=safeGateway({gatewayUrl,caFile});
|
|
140
|
+
const payload=JSON.stringify({device_id:credential.device_id});
|
|
141
|
+
const headers={authorization:'Bearer '+credential.credential,'content-type':'application/json'};
|
|
142
|
+
let response;
|
|
143
|
+
if(gateway.origin.startsWith('https:')){
|
|
144
|
+
response=await new Promise((done,reject)=>{
|
|
145
|
+
const request=https.request(new URL('/device/status',gateway.origin),{
|
|
146
|
+
method:'POST',ca:readFileSync(gateway.caFile),
|
|
147
|
+
headers:{...headers,'content-length':Buffer.byteLength(payload)},
|
|
148
|
+
timeout:timeoutMs
|
|
149
|
+
},res=>{
|
|
150
|
+
let text='';
|
|
151
|
+
res.on('data',chunk=>{text+=chunk;if(text.length>2048)request.destroy(new Error(ERROR));});
|
|
152
|
+
res.on('end',()=>done({status:res.statusCode,text}));
|
|
153
|
+
});
|
|
154
|
+
request.on('error',reject);
|
|
155
|
+
request.on('timeout',()=>request.destroy(new Error(ERROR)));
|
|
156
|
+
request.end(payload);
|
|
157
|
+
});
|
|
158
|
+
}else{
|
|
159
|
+
const r=await fetch(new URL('/device/status',gateway.origin),{
|
|
160
|
+
method:'POST',headers,body:payload,signal:AbortSignal.timeout(timeoutMs)
|
|
161
|
+
});
|
|
162
|
+
const text=await r.text();
|
|
163
|
+
if(text.length>2048)fail();
|
|
164
|
+
response={status:r.status,text};
|
|
165
|
+
}
|
|
166
|
+
if(response.status!==200)fail();
|
|
167
|
+
let data;
|
|
168
|
+
try{data=JSON.parse(response.text);}catch{fail();}
|
|
169
|
+
if(data?.device_id!==credential.device_id||typeof data.connected!=='boolean'||
|
|
170
|
+
Object.keys(data).sort().join(',')!=='connected,device_id')fail();
|
|
171
|
+
return {connected:data.connected,gatewayVerified:true};
|
|
172
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@remoteshell/device",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0-beta.1",
|
|
4
|
+
"description": "RemoteShell device agent private test package; distribution not enabled",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"remoteshell-device": "./bin/device.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin/",
|
|
11
|
+
"src/"
|
|
12
|
+
],
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=22"
|
|
15
|
+
},
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@modelcontextprotocol/sdk": "1.32.1",
|
|
18
|
+
"@wonderwhy-er/desktop-commander": "0.3.0"
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import {lstatSync,readdirSync,realpathSync} from 'node:fs';
|
|
2
|
+
import {isAbsolute,relative,resolve,sep} from 'node:path';
|
|
3
|
+
import {validateReadPath,resolveReadTarget} from './isolated-read-boundary.mjs';
|
|
4
|
+
|
|
5
|
+
export const BOUNDED_SEARCH_LIMITS=Object.freeze({maxSessions:2,maxDepth:3,maxEntries:128,maxFileBytes:65536,maxTreeBytes:4*1024*1024,maxPatternBytes:256,maxFilePatternBytes:128,maxResults:200,maxPage:50,maxPathBytes:256,maxSnippetBytes:256,maxPageBytes:32768,maxSessionBytes:131072,searchTimeoutMs:30000});
|
|
6
|
+
const deny=()=>{throw new Error('SEARCH_SCOPE_DENIED');};
|
|
7
|
+
const utf8Prefix=(value,max)=>{let out='';for(const cp of value){if(Buffer.byteLength(out+cp)>max)break;out+=cp;}return out;};
|
|
8
|
+
const textOf=result=>{if(result?.isError||!Array.isArray(result.content)||result.content.some(x=>x.type!=='text'||typeof x.text!=='string'))deny();const text=result.content.map(x=>x.text).join('\n');if(Buffer.byteLength(text)>BOUNDED_SEARCH_LIMITS.maxSessionBytes)deny();return text;};
|
|
9
|
+
function scanTree(root){
|
|
10
|
+
let entries=0,totalBytes=0;
|
|
11
|
+
const visit=(dir,depth)=>{
|
|
12
|
+
if(depth>BOUNDED_SEARCH_LIMITS.maxDepth)deny();
|
|
13
|
+
for(const name of readdirSync(dir)){
|
|
14
|
+
entries++;if(entries>BOUNDED_SEARCH_LIMITS.maxEntries)deny();
|
|
15
|
+
const abs=resolve(dir,name),rel=relative(root,abs).split(sep).join('/');
|
|
16
|
+
validateReadPath(rel);
|
|
17
|
+
const stat=lstatSync(abs);if(stat.isSymbolicLink()||!stat.isFile()&&!stat.isDirectory())deny();
|
|
18
|
+
if(stat.isDirectory())visit(abs,depth+1);
|
|
19
|
+
else {if(stat.size>BOUNDED_SEARCH_LIMITS.maxFileBytes)deny();totalBytes+=stat.size;if(totalBytes>BOUNDED_SEARCH_LIMITS.maxTreeBytes)deny();}
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
visit(root,0);
|
|
23
|
+
}
|
|
24
|
+
function relativeResultPath(root,value){
|
|
25
|
+
if(typeof value!=='string'||!isAbsolute(value))deny();
|
|
26
|
+
const resolved=resolve(value),rel=relative(root,resolved);
|
|
27
|
+
if(!rel||rel==='..'||rel.startsWith('..'+sep)||isAbsolute(rel))deny();
|
|
28
|
+
const safe=rel.split(sep).join('/');validateReadPath(safe);
|
|
29
|
+
const stat=lstatSync(resolved);if(stat.isSymbolicLink()||!stat.isFile())deny();
|
|
30
|
+
const real=realpathSync(resolved);if(real!==resolved)deny();
|
|
31
|
+
return safe;
|
|
32
|
+
}
|
|
33
|
+
function parseSearchText(text,root){
|
|
34
|
+
const sid=/(?:Started (?:file|content) search session:|Search session:)\s*(search_[A-Za-z0-9_-]+)/.exec(text)?.[1];
|
|
35
|
+
const status=/^Status:\s*(RUNNING|COMPLETED|STOPPED|FAILED)\s*$/m.exec(text)?.[1]??(/terminated successfully/i.test(text)?'STOPPED':undefined);
|
|
36
|
+
const totalMatch=/^Total results:\s*(\d+)\s+match(?:es)?\s*$/im.exec(text);
|
|
37
|
+
const pageMatch=/^Showing results\s+(\d+)-(\d+)(?:\s+of\s+\d+)?\s*$/im.exec(text);
|
|
38
|
+
const emptyOffset=/^No results at offset\s+(\d+)\b/im.exec(text);
|
|
39
|
+
const emptyTotal=/^No results at offset\s+\d+\s+\((\d+)\s+in total\)/im.exec(text);
|
|
40
|
+
const bodyStart=Math.max(text.lastIndexOf('\nResults:'),text.lastIndexOf('\nInitial results:'));
|
|
41
|
+
const body=bodyStart<0?'':text.slice(bodyStart).split('\n').slice(1);
|
|
42
|
+
const results=[];
|
|
43
|
+
for(const line of body){
|
|
44
|
+
let m=/^📁\s+(.+)$/.exec(line);
|
|
45
|
+
if(m){const path=relativeResultPath(root,m[1]);results.push({path,type:'file'});continue;}
|
|
46
|
+
m=/^📄\s+(.+?):(\d+)\s+-\s?(.*)$/.exec(line);
|
|
47
|
+
if(m){const path=relativeResultPath(root,m[1]),lineNumber=Number(m[2]);if(!Number.isSafeInteger(lineNumber)||lineNumber<1)deny();results.push({path,type:'content',line:lineNumber,snippet:utf8Prefix(m[3],BOUNDED_SEARCH_LIMITS.maxSnippetBytes)});continue;}
|
|
48
|
+
}
|
|
49
|
+
return {sessionId:sid,status:status??(emptyOffset?'COMPLETED':undefined),totalResults:totalMatch?Number(totalMatch[1]):emptyTotal?Number(emptyTotal[1]):undefined,offset:pageMatch?Number(pageMatch[1]):emptyOffset?Number(emptyOffset[1]):0,results};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function makeBoundedSearchAdapter({root,rootScopeId,client,verifyRoot=()=>{}}={}){
|
|
53
|
+
if(typeof root!=='string'||typeof rootScopeId!=='string'||!/^[A-Za-z0-9_-]{16,128}$/.test(rootScopeId)||!client||typeof client.callTool!=='function')throw new Error('BOUNDED_SEARCH_DISABLED');
|
|
54
|
+
const canonicalRoot=realpathSync(root),active=new Map();
|
|
55
|
+
const verified=()=>{verifyRoot(canonicalRoot);const target=resolveReadTarget(canonicalRoot,'.',{type:'directory',maxEntries:BOUNDED_SEARCH_LIMITS.maxEntries});scanTree(canonicalRoot);return target.root;};
|
|
56
|
+
const call=async(name,args)=>textOf(await client.callTool({name,arguments:args}));
|
|
57
|
+
const resultEnvelope=value=>{const text=JSON.stringify(value);if(Buffer.byteLength(text)>BOUNDED_SEARCH_LIMITS.maxPageBytes)deny();return text;};
|
|
58
|
+
async function execute(name,args){
|
|
59
|
+
for(const [id,session] of active){if(Date.now()>=session.expiresAt){clearTimeout(session.timer);active.delete(id);await client.callTool({name:'stop_search',arguments:{sessionId:id}}).catch(()=>{});}}
|
|
60
|
+
const rootNow=verified();if(rootNow!==canonicalRoot)deny();
|
|
61
|
+
if(name==='list_searches'){
|
|
62
|
+
if(Object.keys(args).length)deny();
|
|
63
|
+
const raw=await call(name,{}),sessions=[];
|
|
64
|
+
if(raw!=='No active searches.'&&!raw.startsWith('Active Searches ('))deny();
|
|
65
|
+
for(const block of raw.split(/^Session: /m).slice(1)){
|
|
66
|
+
const id=block.split('\n')[0].trim(),status=/^ Status: (?:🔄 |✅ |❌ )?(RUNNING|COMPLETED|ERROR)\s*$/m.exec(block)?.[1];
|
|
67
|
+
if(!/^search_[A-Za-z0-9_-]{1,120}$/.test(id)||!status)deny();
|
|
68
|
+
if(active.has(id)){if(sessions.some(x=>x.sessionId===id))deny();sessions.push({sessionId:id,status});}
|
|
69
|
+
}
|
|
70
|
+
if(sessions.length>BOUNDED_SEARCH_LIMITS.maxSessions)deny();
|
|
71
|
+
return resultEnvelope({kind:'list',rootScopeId,sessions});
|
|
72
|
+
}
|
|
73
|
+
if(name==='start_search'){
|
|
74
|
+
if(active.size>=BOUNDED_SEARCH_LIMITS.maxSessions)deny();
|
|
75
|
+
const safe=validateReadPath(args.path,{allowRoot:true});
|
|
76
|
+
const target=resolveReadTarget(canonicalRoot,safe,{type:'directory',maxEntries:BOUNDED_SEARCH_LIMITS.maxEntries});
|
|
77
|
+
if(Buffer.byteLength(args.pattern,'utf8')>BOUNDED_SEARCH_LIMITS.maxPatternBytes)deny();
|
|
78
|
+
const filePattern=args.filePattern;
|
|
79
|
+
const nativeArgs={path:target.path,pattern:args.pattern,searchType:args.searchType,filePattern,ignoreCase:args.ignoreCase,maxResults:args.maxResults,includeHidden:false,contextLines:2,timeout_ms:BOUNDED_SEARCH_LIMITS.searchTimeoutMs,earlyTermination:false,literalSearch:args.literalSearch};
|
|
80
|
+
for(const key of Object.keys(nativeArgs))if(nativeArgs[key]===undefined)delete nativeArgs[key];
|
|
81
|
+
const started=parseSearchText(await call('start_search',nativeArgs),canonicalRoot);
|
|
82
|
+
if(!started.sessionId||!/^search_[A-Za-z0-9_-]+$/.test(started.sessionId)){deny();}
|
|
83
|
+
const session={expiresAt:Date.now()+120000,timer:null,totalResults:started.totalResults};
|
|
84
|
+
session.timer=setTimeout(()=>{if(active.get(started.sessionId)===session){active.delete(started.sessionId);void client.callTool({name:'stop_search',arguments:{sessionId:started.sessionId}}).catch(()=>{});}},120000);
|
|
85
|
+
session.timer.unref?.();active.set(started.sessionId,session);
|
|
86
|
+
try{
|
|
87
|
+
if(!['RUNNING','COMPLETED'].includes(started.status)||!Number.isSafeInteger(started.totalResults)||started.totalResults>(args.maxResults??BOUNDED_SEARCH_LIMITS.maxResults)||started.results.length>started.totalResults)deny();
|
|
88
|
+
const results=started.results.slice(0,BOUNDED_SEARCH_LIMITS.maxPage);
|
|
89
|
+
const value={kind:'start',sessionId:started.sessionId,rootScopeId,searchType:args.searchType,status:started.status,totalResults:started.totalResults,offset:0,results};
|
|
90
|
+
return resultEnvelope(value);
|
|
91
|
+
}catch(error){clearTimeout(session.timer);active.delete(started.sessionId);await client.callTool({name:'stop_search',arguments:{sessionId:started.sessionId}}).catch(()=>{});throw error;}
|
|
92
|
+
}
|
|
93
|
+
if(name==='get_more_search_results'){
|
|
94
|
+
const sid=args.sessionId;if(!active.has(sid))deny();
|
|
95
|
+
const page=parseSearchText(await call(name,{sessionId:sid,offset:args.offset,length:args.length}),canonicalRoot);
|
|
96
|
+
const totalResults=page.totalResults??active.get(sid).totalResults;
|
|
97
|
+
// Reject malformed or cross-session pages without exposing native search handles.
|
|
98
|
+
// Distinct fixed codes identify the *first* failing invariant in native E2E.
|
|
99
|
+
if(page.sessionId!==sid)throw Error('SEARCH_PAGE_SESSION_DENIED');
|
|
100
|
+
if(!['RUNNING','COMPLETED'].includes(page.status))throw Error('SEARCH_PAGE_STATUS_DENIED');
|
|
101
|
+
if(!Number.isSafeInteger(totalResults)||totalResults<0||totalResults>BOUNDED_SEARCH_LIMITS.maxResults)throw Error('SEARCH_PAGE_TOTAL_INVALID');
|
|
102
|
+
if(totalResults!==active.get(sid).totalResults)throw Error('SEARCH_PAGE_TOTAL_CHANGED');
|
|
103
|
+
if(page.results.length>args.length)throw Error('SEARCH_PAGE_LENGTH_DENIED');
|
|
104
|
+
return resultEnvelope({kind:'page',sessionId:sid,rootScopeId,status:page.status,totalResults,offset:args.offset,results:page.results});
|
|
105
|
+
}
|
|
106
|
+
if(name==='stop_search'){
|
|
107
|
+
const sid=args.sessionId;if(!active.has(sid))deny();
|
|
108
|
+
const response=await call(name,{sessionId:sid});if(!/terminated successfully/i.test(response))deny();
|
|
109
|
+
clearTimeout(active.get(sid).timer);active.delete(sid);return resultEnvelope({kind:'stop',sessionId:sid,rootScopeId,stopped:true});
|
|
110
|
+
}
|
|
111
|
+
deny();
|
|
112
|
+
}
|
|
113
|
+
execute.close=async()=>{for(const [sessionId,session] of active){clearTimeout(session.timer);await client.callTool({name:'stop_search',arguments:{sessionId}}).catch(()=>{});}active.clear();};
|
|
114
|
+
return execute;
|
|
115
|
+
}
|
|
116
|
+
|
|
@@ -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
|
+
|