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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/LICENSE +26 -0
  2. package/NOTICE +20 -0
  3. package/bin/dev-agent-client.mjs +228 -0
  4. package/bin/dev-agent-runner.mjs +60 -0
  5. package/bin/dev-api-client.mjs +31 -0
  6. package/bin/dev-auto-worker.mjs +25 -0
  7. package/bin/dev-browser-open.mjs +12 -0
  8. package/bin/dev-dogfood-read.mjs +3 -0
  9. package/bin/dev-heartbeat-service.mjs +77 -0
  10. package/bin/dev-pairing-client.mjs +63 -0
  11. package/bin/dev-secrets.mjs +33 -0
  12. package/bin/dev-setup-recovery.mjs +34 -0
  13. package/bin/dev-signer-pin.mjs +22 -0
  14. package/bin/device.mjs +384 -0
  15. package/bin/direct-npx-runtime.mjs +150 -0
  16. package/bin/enrollment-client.mjs +105 -0
  17. package/bin/install-acquire.mjs +89 -0
  18. package/bin/install-integrity.mjs +74 -0
  19. package/bin/install-plan.mjs +43 -0
  20. package/bin/lifecycle.mjs +172 -0
  21. package/bin/native-path-contract.mjs +23 -0
  22. package/bin/remoteshell-device-install.cmd +17 -0
  23. package/bin/remoteshell-device-install.ps1 +17 -0
  24. package/bin/remoteshell-device-install.sh +15 -0
  25. package/bin/remoteshell-device-preflight.cmd +10 -0
  26. package/bin/remoteshell-device-preflight.ps1 +10 -0
  27. package/bin/remoteshell-easy-diagnose.ps1 +32 -0
  28. package/bin/remoteshell-easy-install.ps1 +292 -0
  29. package/bin/remoteshell-easy-install.sh +71 -0
  30. package/bin/remoteshell-easy-uninstall.ps1 +128 -0
  31. package/bin/windows-acl-wmi-client.mjs +50 -0
  32. package/bin/windows-acl-wmi.js +43 -0
  33. package/bin/windows-credential-boundary.mjs +113 -0
  34. package/bin/windows-direct-autostart-runner.mjs +50 -0
  35. package/bin/windows-direct-autostart.mjs +110 -0
  36. package/bin/windows-install-layout.mjs +28 -0
  37. package/bin/windows-native-installer.mjs +91 -0
  38. package/bin/windows-private-store.mjs +176 -0
  39. package/bin/windows-user-lifecycle.mjs +34 -0
  40. package/npm-shrinkwrap.json +8591 -0
  41. package/package.json +27 -4
  42. package/shared/lib/bounded-search-contract.mjs +5 -0
  43. package/shared/lib/bounded-search-policy.mjs +24 -0
  44. package/shared/lib/config.mjs +14 -0
  45. package/shared/lib/contracts.mjs +26 -0
  46. package/shared/lib/dc-generic-policy.mjs +102 -0
  47. package/shared/lib/dc-relay-contract.mjs +42 -0
  48. package/shared/lib/dc-tool-catalog.mjs +67 -0
  49. package/shared/lib/dev-dc-relay-contract.mjs +20 -0
  50. package/shared/lib/dev-paged-output.mjs +32 -0
  51. package/shared/lib/dev-root-exclusions.mjs +56 -0
  52. package/shared/lib/errors.mjs +9 -0
  53. package/shared/lib/events.mjs +5 -0
  54. package/shared/lib/execution-policy.mjs +41 -0
  55. package/shared/lib/isolated-read-boundary.mjs +50 -0
  56. package/shared/lib/isolated-read-policy.mjs +29 -0
  57. package/shared/lib/lifecycle-events.mjs +13 -0
  58. package/shared/lib/runtime-timing.mjs +9 -0
  59. package/shared/lib/synthetic-auxiliary-policy.mjs +21 -0
  60. package/shared/lib/synthetic-write-policy.mjs +52 -0
  61. package/shared/lib/tool-registry.mjs +58 -0
  62. package/src/config/l2-dev-oci-credential.mjs +39 -0
  63. package/src/config/p2-private-credential.mjs +15 -0
  64. package/src/connection/dev-dogfood-processes.mjs +25 -0
  65. package/src/connection/dev-dogfood-read.mjs +64 -0
  66. package/src/connection/dev-dogfood-task.mjs +113 -0
  67. package/src/connection/dev-dogfood-write.mjs +62 -0
  68. package/src/connection/dev-file-task.mjs +119 -0
  69. package/src/connection/dev-r4-file-task.mjs +56 -0
  70. package/src/connection/dev-read-tools.mjs +134 -0
  71. package/src/connection/dev-root-scopes.mjs +82 -0
  72. package/src/core/c1-dc-transport.mjs +26 -0
  73. package/src/core/c1-startup.mjs +22 -0
  74. package/src/core/c1-supervisor.mjs +111 -0
  75. package/src/core/c1-worker.mjs +88 -0
  76. package/src/core/fixture.txt +2 -0
  77. package/src/dc/dc-access-readiness.mjs +31 -0
  78. package/src/dc/dev-dc-relay.mjs +47 -0
  79. package/src/device-agent/main.mjs +1 -0
  80. package/src/gateway-keepalive.mjs +73 -0
  81. package/src/main.mjs +436 -0
  82. package/src/policy/bounded-search-adapter.mjs +115 -0
  83. package/src/policy/isolated-read-adapter.mjs +50 -0
  84. package/src/policy/isolated-read-mount.mjs +27 -0
  85. package/src/policy/synthetic-auxiliary-adapter.mjs +75 -0
  86. package/src/policy/synthetic-file-adapter.mjs +26 -0
  87. package/src/policy/synthetic-file-transaction.mjs +87 -0
  88. package/src/policy/synthetic-write-adapter.mjs +151 -0
  89. package/src/policy/synthetic-write-mount.mjs +23 -0
  90. package/src/policy/verified-bounded-search.mjs +12 -0
  91. package/src/policy/verified-isolated-read.mjs +15 -0
  92. package/src/policy/verified-synthetic-write.mjs +14 -0
  93. package/README.md +0 -3
