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

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 (88) 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 +363 -0
  15. package/bin/enrollment-client.mjs +105 -0
  16. package/bin/install-acquire.mjs +89 -0
  17. package/bin/install-integrity.mjs +74 -0
  18. package/bin/install-plan.mjs +43 -0
  19. package/bin/lifecycle.mjs +172 -0
  20. package/bin/native-path-contract.mjs +23 -0
  21. package/bin/remoteshell-device-install.cmd +17 -0
  22. package/bin/remoteshell-device-install.ps1 +17 -0
  23. package/bin/remoteshell-device-install.sh +15 -0
  24. package/bin/remoteshell-device-preflight.cmd +10 -0
  25. package/bin/remoteshell-device-preflight.ps1 +10 -0
  26. package/bin/remoteshell-easy-diagnose.ps1 +32 -0
  27. package/bin/remoteshell-easy-install.ps1 +289 -0
  28. package/bin/remoteshell-easy-install.sh +71 -0
  29. package/bin/remoteshell-easy-uninstall.ps1 +124 -0
  30. package/bin/windows-credential-boundary.mjs +106 -0
  31. package/bin/windows-install-layout.mjs +28 -0
  32. package/bin/windows-native-installer.mjs +88 -0
  33. package/bin/windows-private-store.mjs +163 -0
  34. package/bin/windows-user-lifecycle.mjs +34 -0
  35. package/npm-shrinkwrap.json +8591 -0
  36. package/package.json +27 -4
  37. package/shared/lib/bounded-search-contract.mjs +5 -0
  38. package/shared/lib/bounded-search-policy.mjs +24 -0
  39. package/shared/lib/config.mjs +14 -0
  40. package/shared/lib/contracts.mjs +26 -0
  41. package/shared/lib/dc-generic-policy.mjs +102 -0
  42. package/shared/lib/dc-relay-contract.mjs +42 -0
  43. package/shared/lib/dc-tool-catalog.mjs +67 -0
  44. package/shared/lib/dev-dc-relay-contract.mjs +20 -0
  45. package/shared/lib/dev-paged-output.mjs +32 -0
  46. package/shared/lib/dev-root-exclusions.mjs +56 -0
  47. package/shared/lib/errors.mjs +9 -0
  48. package/shared/lib/events.mjs +5 -0
  49. package/shared/lib/execution-policy.mjs +41 -0
  50. package/shared/lib/isolated-read-boundary.mjs +50 -0
  51. package/shared/lib/isolated-read-policy.mjs +29 -0
  52. package/shared/lib/lifecycle-events.mjs +13 -0
  53. package/shared/lib/runtime-timing.mjs +9 -0
  54. package/shared/lib/synthetic-auxiliary-policy.mjs +21 -0
  55. package/shared/lib/synthetic-write-policy.mjs +52 -0
  56. package/shared/lib/tool-registry.mjs +58 -0
  57. package/src/config/l2-dev-oci-credential.mjs +39 -0
  58. package/src/config/p2-private-credential.mjs +15 -0
  59. package/src/connection/dev-dogfood-processes.mjs +25 -0
  60. package/src/connection/dev-dogfood-read.mjs +64 -0
  61. package/src/connection/dev-dogfood-task.mjs +113 -0
  62. package/src/connection/dev-dogfood-write.mjs +62 -0
  63. package/src/connection/dev-file-task.mjs +119 -0
  64. package/src/connection/dev-r4-file-task.mjs +56 -0
  65. package/src/connection/dev-read-tools.mjs +134 -0
  66. package/src/connection/dev-root-scopes.mjs +82 -0
  67. package/src/core/c1-dc-transport.mjs +26 -0
  68. package/src/core/c1-startup.mjs +22 -0
  69. package/src/core/c1-supervisor.mjs +111 -0
  70. package/src/core/c1-worker.mjs +88 -0
  71. package/src/core/fixture.txt +2 -0
  72. package/src/dc/dc-access-readiness.mjs +31 -0
  73. package/src/dc/dev-dc-relay.mjs +47 -0
  74. package/src/device-agent/main.mjs +1 -0
  75. package/src/gateway-keepalive.mjs +73 -0
  76. package/src/main.mjs +434 -0
  77. package/src/policy/bounded-search-adapter.mjs +115 -0
  78. package/src/policy/isolated-read-adapter.mjs +50 -0
  79. package/src/policy/isolated-read-mount.mjs +27 -0
  80. package/src/policy/synthetic-auxiliary-adapter.mjs +75 -0
  81. package/src/policy/synthetic-file-adapter.mjs +26 -0
  82. package/src/policy/synthetic-file-transaction.mjs +87 -0
  83. package/src/policy/synthetic-write-adapter.mjs +151 -0
  84. package/src/policy/synthetic-write-mount.mjs +23 -0
  85. package/src/policy/verified-bounded-search.mjs +12 -0
  86. package/src/policy/verified-isolated-read.mjs +15 -0
  87. package/src/policy/verified-synthetic-write.mjs +14 -0
  88. package/README.md +0 -3
@@ -0,0 +1,88 @@
1
+ // #310 Windows native user package installation. No service or enrollment.
2
+ // A package-only stage is never reported as Agent connected/DC ready.
3
+ import {existsSync,lstatSync,mkdirSync,readFileSync,writeFileSync,renameSync,rmSync,realpathSync} from 'node:fs';
4
+ import {win32} from 'node:path';
5
+ import {randomUUID} from 'node:crypto';
6
+ import {spawnSync} from 'node:child_process';
7
+ import {windowsInstallLayout} from './windows-install-layout.mjs';
8
+ import {canonicalWindowsLocalFile,isWindowsChildPath} from './native-path-contract.mjs';
9
+ const fail=(code='DEVICE_WINDOWS_INSTALL_DENIED')=>{throw Error(code);};
10
+ function secureDirectory(path,{allowCreate=false}={}){
11
+ canonicalWindowsLocalFile(path);
12
+ if(!existsSync(path)){
13
+ if(!allowCreate)fail();
14
+ mkdirSync(path,{recursive:true});
15
+ }
16
+ const st=lstatSync(path);
17
+ if(!st.isDirectory()||st.isSymbolicLink()||win32.normalize(realpathSync(path)).toLowerCase()!==path.toLowerCase())fail();
18
+ }
19
+ function receipt(install,expected){
20
+ const file=win32.join(install,'receipt.json');
21
+ const st=lstatSync(file);
22
+ if(!st.isFile()||st.isSymbolicLink()||st.size>2048)fail();
23
+ const data=JSON.parse(readFileSync(file,'utf8'));
24
+ if(data?.schema!==1||data.version!==expected||data.distribution!=='synthetic-private'||
25
+ data.registered!==false||data.serviceEnabled!==false)fail();
26
+ for(const [name,version] of [['@remoteshell/device',expected],['@wonderwhy-er/desktop-commander','0.3.1']]){
27
+ const p=win32.join(install,'node_modules',...name.split('/'),'package.json');
28
+ const s=lstatSync(p);
29
+ if(!s.isFile()||s.isSymbolicLink()||JSON.parse(readFileSync(p,'utf8')).version!==version)fail();
30
+ }
31
+ return data;
32
+ }
33
+ export function installWindowsNative({
34
+ home,localAppData,packageRoot,version,nodeBin=process.execPath,run=spawnSync
35
+ }={}){
36
+ const layout=windowsInstallLayout({home,localAppData});
37
+ const {base,install}=layout;
38
+ // LOCALAPPDATA can be absent in remote sessions; use the validated layout.
39
+ const effectiveLocalAppData=win32.dirname(win32.dirname(base));
40
+ for(const p of [home,effectiveLocalAppData,win32.dirname(base),base])secureDirectory(p,{allowCreate:p!==home});
41
+ if(existsSync(install))fail('DEVICE_ALREADY_INSTALLED');
42
+ canonicalWindowsLocalFile(packageRoot);isWindowsChildPath(packageRoot,home);
43
+ // Only resolve npm's trusted installed JavaScript entrypoint. Avoid .cmd,
44
+ // powershell, shell:true and untrusted command interpolation.
45
+ const npmCli=win32.join(win32.dirname(nodeBin),'node_modules','npm','bin','npm-cli.js');
46
+ const st=lstatSync(npmCli);
47
+ if(!st.isFile()||st.isSymbolicLink())fail();
48
+ const staging=win32.join(base,'.install-'+randomUUID());
49
+ mkdirSync(staging);
50
+ try{
51
+ const options={shell:false,windowsHide:true,encoding:'utf8',stdio:'pipe',timeout:120000,maxBuffer:1048576};
52
+ const pack=run(nodeBin,[npmCli,'pack',packageRoot,'--ignore-scripts','--json','--pack-destination',staging],options);
53
+ if(pack.error||pack.signal||pack.status!==0)fail('DEVICE_INSTALL_PACKAGE_FAILED');
54
+ let data;try{data=JSON.parse(pack.stdout);}catch{fail('DEVICE_INSTALL_PACKAGE_FAILED');}
55
+ const entry=Array.isArray(data)?data[0]:null;
56
+ if(entry?.filename!==`remoteshell-device-${version}.tgz`)fail('DEVICE_INSTALL_PACKAGE_FAILED');
57
+ const archive=win32.join(staging,entry.filename);
58
+ const installed=run(nodeBin,[npmCli,'install','--prefix',staging,'--ignore-scripts','--no-audit','--no-fund','--no-package-lock','--no-save',archive],options);
59
+ if(installed.error||installed.signal||installed.status!==0)fail('DEVICE_INSTALL_DEPENDENCY_FAILED');
60
+ rmSync(archive,{force:true});
61
+ writeFileSync(win32.join(staging,'receipt.json'),JSON.stringify({
62
+ schema:1,version,distribution:'synthetic-private',registered:false,serviceEnabled:false
63
+ })+'\n',{flag:'wx'});
64
+ receipt(staging,version);
65
+ if(existsSync(install))fail('DEVICE_ALREADY_INSTALLED');
66
+ renameSync(staging,install);
67
+ return Object.freeze({installed:true,version,registered:false,connected:false,
68
+ dcReady:false,serviceEnabled:false,credentialsPreserved:true,runMode:'not-started',
69
+ next:'owner-consent-and-worker-not-ready'});
70
+ }finally{if(existsSync(staging))rmSync(staging,{recursive:true,force:true});}
71
+ }
72
+ export function statusWindowsNative({home,localAppData,version}={}){
73
+ const p=windowsInstallLayout({home,localAppData});
74
+ if(!existsSync(p.install))return {installed:false,registered:false,connected:false,dcReady:false};
75
+ secureDirectory(p.install);
76
+ receipt(p.install,version);
77
+ return {installed:true,version,registered:false,connected:false,dcReady:false,
78
+ serviceEnabled:false,credentialsPreserved:true};
79
+ }
80
+ export function uninstallWindowsNative({home,localAppData,version}={}){
81
+ const p=windowsInstallLayout({home,localAppData});
82
+ if(!existsSync(p.install))return {removed:false};
83
+ secureDirectory(p.install);receipt(p.install,version);
84
+ // Service operations are still explicitly disabled; delete only the package
85
+ // created by this installer. Never touch separate credentials or RDC.
86
+ rmSync(p.install,{recursive:true,force:false});
87
+ return {removed:true,credentialsPreserved:true,serviceUntouched:true};
88
+ }
@@ -0,0 +1,163 @@
1
+ // Windows native owner-paired DEV credential storage.
2
+ // No existing RDC/RS credential is read, copied, imported or overwritten.
3
+ import {spawnSync} from 'node:child_process';
4
+ import {existsSync,lstatSync,mkdirSync,readFileSync,realpathSync,renameSync,rmSync,writeFileSync} from 'node:fs';
5
+ import {homedir} from 'node:os';
6
+ import {randomBytes} from 'node:crypto';
7
+ import {win32} from 'node:path';
8
+ import {canonicalWindowsLocalFile,isWindowsChildPath} from './native-path-contract.mjs';
9
+ import {inspectWindowsCredentialAcl,inspectWindowsPrivateDirectoryAcl} from './windows-credential-boundary.mjs';
10
+
11
+ const deny=()=>{throw Error('DEVICE_WINDOWS_PRIVATE_STORE_DENIED');};
12
+ const verifiedUpdate=Symbol('windows-private-preverified-update');
13
+ const sidPattern=/^S-1-\d+(?:-\d+){1,15}$/;
14
+ function nativeTool(name){
15
+ const root=process.env.SystemRoot||'C:\\Windows';
16
+ canonicalWindowsLocalFile(root+'\\System32');
17
+ return win32.join(root,'System32',name);
18
+ }
19
+ function runWin(name,args,{run=spawnSync,maxBuffer=8192}={}){
20
+ const res=run(nativeTool(name),args,{shell:false,windowsHide:true,
21
+ encoding:'utf8',timeout:20000,maxBuffer,stdio:'pipe'});
22
+ if(res.error||res.signal||res.status!==0)deny();
23
+ return String(res.stdout||'');
24
+ }
25
+ function currentSid({run=spawnSync}={}){
26
+ const stdout=runWin('whoami.exe',['/user','/fo','csv','/nh'],{run});
27
+ const sid=stdout.match(/S-1-\d+(?:-\d+){1,15}/)?.[0];
28
+ if(!sidPattern.test(sid||''))deny();
29
+ return sid;
30
+ }
31
+ function checkStore(store,{home=homedir()}={}){
32
+ if(process.platform!=='win32')deny();
33
+ canonicalWindowsLocalFile(home);
34
+ isWindowsChildPath(store,home);
35
+ if(!store.toLowerCase().endsWith('\\dev-credentials'))deny();
36
+ const parent=win32.dirname(store);
37
+ canonicalWindowsLocalFile(parent);
38
+ isWindowsChildPath(parent,home);
39
+ for(const item of [home,parent]){
40
+ const st=lstatSync(item);
41
+ if(!st.isDirectory()||st.isSymbolicLink()||
42
+ realpathSync(item).toLowerCase()!==item.toLowerCase())deny();
43
+ }
44
+ return home;
45
+ }
46
+ export function parseWindowsLogonSids(text){
47
+ if(typeof text!=='string'||text.length>8192)deny();
48
+ const numeric=text.match(/S-1-5-5-\d+-\d+/g)||[];
49
+ // icacls sometimes resolves S-1-5-5-X-Y as LogonSessionId_X_Y.
50
+ const named=[...text.matchAll(/LogonSessionId_(\d+)_(\d+)/gi)]
51
+ .map(match=>'S-1-5-5-'+match[1]+'-'+match[2]);
52
+ return [...new Set([...numeric,...named])];
53
+ }
54
+ function sealAcl(path,{directory=false,run=spawnSync}={}){
55
+ const sid=currentSid({run});
56
+ const suffix=directory?':(OI)(CI)F':':F';
57
+ runWin('icacls.exe',[path,'/inheritance:r','/grant:r','*'+sid+suffix,
58
+ '/grant:r','*S-1-5-18'+suffix],{run});
59
+ // Task Scheduler interactive tokens can leave an explicit per-logon SID on
60
+ // freshly written files. /grant:r replaces only grants for named SIDs; it
61
+ // does not remove this extra entry, which the independent ACL verifier denies.
62
+ // Remove only session SIDs, never broaden the user/SYSTEM allowlist.
63
+ const aclText=runWin('icacls.exe',[path],{run});
64
+ // icacls may resolve the same SID to NT AUTHORITY\\LogonSessionId_N_N.
65
+ // Match both localized display forms without granting any new identity.
66
+ const logonSids=parseWindowsLogonSids(aclText);
67
+ for(const logonSid of logonSids){
68
+ runWin('icacls.exe',[path,'/remove:g','*'+logonSid],{run});
69
+ }
70
+ // Windows service tokens may create new files owned by Administrators even
71
+ // when the creator is LocalSystem. Ensure the owner matches the running SID
72
+ // before the independent NTFS owner/ACL verification.
73
+ if(sid==='S-1-5-18')runWin('icacls.exe',[path,'/setowner','*S-1-5-18'],{run});
74
+ }
75
+ export function ensureWindowsPrivateStore(store,{home=homedir(),run=spawnSync}={}){
76
+ if(process.platform!=='win32')deny();
77
+ try{
78
+ canonicalWindowsLocalFile(home);
79
+ isWindowsChildPath(store,home);
80
+ const base=win32.dirname(store);
81
+ canonicalWindowsLocalFile(base);
82
+ isWindowsChildPath(base,home);
83
+ if(!store.toLowerCase().endsWith('\\dev-credentials'))deny();
84
+ const existed=existsSync(store);
85
+ if(!existed){
86
+ if(!existsSync(base))mkdirSync(base,{recursive:true});
87
+ const parent=lstatSync(base);
88
+ if(!parent.isDirectory()||parent.isSymbolicLink()||
89
+ realpathSync(base).toLowerCase()!==base.toLowerCase())deny();
90
+ mkdirSync(store);
91
+ sealAcl(store,{directory:true,run});
92
+ }
93
+ checkStore(store,{home});
94
+ inspectWindowsPrivateDirectoryAcl({directory:store,home});
95
+ return Object.freeze({ready:true,created:!existed,aclVerified:true});
96
+ }catch{deny();}
97
+ }
98
+ function verifyFile(file,{home=homedir()}={}){
99
+ const store=win32.dirname(file);
100
+ checkStore(store,{home});
101
+ // The native file snapshot also checks its protected parent directory.
102
+ // Avoid a duplicate PowerShell invocation in every credential operation.
103
+ inspectWindowsCredentialAcl({file,home});
104
+ }
105
+ export function readWindowsPrivate(file,{home=homedir()}={}){
106
+ try{
107
+ verifyFile(file,{home});
108
+ return readFileSync(file,'utf8');
109
+ }catch{deny();}
110
+ }
111
+ // A one-use update capability keeps the old credential ACL verification and
112
+ // the new credential ACL verification, without re-launching PowerShell twice
113
+ // for an unchanged old file. It never skips the OS owner/DACL checks.
114
+ export function readWindowsPrivateForUpdate(file,{home=homedir()}={}){
115
+ try{
116
+ verifyFile(file,{home});
117
+ const initial=readFileSync(file,'utf8');
118
+ const stat=lstatSync(file);
119
+ if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1)deny();
120
+ let consumed=false;
121
+ return Object.freeze({content:initial,replace(value){
122
+ if(consumed)deny();
123
+ consumed=true;
124
+ try{
125
+ const current=lstatSync(file);
126
+ if(!current.isFile()||current.isSymbolicLink()||current.nlink!==1||
127
+ current.size!==stat.size||current.mtimeMs!==stat.mtimeMs||
128
+ current.ctimeMs!==stat.ctimeMs||readFileSync(file,'utf8')!==initial)deny();
129
+ return atomicWindowsPrivate(file,value,{replace:true,home,
130
+ [verifiedUpdate]:true});
131
+ }catch{deny();}
132
+ }});
133
+ }catch{deny();}
134
+ }
135
+ export function atomicWindowsPrivate(file,value,{replace=false,home=homedir(),run=spawnSync,...proof}={}){
136
+ let temp;
137
+ try{
138
+ if(typeof value!=='string'||Buffer.byteLength(value)>8192||Buffer.byteLength(value)<1)deny();
139
+ const store=win32.dirname(file);
140
+ canonicalWindowsLocalFile(file);
141
+ isWindowsChildPath(file,store);
142
+ // For replacement, existing file verification already checks the parent
143
+ // directory and file ACLs. New files still require a protected store.
144
+ if(replace){
145
+ if(proof[verifiedUpdate]!==true)verifyFile(file,{home});
146
+ else checkStore(store,{home});
147
+ }else {ensureWindowsPrivateStore(store,{home,run});if(existsSync(file))deny();}
148
+ temp=file+'.tmp-'+randomBytes(12).toString('hex');
149
+ writeFileSync(temp,value,{flag:'wx'});
150
+ // The protected parent directory and successful SID-specific icacls seal
151
+ // protect the temporary file. After atomic rename, verify the final file
152
+ // and parent with a fresh independent native ACL snapshot.
153
+ sealAcl(temp,{run});
154
+ if(!replace&&existsSync(file))deny();
155
+ renameSync(temp,file);
156
+ // Windows file replacement can preserve the destination security descriptor.
157
+ // Seal the final file as well, then independently verify its owner/DACL.
158
+ sealAcl(file,{run});
159
+ verifyFile(file,{home});
160
+ return Object.freeze({written:true,aclVerified:true});
161
+ }catch{deny();
162
+ }finally{if(temp&&existsSync(temp))rmSync(temp,{force:true});}
163
+ }
@@ -0,0 +1,34 @@
1
+ // #310 Windows native per-user agent lifecycle. Explicit opt-in only.
2
+ // No admin service, shell invocation, token copy, or implicit enrolment.
3
+ import {spawnSync} from 'node:child_process';
4
+ import {win32} from 'node:path';
5
+ import {canonicalWindowsLocalFile} from './native-path-contract.mjs';
6
+
7
+ const deny=()=>{throw Error('DEVICE_WINDOWS_LIFECYCLE_DENIED');};
8
+ const TASK='RemoteShell Device Agent (User)';
9
+ const safePath=value=>{try{canonicalWindowsLocalFile(value);return true;}catch{return false;}};
10
+ const quote=value=>'"'+value.replaceAll('"','""')+'"';
11
+ export function windowsUserPlan({action,nodeBin,agentScript,os='win32'}={}){
12
+ if(os!=='win32'||!['install','start','stop','status','uninstall'].includes(action))deny();
13
+ if(action==='install'&&(!safePath(nodeBin)||!safePath(agentScript)))deny();
14
+ // Task Scheduler only supports a single command string in /TR. Paths are
15
+ // validated and quoted, with no cmd.exe or PowerShell in the execution path.
16
+ const base=['/TN',TASK];
17
+ if(action==='install')return Object.freeze({program:'schtasks.exe',
18
+ args:['/Create','/SC','ONLOGON','/RL','LIMITED',...base,
19
+ '/TR',quote(win32.normalize(nodeBin))+' '+quote(win32.normalize(agentScript))+' dev-heartbeat'],
20
+ task:TASK,autostart:true,credentialsPreserved:true,approvalRequired:true});
21
+ if(action==='start')return Object.freeze({program:'schtasks.exe',args:['/Run',...base],task:TASK,credentialsPreserved:true});
22
+ if(action==='stop')return Object.freeze({program:'schtasks.exe',args:['/End',...base],task:TASK,credentialsPreserved:true});
23
+ if(action==='status')return Object.freeze({program:'schtasks.exe',args:['/Query',...base,'/FO','LIST'],task:TASK,credentialsPreserved:true});
24
+ return Object.freeze({program:'schtasks.exe',args:['/Delete',...base,'/F'],task:TASK,credentialsPreserved:true});
25
+ }
26
+ export function runWindowsUserPlan(options,{run=spawnSync,confirmed=false}={}){
27
+ if(!confirmed)deny();
28
+ const plan=windowsUserPlan(options);
29
+ const result=run(plan.program,plan.args,{shell:false,windowsHide:true,encoding:'utf8',
30
+ timeout:10000,maxBuffer:16384,stdio:'pipe'});
31
+ if(result?.error||result?.signal||result?.status!==0)deny();
32
+ return Object.freeze({action:options.action,task:plan.task,commandSucceeded:true,
33
+ connected:false,dcReady:false,credentialsPreserved:true});
34
+ }