@@ -0,0 +1,22 @@
1
+ // #310 Private DEV signing trust anchor. Copied from the existing pinned
2
+ // platform artifact delivery contract, not supplied by a remote manifest.
3
+ import {createHash,createPublicKey} from 'node:crypto';
4
+ import {lstatSync,readFileSync} from 'node:fs';
5
+ export const DEV_SIGNER_SPKI_SHA256='b9d6e83b1f270bdd69b80e4f577090fe1be39225ce538808200fe95e0b671b3e';
6
+ const fail=()=>{throw Error('DEVICE_INSTALL_TRUST_ANCHOR_INVALID');};
7
+ export function loadPinnedDevSigner({publicKeyPath}={}){
8
+ if(typeof publicKeyPath!=='string'||!publicKeyPath||publicKeyPath.length>2048)fail();
9
+ let bytes;
10
+ try{
11
+ const stat=lstatSync(publicKeyPath);
12
+ if(!stat.isFile()||stat.isSymbolicLink()||stat.size<50||stat.size>8192)fail();
13
+ bytes=readFileSync(publicKeyPath);
14
+ if(bytes.length!==stat.size)fail();
15
+ }catch{fail();}
16
+ let key;
17
+ try{key=createPublicKey(bytes);}catch{fail();}
18
+ if(key.type!=='public'||key.asymmetricKeyType!=='ed25519')fail();
19
+ const digest=createHash('sha256').update(key.export({type:'spki',format:'der'})).digest('hex');
20
+ if(digest!==DEV_SIGNER_SPKI_SHA256)fail();
21
+ return Object.freeze({[DEV_SIGNER_SPKI_SHA256]:key});
22
+ }
package/bin/device.mjs ADDED
@@ -0,0 +1,384 @@
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 {createInterface} from 'node:readline/promises';
12
+ import {foreground,installUserUnit,userService,gatewayStatus} from './lifecycle.mjs';
13
+ import {readDeviceCredential} from './enrollment-client.mjs';
14
+ import {probeDev} from './dev-api-client.mjs';
15
+ import {devEnroll,devHeartbeatOnce,devHeartbeatForeground,devLocalStatus,devOfficialRegistration,readDevCapabilityFromStdin} from './dev-agent-client.mjs';
16
+ import {devPairDevice} from './dev-pairing-client.mjs';
17
+ import {resumeRegisteredDevice,recoverRevokedDevice} from './dev-setup-recovery.mjs';
18
+ import {openDevApproval} from './dev-browser-open.mjs';
19
+ import {configureDevHeartbeatService,controlDevHeartbeatService,uninstallDevHeartbeatService} from './dev-heartbeat-service.mjs';
20
+ import {runDevAgentWorker} from './dev-agent-runner.mjs';
21
+ import {startOfficialWorker} from './dev-auto-worker.mjs';
22
+ import {installPreflight} from './install-integrity.mjs';
23
+ import {planVerifiedInstall} from './install-plan.mjs';
24
+ import {acquireVerifiedDevArchive} from './install-acquire.mjs';
25
+ import {loadPinnedDevSigner} from './dev-signer-pin.mjs';
26
+ import {runWindowsUserPlan} from './windows-user-lifecycle.mjs';
27
+ import {windowsInstallLayout} from './windows-install-layout.mjs';
28
+ import {installWindowsNative,statusWindowsNative,uninstallWindowsNative} from './windows-native-installer.mjs';
29
+ import {ensureWindowsPrivateStore} from './windows-private-store.mjs';
30
+ import {directPaths,directRegister,directRun} from './direct-npx-runtime.mjs';
31
+ import {enableDirectAutostart,disableDirectAutostart,directAutostartStatus} from './windows-direct-autostart.mjs';
32
+ const require=createRequire(import.meta.url);
33
+ const pkg=require('../package.json');
34
+ const packageRoot=resolve(dirname(fileURLToPath(import.meta.url)),'..');
35
+ const action=process.argv[2];
36
+ const deny=(code='DEVICE_INSTALL_DENIED')=>{throw Error(code);};
37
+ const currentUid=process.getuid?.();
38
+ function checkDir(path,{privateMode=false}={}){
39
+ const stat=lstatSync(path);
40
+ if(!stat.isDirectory()||stat.isSymbolicLink()||(currentUid!==undefined&&stat.uid!==currentUid)||(privateMode&&(stat.mode&0o777)!==0o700))deny();
41
+ }
42
+ function ensureDir(path,{privateMode=false}={}){
43
+ if(!existsSync(path))mkdirSync(path,{mode:0o700});
44
+ checkDir(path,{privateMode});
45
+ }
46
+ function paths(){
47
+ const home=homedir();
48
+ if(!home||!home.startsWith('/')||resolve(home)==='/')deny();
49
+ checkDir(home);
50
+ const local=join(home,'.local'),share=join(local,'share');
51
+ const base=join(share,'remoteshell-device');
52
+ return {local,share,base,install:join(base,'install')};
53
+ }
54
+ function checkReceipt(root){
55
+ const receiptPath=join(root,'receipt.json');
56
+ if(!existsSync(receiptPath))deny();
57
+ const st=lstatSync(receiptPath);
58
+ if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o777)!==0o600||(currentUid!==undefined&&st.uid!==currentUid)||st.size>2048)deny();
59
+ const data=JSON.parse(readFileSync(receiptPath,'utf8'));
60
+ if(data?.schema!==1||data.version!==pkg.version||data.distribution!=='synthetic-private'||data.registered!==false||data.serviceEnabled!==false)deny();
61
+ const runtimePkg=join(root,'node_modules','@remoteshell','device','package.json');
62
+ const dcPkg=join(root,'node_modules','@wonderwhy-er','desktop-commander','package.json');
63
+ for(const file of [runtimePkg,dcPkg]){
64
+ const s=lstatSync(file);
65
+ if(!s.isFile()||s.isSymbolicLink())deny();
66
+ }
67
+ const installed=JSON.parse(readFileSync(runtimePkg,'utf8'));
68
+ const dc=JSON.parse(readFileSync(dcPkg,'utf8'));
69
+ if(installed.name!==pkg.name||installed.version!==pkg.version||dc.version!=='0.3.1')deny('DEVICE_DEPENDENCY_INVALID');
70
+ return data;
71
+ }
72
+ async function confirmReenrollment(){
73
+ console.error('기존 장치 등록이 취소되었거나 인증이 만료되었습니다. 다시 등록하기');
74
+ if(!process.stdin.isTTY||!process.stderr.isTTY)deny('DEVICE_REREGISTRATION_CONFIRM_REQUIRED');
75
+ const prompt=createInterface({input:process.stdin,output:process.stderr});
76
+ try{
77
+ const answer=(await prompt.question('새 장치로 다시 등록할까요? [y/N]: ')).trim().toLowerCase();
78
+ return answer==='y'||answer==='yes';
79
+ }finally{prompt.close();}
80
+ }
81
+ async function status(p){
82
+ if(!existsSync(p.base))return {installed:false,registered:false,connected:false};
83
+ checkDir(p.base,{privateMode:true});
84
+ if(!existsSync(p.install))return {installed:false,registered:false,connected:false};
85
+ checkDir(p.install,{privateMode:true});
86
+ const receipt=checkReceipt(p.install);
87
+ const store=join(p.base,'credentials'),credential=join(store,'device.json');
88
+ const hasMock=existsSync(credential);
89
+ if(hasMock)readDeviceCredential({storageDir:store}); // refuse tampered credentials
90
+ let verified=false,connected=false;
91
+ if(hasMock&&process.env.RS_GATEWAY_URL){
92
+ try{
93
+ const online=await gatewayStatus({gatewayUrl:process.env.RS_GATEWAY_URL,caFile:process.env.RS_CA_FILE});
94
+ verified=online.gatewayVerified;connected=online.connected;
95
+ }catch{verified=false;connected=false;}
96
+ }
97
+ const unit=join(homedir(),'.config/systemd/user/remoteshell-device.service');
98
+ const service=existsSync(unit)?userService({action:'status'}):{unitInstalled:false,active:false};
99
+ const dev=devLocalStatus({storageDir:join(p.base,'dev-credentials')});
100
+ let devRuntime;
101
+ try{const status=controlDevHeartbeatService({action:'status'});
102
+ devRuntime={devUnitInstalled:status.unitInstalled,devProcessRunning:status.running,
103
+ devAutostartEnabled:status.autostartEnabled};
104
+ }catch{devRuntime={devUnitInstalled:'unknown',devProcessRunning:'unknown',devAutostartEnabled:'unknown'};}
105
+ return {installed:true,version:receipt.version,registered:dev.devRegistered,...devRuntime,mockCredentialStored:hasMock,
106
+ connected,gatewayVerified:verified,serviceEnabled:service.enabled===true,serviceActive:service.active===true,
107
+ // The on-device status command cannot prove a remote DC catalog is live.
108
+ // The authenticated owner /dev/devices page resolves this independently.
109
+ heartbeatState:dev.devRegistered?'unverified':'not-registered',
110
+ dcReadiness:'unverified',...dev};
111
+ }
112
+ function install(p){
113
+ if(platform()!=='linux')deny('DEVICE_PLATFORM_UNSUPPORTED');
114
+ for(const d of [p.local,p.share])ensureDir(d);
115
+ ensureDir(p.base,{privateMode:true});
116
+ if(existsSync(p.install))deny('DEVICE_ALREADY_INSTALLED');
117
+ const staging=join(p.base,'.install-'+randomUUID());
118
+ mkdirSync(staging,{mode:0o700});
119
+ try{
120
+ // Package is fetched by npx before this command. Dependencies are pinned;
121
+ // ignore lifecycle scripts and do not execute any downloaded program.
122
+ // Installing directly from a directory makes npm link the ephemeral npx
123
+ // cache. Pack first to ensure the installed Agent survives npx cache cleanup.
124
+ const packed=spawnSync('npm',['pack',packageRoot,'--ignore-scripts','--json','--pack-destination',staging],{
125
+ encoding:'utf8',timeout:30000,maxBuffer:1048576,stdio:'pipe'
126
+ });
127
+ if(packed.error||packed.signal||packed.status!==0)deny('DEVICE_INSTALL_PACKAGE_FAILED');
128
+ let meta;
129
+ try{meta=JSON.parse(packed.stdout);}catch{deny('DEVICE_INSTALL_PACKAGE_FAILED');}
130
+ const entry=Array.isArray(meta)?meta[0]:meta['@remoteshell/device'];
131
+ if(entry?.filename!==`remoteshell-device-${pkg.version}.tgz`)deny('DEVICE_INSTALL_PACKAGE_FAILED');
132
+ const archive=join(staging,entry.filename);
133
+ const result=spawnSync('npm',['install','--prefix',staging,'--ignore-scripts','--no-audit','--no-fund','--no-package-lock','--no-save',archive],{
134
+ encoding:'utf8',timeout:120000,maxBuffer:65536,stdio:'pipe'
135
+ });
136
+ if(result.error||result.signal||result.status!==0)deny('DEVICE_INSTALL_DEPENDENCY_FAILED');
137
+ rmSync(archive,{force:true});
138
+ writeFileSync(join(staging,'receipt.json'),JSON.stringify({
139
+ schema:1,version:pkg.version,distribution:'synthetic-private',registered:false,serviceEnabled:false
140
+ })+'\n',{flag:'wx',mode:0o600});
141
+ checkReceipt(staging);
142
+ if(existsSync(p.install))deny('DEVICE_ALREADY_INSTALLED');
143
+ renameSync(staging,p.install);
144
+ return {installed:true,version:pkg.version,registered:false,connected:false,serviceEnabled:false,
145
+ next:'enrollment-not-yet-implemented'};
146
+ }finally{if(existsSync(staging))rmSync(staging,{recursive:true,force:true});}
147
+ }
148
+ function uninstall(p){
149
+ if(!existsSync(p.base))return {removed:false};
150
+ checkDir(p.base,{privateMode:true});
151
+ if(!existsSync(p.install))return {removed:false};
152
+ checkDir(p.install,{privateMode:true});
153
+ checkReceipt(p.install);
154
+ const unit=join(homedir(),'.config/systemd/user/remoteshell-device.service');
155
+ if(existsSync(unit))deny('DEVICE_UNIT_MUST_BE_REMOVED_FIRST');
156
+ const devUnit=join(homedir(),'.config/systemd/user/remoteshell-device-dev-heartbeat.service');
157
+ if(existsSync(devUnit))deny('DEVICE_UNIT_MUST_BE_REMOVED_FIRST');
158
+ // No service was installed by this CLI version. No other product folder,
159
+ // credentials, existing P4 unit or release is touched.
160
+ rmSync(p.install,{recursive:true,force:false});
161
+ return {removed:true,credentialsPreserved:true,systemdUntouched:true};
162
+ }
163
+ try{
164
+ if(action==='run'&&process.argv.length===3){
165
+ const outcome=await directRun(directPaths(),{packageRoot});
166
+ process.exitCode=outcome.exitCode;
167
+ }
168
+ else if(action==='register'&&process.argv.length===3){
169
+ console.log(JSON.stringify(await directRegister(directPaths())));
170
+ }
171
+ else if(action==='autostart-enable'&&process.argv.length===3){
172
+ if(platform()!=='win32')deny('DEVICE_PLATFORM_UNSUPPORTED');
173
+ console.log(JSON.stringify(enableDirectAutostart({version:pkg.version})));
174
+ }
175
+ else if(action==='autostart-disable'&&process.argv.length===3){
176
+ if(platform()!=='win32')deny('DEVICE_PLATFORM_UNSUPPORTED');
177
+ console.log(JSON.stringify(disableDirectAutostart()));
178
+ }
179
+ else if(action==='autostart-status'&&process.argv.length===3){
180
+ if(platform()!=='win32')deny('DEVICE_PLATFORM_UNSUPPORTED');
181
+ console.log(JSON.stringify(directAutostartStatus()));
182
+ }
183
+ else if(action==='install-preflight'&&process.argv.length===3){
184
+ let wsl=false;
185
+ if(platform()==='linux'){try{wsl=/microsoft|wsl/i.test(readFileSync('/proc/version','utf8'));}catch{}}
186
+ console.log(JSON.stringify(installPreflight({os:platform(),arch:process.arch,nodeVersion:process.version,wsl})));
187
+ }
188
+ else if(action==='windows-layout'&&process.argv.length===3){
189
+ if(platform()!=='win32')deny('DEVICE_PLATFORM_UNSUPPORTED');
190
+ console.log(JSON.stringify(windowsInstallLayout({
191
+ home:homedir(),localAppData:process.env.LOCALAPPDATA,os:platform()
192
+ })));
193
+ }
194
+ else if(action==='windows-pair'&&process.argv.length===4){
195
+ if(platform()!=='win32')deny('DEVICE_PLATFORM_UNSUPPORTED');
196
+ const home=homedir();
197
+ const layout=windowsInstallLayout({home,localAppData:process.env.LOCALAPPDATA});
198
+ if(!statusWindowsNative({home,localAppData:process.env.LOCALAPPDATA,version:pkg.version}).installed)
199
+ deny('DEVICE_WINDOWS_INSTALL_DENIED');
200
+ ensureWindowsPrivateStore(layout.credentials,{home});
201
+ const previous=devLocalStatus({storageDir:layout.credentials});
202
+ if(previous.devRegistered)deny('DEVICE_ALREADY_REGISTERED');
203
+ const result=await devPairDevice({base:process.argv[3],storageDir:layout.credentials,
204
+ onApprove:url=>console.log(JSON.stringify({next:'approve-device-in-browser',
205
+ approval_url:url,ownerApprovalRequired:true}))});
206
+ console.log(JSON.stringify({...result,runMode:'not-started',
207
+ dcReady:false,autostart:false,next:'windows-start-worker'}));
208
+ }
209
+ else if(action==='install-download-verify'&&process.argv.length===7){
210
+ // Download to a private temporary staging folder and verify with the
211
+ // independently pinned DEV signer; never run or install the archive.
212
+ const [allowedOrigin,manifestUrl,archiveUrl,publicKeyPath]=process.argv.slice(3);
213
+ let wsl=false;
214
+ if(platform()==='linux'){try{wsl=/microsoft|wsl/i.test(readFileSync('/proc/version','utf8'));}catch{}}
215
+ const result=await acquireVerifiedDevArchive({allowedOrigin,manifestUrl,archiveUrl,
216
+ publicKeyPath,os:platform(),arch:process.arch,nodeVersion:process.version,wsl});
217
+ console.log(JSON.stringify(result));
218
+ }
219
+ else if(action==='install-verify'&&process.argv.length===6){
220
+ // Offline only. The manifest/public key cannot establish their own trust:
221
+ // the signer is accepted only after matching the independently pinned DEV key.
222
+ const [artifactPath,manifestPath,keyPath]=process.argv.slice(3);
223
+ const stat=lstatSync(manifestPath);
224
+ if(!stat.isFile()||stat.isSymbolicLink()||stat.size<1||stat.size>8192)
225
+ deny('DEVICE_INSTALL_MANIFEST_DENIED');
226
+ let manifest;
227
+ try{manifest=JSON.parse(readFileSync(manifestPath,'utf8'));}catch{deny('DEVICE_INSTALL_MANIFEST_DENIED');}
228
+ const trustedKeys=loadPinnedDevSigner({publicKeyPath:keyPath});
229
+ let wsl=false;
230
+ if(platform()==='linux'){try{wsl=/microsoft|wsl/i.test(readFileSync('/proc/version','utf8'));}catch{}}
231
+ const result=planVerifiedInstall({artifactPath,manifest,trustedKeys,
232
+ os:platform(),arch:process.arch,nodeVersion:process.version,wsl});
233
+ console.log(JSON.stringify(result));
234
+ }
235
+ else if(['windows-service-install','windows-service-start','windows-service-stop','windows-service-status','windows-service-uninstall'].includes(action)&&process.argv.length===4&&process.argv[3]==='--confirm'){
236
+ // Opt-in native Windows lifecycle: no implicit account registration or service modification.
237
+ if(platform()!=='win32')deny('DEVICE_PLATFORM_UNSUPPORTED');
238
+ const operation=action.slice('windows-service-'.length);
239
+ // Only a paired, version-checked per-user installation may own this task.
240
+ // No SYSTEM service, RDC task, credentials or installer-cache entry is used.
241
+ const home=homedir(),localAppData=process.env.LOCALAPPDATA;
242
+ const layout=windowsInstallLayout({home,localAppData});
243
+ const native=statusWindowsNative({home,localAppData,version:pkg.version});
244
+ if(!native.installed)deny('DEVICE_WINDOWS_INSTALL_DENIED');
245
+ const registered=devOfficialRegistration({storageDir:layout.credentials});
246
+ if(['install','start'].includes(operation)&&!registered)deny('DEVICE_ENROLLMENT_DENIED');
247
+ const script=join(layout.install,'node_modules','@remoteshell','device','bin','device.mjs');
248
+ if(!existsSync(script))deny('DEVICE_WINDOWS_INSTALL_DENIED');
249
+ const result=runWindowsUserPlan({action:operation,nodeBin:process.execPath,
250
+ agentScript:script},{confirmed:true});
251
+ console.log(JSON.stringify({...result,registered:!!registered,deviceId:registered?.deviceId,
252
+ next:operation==='install'?'run-windows-service-start':'verify-device-in-owner-ui'}));
253
+ }
254
+ else if(action==='version'||action==='--version'){console.log(pkg.version);}
255
+ else if(action==='dev-check'&&process.argv.length===4)console.log(JSON.stringify(await probeDev({url:process.argv[3]})));
256
+ else if(action==='dev-enroll'&&process.argv.length===5){
257
+ const p=paths();ensureDir(p.local);ensureDir(p.share);ensureDir(p.base,{privateMode:true});
258
+ console.log(JSON.stringify(await devEnroll({base:process.argv[3],enrollmentId:process.argv[4],storageDir:join(p.base,'dev-credentials'),capability:readDevCapabilityFromStdin()})));
259
+ }
260
+ else if(action==='dev-heartbeat'&&process.argv.length===3){
261
+ const home=homedir();
262
+ const p=platform()==='win32'?windowsInstallLayout({home,localAppData:process.env.LOCALAPPDATA}):paths();
263
+ const storageDir=join(p.base,'dev-credentials');
264
+ const child=startOfficialWorker({home,install:p.install,storageDir});
265
+ if(!child){
266
+ const abort=new AbortController();
267
+ process.once('SIGINT',()=>abort.abort());process.once('SIGTERM',()=>abort.abort());
268
+ console.log(JSON.stringify(await devHeartbeatForeground({storageDir,signal:abort.signal})));
269
+ }
270
+ }
271
+ else if(action==='dev-heartbeat-once'&&process.argv.length===3){
272
+ const home=homedir();
273
+ const p=platform()==='win32'?windowsInstallLayout({home,localAppData:process.env.LOCALAPPDATA}):paths();
274
+ console.log(JSON.stringify(await devHeartbeatOnce({storageDir:join(p.base,'dev-credentials')})));
275
+ }
276
+ else if(action==='dev-agent-run'&&process.argv.length===6){
277
+ const p=paths();checkReceipt(p.install);
278
+ const rootId=process.argv[4],rootPath=process.argv[5];
279
+ const credentialFile=join(p.base,'dev-credentials','device.json');
280
+ devLocalStatus({storageDir:join(p.base,'dev-credentials')});
281
+ const mainFile=join(p.install,'node_modules/@remoteshell/device/src/device-agent/main.mjs');
282
+ const child=runDevAgentWorker({gatewayUrl:process.argv[3],credentialFile,rootId,rootPath,
283
+ mainFile,home:homedir()});
284
+ child.once('error',()=>deny('DEVICE_DEV_AGENT_RUN_DENIED'));
285
+ child.once('exit',(code,signal)=>{if(signal)process.kill(process.pid,signal);else process.exitCode=code??1;});
286
+ }
287
+ else if(action==='setup'&&process.argv.length>=4&&process.argv.length<=6){
288
+ const mode=process.argv[4]??'foreground';
289
+ const confirmLinger=process.argv[5]==='--confirm-linger';
290
+ if(!['foreground','manual','login','boot'].includes(mode)||
291
+ (process.argv.length===6&&!confirmLinger)||
292
+ (confirmLinger&&mode!=='boot'))deny('DEVICE_DEV_SERVICE_DENIED');
293
+ const p=paths();
294
+ const base=process.argv[3];
295
+ // Install first, then request browser owner consent. On failure the CLI must
296
+ // never claim registration or an enabled background service.
297
+ if(!existsSync(p.install))install(p);
298
+ else checkReceipt(p.install);
299
+ const credentialDir=join(p.base,'dev-credentials');
300
+ const already=devLocalStatus({storageDir:credentialDir});
301
+ const pairDevice=options=>devPairDevice({base,storageDir:credentialDir,...options,
302
+ onApprove:url=>{
303
+ console.log(JSON.stringify({next:'approve-device-in-browser',approval_url:url}));
304
+ openDevApproval(url,{base});
305
+ }});
306
+ let out;
307
+ if(already.devRegistered){
308
+ try{
309
+ out=await resumeRegisteredDevice({localStatus:already,
310
+ heartbeatOnce:()=>devHeartbeatOnce({storageDir:credentialDir})});
311
+ }catch(e){
312
+ if(e?.message!=='DEVICE_DEV_CREDENTIAL_REVOKED')throw e;
313
+ out=await recoverRevokedDevice({localStatus:already,
314
+ confirmReplacement:confirmReenrollment,pairDevice});
315
+ }
316
+ }else out=await pairDevice();
317
+ if(mode==='foreground'){
318
+ const child=startOfficialWorker({home:homedir(),install:p.install,storageDir:credentialDir});
319
+ console.log(JSON.stringify({...out,runMode:'foreground',autostart:false,
320
+ next:child?'dc-worker-starting':'foreground-running'}));
321
+ if(!child){
322
+ const abort=new AbortController();
323
+ process.once('SIGINT',()=>abort.abort());process.once('SIGTERM',()=>abort.abort());
324
+ console.log(JSON.stringify(await devHeartbeatForeground({storageDir:credentialDir,signal:abort.signal})));
325
+ }
326
+ }else{
327
+ const service=configureDevHeartbeatService({mode,confirmLinger});
328
+ console.log(JSON.stringify({...out,runMode:mode,serviceEnabled:service.enabled,
329
+ serviceStarted:service.started,next:'dc-worker-connecting'}));
330
+ }
331
+ }
332
+ else if(action==='dev-mode'&&process.argv.length>=4&&process.argv.length<=5){
333
+ const mode=process.argv[3],confirmed=process.argv[4]==='--confirm-linger';
334
+ if(!['manual','login','boot'].includes(mode)||
335
+ (process.argv.length===5&&!confirmed)||(confirmed&&mode!=='boot'))deny('DEVICE_DEV_SERVICE_DENIED');
336
+ console.log(JSON.stringify(configureDevHeartbeatService({mode,confirmLinger:confirmed})));
337
+ }
338
+ else if(action==='dev-run-once'&&process.argv.length===3){
339
+ const p=paths();const storageDir=join(p.base,'dev-credentials');
340
+ const child=startOfficialWorker({home:homedir(),install:p.install,storageDir});
341
+ console.log(JSON.stringify({runMode:'foreground',autostart:false,registeredPreserved:true,
342
+ next:child?'dc-worker-starting':'heartbeat-running'}));
343
+ if(!child){
344
+ const abort=new AbortController();
345
+ process.once('SIGINT',()=>abort.abort());process.once('SIGTERM',()=>abort.abort());
346
+ console.log(JSON.stringify(await devHeartbeatForeground({storageDir,signal:abort.signal})));
347
+ }
348
+ }
349
+ else if(['dev-start','dev-stop','dev-status','dev-autostart-enable','dev-autostart-disable'].includes(action)&&process.argv.length===3){
350
+ const actions={'dev-start':'start','dev-stop':'stop','dev-status':'status','dev-autostart-enable':'autostart-enable','dev-autostart-disable':'autostart-disable'};
351
+ console.log(JSON.stringify(controlDevHeartbeatService({action:actions[action]})));
352
+ }
353
+ else if(action==='dev-service-uninstall'&&process.argv.length===3)console.log(JSON.stringify(uninstallDevHeartbeatService()));
354
+ else if(action==='install'&&process.argv.length===3){
355
+ let wsl=false;
356
+ if(platform()==='linux'){try{wsl=/microsoft|wsl/i.test(readFileSync('/proc/version','utf8'));}catch{}}
357
+ // The non-executing preflight is a necessary gate for installation too.
358
+ // Its own JSON output is not proof of an installed or connected Agent.
359
+ installPreflight({os:platform(),arch:process.arch,nodeVersion:process.version,wsl});
360
+ console.log(JSON.stringify(platform()==='win32'?installWindowsNative({home:homedir(),localAppData:process.env.LOCALAPPDATA,packageRoot,version:pkg.version}):install(paths())));
361
+ }
362
+ else if(action==='status'&&process.argv.length===3){
363
+ if(platform()==='win32'){
364
+ const home=homedir();
365
+ const layout=windowsInstallLayout({home,localAppData:process.env.LOCALAPPDATA});
366
+ const state=statusWindowsNative({home,localAppData:process.env.LOCALAPPDATA,version:pkg.version});
367
+ const registered=devOfficialRegistration({storageDir:layout.credentials});
368
+ console.log(JSON.stringify({...state,registered:!!registered,deviceId:registered?.deviceId,
369
+ connected:false,dcReady:false,heartbeatState:registered?'unverified':'not-registered'}));
370
+ }else console.log(JSON.stringify(await status(paths())));
371
+ }
372
+ else if(action==='uninstall'&&process.argv.length===3)console.log(JSON.stringify(platform()==='win32'?uninstallWindowsNative({home:homedir(),localAppData:process.env.LOCALAPPDATA,version:pkg.version}):uninstall(paths())));
373
+ 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})));
374
+ 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)})));
375
+ 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})));
376
+ else if(['update','register'].includes(action)){
377
+ console.error('DEVICE_ONBOARDING_NOT_READY');
378
+ process.exitCode=2;
379
+ }else{console.error('Usage: remoteshell-device version|install|setup https://host/dev/ [foreground|manual|login|boot --confirm-linger]|dev-run-once|dev-mode manual|login|boot [--confirm-linger]|dev-start|dev-stop|dev-status|dev-autostart-enable|dev-autostart-disable|status|dev-service-uninstall|uninstall|dev-check https://host/dev/|dev-enroll https://host/dev/ ENROLLMENT_ID < capability-file|dev-heartbeat|dev-heartbeat-once|dev-agent-run GATEWAY_URL ROOT_ID ABSOLUTE_ROOT');process.exitCode=2;}
380
+ }catch(e){
381
+ const codes=new Set(['DEVICE_INSTALL_DENIED','DEVICE_INSTALL_MANIFEST_DENIED','DEVICE_INSTALL_TRUST_ANCHOR_INVALID','DEVICE_INSTALL_TRUST_ANCHOR_MISSING','DEVICE_INSTALL_SIGNATURE_DENIED','DEVICE_INSTALL_CHECKSUM_DENIED','DEVICE_INSTALL_ARTIFACT_DENIED','DEVICE_INSTALL_VERSION_DENIED','DEVICE_INSTALL_VERSION_REVIEW_REQUIRED','DEVICE_INSTALL_DOWNGRADE_DENIED','DEVICE_INSTALL_DOWNLOAD_DENIED','DEVICE_INSTALL_DOWNLOAD_TIMEOUT','DEVICE_INSTALL_DOWNLOAD_TOO_LARGE','DEVICE_INSTALL_STATE_DENIED','DEVICE_PLATFORM_UNSUPPORTED','DEVICE_INSTALL_OS_UNSUPPORTED','DEVICE_INSTALL_WSL_BETA_EXCLUDED','DEVICE_INSTALL_NODE_UNSUPPORTED','DEVICE_ALREADY_INSTALLED','DEVICE_DEPENDENCY_INVALID','DEVICE_INSTALL_DEPENDENCY_FAILED','DEVICE_INSTALL_PACKAGE_FAILED','DEVICE_LIFECYCLE_DENIED','DEVICE_WINDOWS_LIFECYCLE_DENIED','DEVICE_WINDOWS_WORKER_NOT_READY','DEVICE_WINDOWS_LAYOUT_DENIED','DEVICE_WINDOWS_PRIVATE_STORE_DENIED','DEVICE_ALREADY_REGISTERED','DEVICE_WINDOWS_INSTALL_DENIED','DEVICE_ENROLLMENT_DENIED','DEVICE_DEV_PROBE_DENIED','DEVICE_DEV_AGENT_DENIED','DEVICE_DEV_ENROLLMENT_INPUT_DENIED','DEVICE_UNIT_MUST_BE_REMOVED_FIRST','DEVICE_PAIRING_DENIED','DEVICE_REREGISTRATION_CONFIRM_REQUIRED','DEVICE_REREGISTRATION_CANCELLED','DEVICE_DEV_CREDENTIAL_REVOKED','DEVICE_DEV_SERVICE_DENIED','L2_DEV_CREDENTIAL_DENIED','DEVICE_DIRECT_PLATFORM_DENIED','DEVICE_DIRECT_LEGACY_INSTALLED','DEVICE_DIRECT_OWNER_DENIED','DEVICE_DIRECT_LOCK_DENIED','DEVICE_DIRECT_ALREADY_RUNNING','DEVICE_DIRECT_STALE_LOCK','DEVICE_DIRECT_REGISTRATION_REQUIRED','DEVICE_DIRECT_PACKAGE_INVALID','DEVICE_DIRECT_EXISTING_SERVICE','DEVICE_DIRECT_SERVICE_UNVERIFIED','DEVICE_DIRECT_AUTOSTART_DENIED']);
382
+ console.error(codes.has(e.message)?e.message:'DEVICE_INSTALL_DENIED');
383
+ process.exitCode=1;
384
+ }
@@ -0,0 +1,150 @@
1
+ // #327 S1: direct public-npx runtime. Never copies or installs the package.
2
+ import {existsSync,mkdirSync,openSync,closeSync,readFileSync,rmSync,writeFileSync,lstatSync} from 'node:fs';
3
+ import {join,resolve} from 'node:path';
4
+ import {randomUUID} from 'node:crypto';
5
+ import {spawnSync} from 'node:child_process';
6
+ import {homedir,platform} from 'node:os';
7
+ import {devOfficialRegistration} from './dev-agent-client.mjs';
8
+ import {devPairDevice} from './dev-pairing-client.mjs';
9
+ import {ensureWindowsPrivateStore,sealWindowsPrivateFile} from './windows-private-store.mjs';
10
+ import {windowsInstallLayout} from './windows-install-layout.mjs';
11
+ import {inspectWindowsCredentialAcl} from './windows-credential-boundary.mjs';
12
+ import {runDevAgentWorker} from './dev-agent-runner.mjs';
13
+ const FAIL=code=>{throw Error(code);};
14
+ export const DIRECT_DEV_URL='https://ailab-remoteshell.duckdns.org/dev/';
15
+ const GATEWAY='https://ailab-remoteshell.duckdns.org/gateway/v1/';
16
+ export function directPaths({home=homedir(),os=platform(),localAppData=process.env.LOCALAPPDATA}={}){
17
+ if(os==='win32'){
18
+ const layout=windowsInstallLayout({home,localAppData});
19
+ return {home,base:layout.base,storageDir:layout.credentials,legacyInstall:layout.install,os};
20
+ }
21
+ if(os!=='linux'||!home.startsWith('/')||resolve(home)!==home)FAIL('DEVICE_DIRECT_PLATFORM_DENIED');
22
+ const base=join(home,'.local/share/remoteshell-device');
23
+ return {home,base,storageDir:join(base,'dev-credentials'),legacyInstall:join(base,'install'),os};
24
+ }
25
+ export function requireNoLegacyInstall(p,{exists=existsSync,run=spawnSync}={}){
26
+ // Do not overlap any preexisting install, service, or user autostart.
27
+ // Presence of an install directory itself is sufficient to fail closed:
28
+ // an incomplete install is not automatically eligible for migration.
29
+ if(exists(p.legacyInstall))FAIL('DEVICE_DIRECT_LEGACY_INSTALLED');
30
+ if(p.os==='linux'){
31
+ if(exists(join(p.home,'.config/systemd/user/remoteshell-device-dev-heartbeat.service'))||
32
+ exists(join(p.home,'.config/systemd/user/remoteshell-device.service')))
33
+ FAIL('DEVICE_DIRECT_EXISTING_SERVICE');
34
+ }else if(p.os==='win32'){
35
+ const result=run('schtasks.exe',['/Query','/TN','RemoteShell Device Agent (User)'],{
36
+ shell:false,windowsHide:true,encoding:'utf8',timeout:10000,maxBuffer:8192,stdio:'pipe'});
37
+ // A missing task has a nonzero exit. All other query failures are
38
+ // deliberately treated as conflicts rather than claiming safe isolation.
39
+ if(result.error||result.signal)FAIL('DEVICE_DIRECT_SERVICE_UNVERIFIED');
40
+ if(result.status===0)FAIL('DEVICE_DIRECT_EXISTING_SERVICE');
41
+ if(result.status!==1)FAIL('DEVICE_DIRECT_SERVICE_UNVERIFIED');
42
+ }
43
+ }
44
+
45
+ function privateLockDir(p){
46
+ // Place run state alongside the already user-private credential, not in
47
+ // a newly created Windows folder with inherited broad ACL.
48
+ if(p.os==='win32'){
49
+ ensureWindowsPrivateStore(p.storageDir,{home:p.home});
50
+ }else{
51
+ const st=lstatSync(p.storageDir);
52
+ if(!st.isDirectory()||st.isSymbolicLink()||st.uid!==process.getuid?.()||
53
+ (st.mode&0o777)!==0o700)FAIL('DEVICE_DIRECT_OWNER_DENIED');
54
+ }
55
+ return p.storageDir;
56
+ }
57
+ export function acquireDirectLock(p,{pid=process.pid,alive=id=>{
58
+ try{process.kill(id,0);return true;}catch(e){return e?.code==='EPERM';}
59
+ }}={}){
60
+ const dir=privateLockDir(p),lock=join(dir,'direct-run.lock'),reap=join(dir,'direct-run.reap.lock');
61
+ const nonce=randomUUID();
62
+ const create=()=>{
63
+ let fd;
64
+ try{
65
+ fd=openSync(lock,'wx',0o600);
66
+ writeFileSync(fd,JSON.stringify({pid,created:Date.now(),nonce}));
67
+ closeSync(fd);fd=undefined;
68
+ if(p.os==='win32'){
69
+ try{sealWindowsPrivateFile(lock,{home:p.home});}
70
+ catch(e){rmSync(lock,{force:true});throw e;}
71
+ }
72
+ }catch(e){if(fd!==undefined)closeSync(fd);throw e;}
73
+ return ()=>{
74
+ try{
75
+ const info=JSON.parse(readFileSync(lock,'utf8'));
76
+ if(info.pid===pid&&info.nonce===nonce)rmSync(lock);
77
+ }catch{}
78
+ };
79
+ };
80
+ try{return create();}catch(e){
81
+ if(e.code!=='EEXIST')FAIL('DEVICE_DIRECT_LOCK_DENIED');
82
+ }
83
+ // Windows logoff/reboot and Linux systemd can kill the npm wrapper before
84
+ // its child gets an exit event. Reclaim only verified dead process locks.
85
+ // Windows requires NTFS SID/owner/DACL proof, Linux requires uid/mode proof.
86
+ if(p.os!=='linux'&&p.os!=='win32')FAIL('DEVICE_DIRECT_STALE_LOCK');
87
+ let snapshot,prior,bytes;
88
+ try{
89
+ snapshot=lstatSync(lock);
90
+ if(!snapshot.isFile()||snapshot.isSymbolicLink()||snapshot.size<1||snapshot.size>256)
91
+ FAIL('DEVICE_DIRECT_STALE_LOCK');
92
+ if(p.os==='linux'){
93
+ if(snapshot.uid!==process.getuid?.()||(snapshot.mode&0o777)!==0o600)
94
+ FAIL('DEVICE_DIRECT_STALE_LOCK');
95
+ }else inspectWindowsCredentialAcl({file:lock,home:p.home});
96
+ bytes=readFileSync(lock,'utf8');prior=JSON.parse(bytes);
97
+ if(!Number.isSafeInteger(prior?.pid)||prior.pid<=1)
98
+ FAIL('DEVICE_DIRECT_STALE_LOCK');
99
+ }catch{FAIL('DEVICE_DIRECT_STALE_LOCK');}
100
+ if(alive(prior.pid))FAIL('DEVICE_DIRECT_ALREADY_RUNNING');
101
+ let mutex;
102
+ try{mutex=openSync(reap,'wx',0o600);}catch{FAIL('DEVICE_DIRECT_STALE_LOCK');}
103
+ try{
104
+ const current=lstatSync(lock);
105
+ if(current.dev!==snapshot.dev||current.ino!==snapshot.ino||
106
+ !current.isFile()||readFileSync(lock,'utf8')!==bytes)
107
+ FAIL('DEVICE_DIRECT_STALE_LOCK');
108
+ if(alive(prior.pid))FAIL('DEVICE_DIRECT_ALREADY_RUNNING');
109
+ rmSync(lock);
110
+ }catch(e){
111
+ if(e.message==='DEVICE_DIRECT_ALREADY_RUNNING')throw e;
112
+ FAIL('DEVICE_DIRECT_STALE_LOCK');
113
+ }finally{
114
+ closeSync(mutex);
115
+ rmSync(reap,{force:true});
116
+ }
117
+ try{return create();}catch(e){
118
+ if(e.code==='EEXIST')FAIL('DEVICE_DIRECT_ALREADY_RUNNING');
119
+ FAIL('DEVICE_DIRECT_LOCK_DENIED');
120
+ }
121
+ }
122
+ export async function directRegister(p,{pair=devPairDevice,onApprove=url=>console.log(JSON.stringify({next:'approve-device-in-browser',approval_url:url,ownerApprovalRequired:true}))}={}){
123
+ requireNoLegacyInstall(p);
124
+ if(p.os==='win32')ensureWindowsPrivateStore(p.storageDir,{home:p.home});
125
+ const existing=devOfficialRegistration({storageDir:p.storageDir});
126
+ if(existing)return {registered:true,deviceId:existing.deviceId,reused:true,credentialsPreserved:true};
127
+ const result=await pair({base:DIRECT_DEV_URL,storageDir:p.storageDir,onApprove});
128
+ return {...result,reused:false};
129
+ }
130
+ export async function directRun(p,{packageRoot,runWorker=runDevAgentWorker,guard=requireNoLegacyInstall}={}){
131
+ guard(p);
132
+ const registration=devOfficialRegistration({storageDir:p.storageDir});
133
+ if(!registration)FAIL('DEVICE_DIRECT_REGISTRATION_REQUIRED');
134
+ const mainFile=join(packageRoot,'src/device-agent/main.mjs');
135
+ if(!existsSync(mainFile))FAIL('DEVICE_DIRECT_PACKAGE_INVALID');
136
+ const release=acquireDirectLock(p);
137
+ // Also clean on normal process exit when the npm parent receives SIGTERM.
138
+ process.once('exit',release);
139
+ try{
140
+ const child=runWorker({gatewayUrl:GATEWAY,credentialFile:join(p.storageDir,'device.json'),
141
+ rootId:registration.deviceId,rootPath:p.home,home:p.home,mainFile});
142
+ return await new Promise((ok,fail)=>{
143
+ const onInt=()=>child.kill('SIGINT'),onTerm=()=>child.kill('SIGTERM');
144
+ const cleanup=()=>{process.removeListener('SIGINT',onInt);process.removeListener('SIGTERM',onTerm);};
145
+ child.once('error',error=>{cleanup();fail(error);});
146
+ child.once('exit',(code,signal)=>{cleanup();ok({exitCode:signal?1:(code??1),signal:signal||null});});
147
+ process.once('SIGINT',onInt);process.once('SIGTERM',onTerm);
148
+ });
149
+ }finally{process.removeListener('exit',release);release();}
150
+ }