@remoteshell/device 0.1.0-beta.1 → 0.1.0-beta.11
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/LICENSE +26 -0
- package/NOTICE +20 -0
- package/bin/dev-agent-client.mjs +228 -0
- package/bin/dev-agent-runner.mjs +60 -0
- package/bin/dev-api-client.mjs +31 -0
- package/bin/dev-auto-worker.mjs +25 -0
- package/bin/dev-browser-open.mjs +12 -0
- package/bin/dev-dogfood-read.mjs +3 -0
- package/bin/dev-heartbeat-service.mjs +77 -0
- package/bin/dev-pairing-client.mjs +63 -0
- package/bin/dev-secrets.mjs +33 -0
- package/bin/dev-setup-recovery.mjs +34 -0
- package/bin/dev-signer-pin.mjs +22 -0
- package/bin/device.mjs +254 -9
- package/bin/direct-npx-runtime.mjs +156 -0
- package/bin/install-acquire.mjs +89 -0
- package/bin/install-integrity.mjs +74 -0
- package/bin/install-plan.mjs +43 -0
- package/bin/native-path-contract.mjs +23 -0
- package/bin/remoteshell-device-install.cmd +17 -0
- package/bin/remoteshell-device-install.ps1 +17 -0
- package/bin/remoteshell-device-install.sh +15 -0
- package/bin/remoteshell-device-preflight.cmd +10 -0
- package/bin/remoteshell-device-preflight.ps1 +10 -0
- package/bin/remoteshell-easy-diagnose.ps1 +32 -0
- package/bin/remoteshell-easy-install.ps1 +292 -0
- package/bin/remoteshell-easy-install.sh +71 -0
- package/bin/remoteshell-easy-uninstall.ps1 +128 -0
- package/bin/windows-acl-wmi-client.mjs +50 -0
- package/bin/windows-acl-wmi.js +43 -0
- package/bin/windows-credential-boundary.mjs +113 -0
- package/bin/windows-direct-autostart-runner.mjs +50 -0
- package/bin/windows-direct-autostart.mjs +110 -0
- package/bin/windows-install-layout.mjs +28 -0
- package/bin/windows-native-installer.mjs +91 -0
- package/bin/windows-private-store.mjs +176 -0
- package/bin/windows-user-lifecycle.mjs +34 -0
- package/npm-shrinkwrap.json +8591 -0
- package/package.json +14 -5
- package/shared/lib/bounded-search-contract.mjs +5 -0
- package/shared/lib/dc-generic-policy.mjs +102 -0
- package/shared/lib/dc-relay-contract.mjs +42 -0
- package/shared/lib/dc-tool-catalog.mjs +67 -0
- package/shared/lib/dev-dc-relay-contract.mjs +20 -0
- package/shared/lib/dev-paged-output.mjs +32 -0
- package/shared/lib/dev-root-exclusions.mjs +56 -0
- package/{src/common → shared/lib}/synthetic-write-policy.mjs +0 -1
- package/src/config/l2-dev-oci-credential.mjs +39 -0
- package/src/config/p2-private-credential.mjs +15 -0
- package/src/connection/dev-dogfood-processes.mjs +25 -0
- package/src/connection/dev-dogfood-read.mjs +64 -0
- package/src/connection/dev-dogfood-task.mjs +113 -0
- package/src/connection/dev-dogfood-write.mjs +62 -0
- package/src/connection/dev-file-task.mjs +119 -0
- package/src/connection/dev-r4-file-task.mjs +56 -0
- package/src/connection/dev-read-tools.mjs +134 -0
- package/src/connection/dev-root-scopes.mjs +82 -0
- package/src/{device-agent → core}/c1-supervisor.mjs +9 -7
- package/src/{device-agent → core}/c1-worker.mjs +7 -7
- package/src/dc/dc-access-readiness.mjs +31 -0
- package/src/dc/dev-dc-relay.mjs +47 -0
- package/src/device-agent/main.mjs +1 -230
- package/src/gateway-keepalive.mjs +73 -0
- package/src/main.mjs +436 -0
- package/src/{common → policy}/bounded-search-adapter.mjs +2 -3
- package/src/{common → policy}/isolated-read-adapter.mjs +1 -1
- package/src/{common → policy}/isolated-read-mount.mjs +1 -1
- package/src/{common → policy}/synthetic-auxiliary-adapter.mjs +1 -1
- package/src/{common → policy}/synthetic-file-adapter.mjs +1 -1
- package/src/{common → policy}/synthetic-file-transaction.mjs +1 -1
- package/src/{common → policy}/synthetic-write-adapter.mjs +2 -3
- /package/{src/common → shared/lib}/bounded-search-policy.mjs +0 -0
- /package/{src/common → shared/lib}/config.mjs +0 -0
- /package/{src/common → shared/lib}/contracts.mjs +0 -0
- /package/{src/common → shared/lib}/errors.mjs +0 -0
- /package/{src/common → shared/lib}/events.mjs +0 -0
- /package/{src/common → shared/lib}/execution-policy.mjs +0 -0
- /package/{src/common → shared/lib}/isolated-read-boundary.mjs +0 -0
- /package/{src/common → shared/lib}/isolated-read-policy.mjs +0 -0
- /package/{src/common → shared/lib}/lifecycle-events.mjs +0 -0
- /package/{src/common → shared/lib}/runtime-timing.mjs +0 -0
- /package/{src/common → shared/lib}/synthetic-auxiliary-policy.mjs +0 -0
- /package/{src/common → shared/lib}/tool-registry.mjs +0 -0
- /package/src/{device-agent → core}/c1-dc-transport.mjs +0 -0
- /package/src/{device-agent → core}/c1-startup.mjs +0 -0
- /package/src/{device-agent → core}/fixture.txt +0 -0
- /package/src/{common → policy}/synthetic-write-mount.mjs +0 -0
- /package/src/{common → policy}/verified-bounded-search.mjs +0 -0
- /package/src/{common → policy}/verified-isolated-read.mjs +0 -0
- /package/src/{common → policy}/verified-synthetic-write.mjs +0 -0
|
@@ -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
CHANGED
|
@@ -8,8 +8,27 @@ import {fileURLToPath} from 'node:url';
|
|
|
8
8
|
import {randomUUID} from 'node:crypto';
|
|
9
9
|
import {spawnSync} from 'node:child_process';
|
|
10
10
|
import {createRequire} from 'node:module';
|
|
11
|
+
import {createInterface} from 'node:readline/promises';
|
|
11
12
|
import {foreground,installUserUnit,userService,gatewayStatus} from './lifecycle.mjs';
|
|
12
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';
|
|
13
32
|
const require=createRequire(import.meta.url);
|
|
14
33
|
const pkg=require('../package.json');
|
|
15
34
|
const packageRoot=resolve(dirname(fileURLToPath(import.meta.url)),'..');
|
|
@@ -47,9 +66,18 @@ function checkReceipt(root){
|
|
|
47
66
|
}
|
|
48
67
|
const installed=JSON.parse(readFileSync(runtimePkg,'utf8'));
|
|
49
68
|
const dc=JSON.parse(readFileSync(dcPkg,'utf8'));
|
|
50
|
-
if(installed.name!==pkg.name||installed.version!==pkg.version||dc.version!=='0.3.
|
|
69
|
+
if(installed.name!==pkg.name||installed.version!==pkg.version||dc.version!=='0.3.1')deny('DEVICE_DEPENDENCY_INVALID');
|
|
51
70
|
return data;
|
|
52
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
|
+
}
|
|
53
81
|
async function status(p){
|
|
54
82
|
if(!existsSync(p.base))return {installed:false,registered:false,connected:false};
|
|
55
83
|
checkDir(p.base,{privateMode:true});
|
|
@@ -68,8 +96,18 @@ async function status(p){
|
|
|
68
96
|
}
|
|
69
97
|
const unit=join(homedir(),'.config/systemd/user/remoteshell-device.service');
|
|
70
98
|
const service=existsSync(unit)?userService({action:'status'}):{unitInstalled:false,active:false};
|
|
71
|
-
|
|
72
|
-
|
|
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};
|
|
73
111
|
}
|
|
74
112
|
function install(p){
|
|
75
113
|
if(platform()!=='linux')deny('DEVICE_PLATFORM_UNSUPPORTED');
|
|
@@ -115,25 +153,232 @@ function uninstall(p){
|
|
|
115
153
|
checkReceipt(p.install);
|
|
116
154
|
const unit=join(homedir(),'.config/systemd/user/remoteshell-device.service');
|
|
117
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');
|
|
118
158
|
// No service was installed by this CLI version. No other product folder,
|
|
119
159
|
// credentials, existing P4 unit or release is touched.
|
|
120
160
|
rmSync(p.install,{recursive:true,force:false});
|
|
121
161
|
return {removed:true,credentialsPreserved:true,systemdUntouched:true};
|
|
122
162
|
}
|
|
123
163
|
try{
|
|
124
|
-
if(action==='
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
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())));
|
|
128
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})));
|
|
129
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)})));
|
|
130
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})));
|
|
131
376
|
else if(['update','register'].includes(action)){
|
|
132
377
|
console.error('DEVICE_ONBOARDING_NOT_READY');
|
|
133
378
|
process.exitCode=2;
|
|
134
|
-
}else{console.error('Usage: remoteshell-device version|install|status|uninstall');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;}
|
|
135
380
|
}catch(e){
|
|
136
|
-
|
|
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_SERVICE_TIMEOUT','DEVICE_DIRECT_AUTOSTART_DENIED']);
|
|
137
382
|
console.error(codes.has(e.message)?e.message:'DEVICE_INSTALL_DENIED');
|
|
138
383
|
process.exitCode=1;
|
|
139
384
|
}
|
|
@@ -0,0 +1,156 @@
|
|
|
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,win32} 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
|
+
// During a Windows interactive login the Task Scheduler service may be
|
|
36
|
+
// occupied restoring other sessions. Query its absolute native binary and
|
|
37
|
+
// allow a bounded warm-up, without skipping the safety check on failure.
|
|
38
|
+
const systemRoot=process.env.SystemRoot||'C:\\Windows';
|
|
39
|
+
const taskTool=win32.join(systemRoot,'System32','schtasks.exe');
|
|
40
|
+
const result=run(taskTool,['/Query','/TN','RemoteShell Device Agent (User)'],{
|
|
41
|
+
shell:false,windowsHide:true,encoding:'utf8',timeout:30000,maxBuffer:8192,stdio:'pipe'});
|
|
42
|
+
// A missing task has a nonzero exit. All other query failures are
|
|
43
|
+
// deliberately treated as conflicts rather than claiming safe isolation.
|
|
44
|
+
if(result.error?.code==='ETIMEDOUT')FAIL('DEVICE_DIRECT_SERVICE_TIMEOUT');
|
|
45
|
+
if(result.error||result.signal)FAIL('DEVICE_DIRECT_SERVICE_UNVERIFIED');
|
|
46
|
+
if(result.status===0)FAIL('DEVICE_DIRECT_EXISTING_SERVICE');
|
|
47
|
+
if(result.status!==1)FAIL('DEVICE_DIRECT_SERVICE_UNVERIFIED');
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function privateLockDir(p){
|
|
52
|
+
// Place run state alongside the already user-private credential, not in
|
|
53
|
+
// a newly created Windows folder with inherited broad ACL.
|
|
54
|
+
if(p.os==='win32'){
|
|
55
|
+
ensureWindowsPrivateStore(p.storageDir,{home:p.home});
|
|
56
|
+
}else{
|
|
57
|
+
const st=lstatSync(p.storageDir);
|
|
58
|
+
if(!st.isDirectory()||st.isSymbolicLink()||st.uid!==process.getuid?.()||
|
|
59
|
+
(st.mode&0o777)!==0o700)FAIL('DEVICE_DIRECT_OWNER_DENIED');
|
|
60
|
+
}
|
|
61
|
+
return p.storageDir;
|
|
62
|
+
}
|
|
63
|
+
export function acquireDirectLock(p,{pid=process.pid,alive=id=>{
|
|
64
|
+
try{process.kill(id,0);return true;}catch(e){return e?.code==='EPERM';}
|
|
65
|
+
}}={}){
|
|
66
|
+
const dir=privateLockDir(p),lock=join(dir,'direct-run.lock'),reap=join(dir,'direct-run.reap.lock');
|
|
67
|
+
const nonce=randomUUID();
|
|
68
|
+
const create=()=>{
|
|
69
|
+
let fd;
|
|
70
|
+
try{
|
|
71
|
+
fd=openSync(lock,'wx',0o600);
|
|
72
|
+
writeFileSync(fd,JSON.stringify({pid,created:Date.now(),nonce}));
|
|
73
|
+
closeSync(fd);fd=undefined;
|
|
74
|
+
if(p.os==='win32'){
|
|
75
|
+
try{sealWindowsPrivateFile(lock,{home:p.home});}
|
|
76
|
+
catch(e){rmSync(lock,{force:true});throw e;}
|
|
77
|
+
}
|
|
78
|
+
}catch(e){if(fd!==undefined)closeSync(fd);throw e;}
|
|
79
|
+
return ()=>{
|
|
80
|
+
try{
|
|
81
|
+
const info=JSON.parse(readFileSync(lock,'utf8'));
|
|
82
|
+
if(info.pid===pid&&info.nonce===nonce)rmSync(lock);
|
|
83
|
+
}catch{}
|
|
84
|
+
};
|
|
85
|
+
};
|
|
86
|
+
try{return create();}catch(e){
|
|
87
|
+
if(e.code!=='EEXIST')FAIL('DEVICE_DIRECT_LOCK_DENIED');
|
|
88
|
+
}
|
|
89
|
+
// Windows logoff/reboot and Linux systemd can kill the npm wrapper before
|
|
90
|
+
// its child gets an exit event. Reclaim only verified dead process locks.
|
|
91
|
+
// Windows requires NTFS SID/owner/DACL proof, Linux requires uid/mode proof.
|
|
92
|
+
if(p.os!=='linux'&&p.os!=='win32')FAIL('DEVICE_DIRECT_STALE_LOCK');
|
|
93
|
+
let snapshot,prior,bytes;
|
|
94
|
+
try{
|
|
95
|
+
snapshot=lstatSync(lock);
|
|
96
|
+
if(!snapshot.isFile()||snapshot.isSymbolicLink()||snapshot.size<1||snapshot.size>256)
|
|
97
|
+
FAIL('DEVICE_DIRECT_STALE_LOCK');
|
|
98
|
+
if(p.os==='linux'){
|
|
99
|
+
if(snapshot.uid!==process.getuid?.()||(snapshot.mode&0o777)!==0o600)
|
|
100
|
+
FAIL('DEVICE_DIRECT_STALE_LOCK');
|
|
101
|
+
}else inspectWindowsCredentialAcl({file:lock,home:p.home});
|
|
102
|
+
bytes=readFileSync(lock,'utf8');prior=JSON.parse(bytes);
|
|
103
|
+
if(!Number.isSafeInteger(prior?.pid)||prior.pid<=1)
|
|
104
|
+
FAIL('DEVICE_DIRECT_STALE_LOCK');
|
|
105
|
+
}catch{FAIL('DEVICE_DIRECT_STALE_LOCK');}
|
|
106
|
+
if(alive(prior.pid))FAIL('DEVICE_DIRECT_ALREADY_RUNNING');
|
|
107
|
+
let mutex;
|
|
108
|
+
try{mutex=openSync(reap,'wx',0o600);}catch{FAIL('DEVICE_DIRECT_STALE_LOCK');}
|
|
109
|
+
try{
|
|
110
|
+
const current=lstatSync(lock);
|
|
111
|
+
if(current.dev!==snapshot.dev||current.ino!==snapshot.ino||
|
|
112
|
+
!current.isFile()||readFileSync(lock,'utf8')!==bytes)
|
|
113
|
+
FAIL('DEVICE_DIRECT_STALE_LOCK');
|
|
114
|
+
if(alive(prior.pid))FAIL('DEVICE_DIRECT_ALREADY_RUNNING');
|
|
115
|
+
rmSync(lock);
|
|
116
|
+
}catch(e){
|
|
117
|
+
if(e.message==='DEVICE_DIRECT_ALREADY_RUNNING')throw e;
|
|
118
|
+
FAIL('DEVICE_DIRECT_STALE_LOCK');
|
|
119
|
+
}finally{
|
|
120
|
+
closeSync(mutex);
|
|
121
|
+
rmSync(reap,{force:true});
|
|
122
|
+
}
|
|
123
|
+
try{return create();}catch(e){
|
|
124
|
+
if(e.code==='EEXIST')FAIL('DEVICE_DIRECT_ALREADY_RUNNING');
|
|
125
|
+
FAIL('DEVICE_DIRECT_LOCK_DENIED');
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
export async function directRegister(p,{pair=devPairDevice,onApprove=url=>console.log(JSON.stringify({next:'approve-device-in-browser',approval_url:url,ownerApprovalRequired:true}))}={}){
|
|
129
|
+
requireNoLegacyInstall(p);
|
|
130
|
+
if(p.os==='win32')ensureWindowsPrivateStore(p.storageDir,{home:p.home});
|
|
131
|
+
const existing=devOfficialRegistration({storageDir:p.storageDir});
|
|
132
|
+
if(existing)return {registered:true,deviceId:existing.deviceId,reused:true,credentialsPreserved:true};
|
|
133
|
+
const result=await pair({base:DIRECT_DEV_URL,storageDir:p.storageDir,onApprove});
|
|
134
|
+
return {...result,reused:false};
|
|
135
|
+
}
|
|
136
|
+
export async function directRun(p,{packageRoot,runWorker=runDevAgentWorker,guard=requireNoLegacyInstall}={}){
|
|
137
|
+
guard(p);
|
|
138
|
+
const registration=devOfficialRegistration({storageDir:p.storageDir});
|
|
139
|
+
if(!registration)FAIL('DEVICE_DIRECT_REGISTRATION_REQUIRED');
|
|
140
|
+
const mainFile=join(packageRoot,'src/device-agent/main.mjs');
|
|
141
|
+
if(!existsSync(mainFile))FAIL('DEVICE_DIRECT_PACKAGE_INVALID');
|
|
142
|
+
const release=acquireDirectLock(p);
|
|
143
|
+
// Also clean on normal process exit when the npm parent receives SIGTERM.
|
|
144
|
+
process.once('exit',release);
|
|
145
|
+
try{
|
|
146
|
+
const child=runWorker({gatewayUrl:GATEWAY,credentialFile:join(p.storageDir,'device.json'),
|
|
147
|
+
rootId:registration.deviceId,rootPath:p.home,home:p.home,mainFile});
|
|
148
|
+
return await new Promise((ok,fail)=>{
|
|
149
|
+
const onInt=()=>child.kill('SIGINT'),onTerm=()=>child.kill('SIGTERM');
|
|
150
|
+
const cleanup=()=>{process.removeListener('SIGINT',onInt);process.removeListener('SIGTERM',onTerm);};
|
|
151
|
+
child.once('error',error=>{cleanup();fail(error);});
|
|
152
|
+
child.once('exit',(code,signal)=>{cleanup();ok({exitCode:signal?1:(code??1),signal:signal||null});});
|
|
153
|
+
process.once('SIGINT',onInt);process.once('SIGTERM',onTerm);
|
|
154
|
+
});
|
|
155
|
+
}finally{process.removeListener('exit',release);release();}
|
|
156
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// #310 Private DEV: fetch only, verify before any installer executes. No new
|
|
2
|
+
// trust authority, shell execution, service mutation or token access.
|
|
3
|
+
import {request as httpsRequest} from 'node:https';
|
|
4
|
+
import {createWriteStream,readFileSync,lstatSync,rmSync,mkdtempSync} from 'node:fs';
|
|
5
|
+
import {tmpdir} from 'node:os';
|
|
6
|
+
import {join,basename,resolve} from 'node:path';
|
|
7
|
+
import {pipeline} from 'node:stream/promises';
|
|
8
|
+
import {Transform} from 'node:stream';
|
|
9
|
+
import {planVerifiedInstall} from './install-plan.mjs';
|
|
10
|
+
import {loadPinnedDevSigner} from './dev-signer-pin.mjs';
|
|
11
|
+
const MAX_MANIFEST=8192;
|
|
12
|
+
const MAX_ARTIFACT=128*1024*1024;
|
|
13
|
+
const deny=(code='DEVICE_INSTALL_DOWNLOAD_DENIED')=>{throw Error(code);};
|
|
14
|
+
function checkUrl(value,origin){
|
|
15
|
+
// Check raw URL before URL() normalizes traversal segments away.
|
|
16
|
+
if(typeof value!=='string'||/\/\.\.(?:\/|%2f|$)/i.test(value)||/%2e|%2f|%5c|\\/i.test(value))deny();
|
|
17
|
+
let url;
|
|
18
|
+
try{url=new URL(value);}catch{deny();}
|
|
19
|
+
if(url.protocol!=='https:'||url.username||url.password||url.hash||url.port&&url.port!=='443'||
|
|
20
|
+
url.hostname!==origin.hostname||url.origin!==origin.origin||url.search)deny();
|
|
21
|
+
if(!/^\/[A-Za-z0-9._/-]{1,200}$/.test(url.pathname)||url.pathname.includes('..')||url.pathname.includes('//'))deny();
|
|
22
|
+
return url;
|
|
23
|
+
}
|
|
24
|
+
async function getHttps(url,{requestImpl=httpsRequest,bytesMax}={}){
|
|
25
|
+
const response=await new Promise((ok,no)=>{
|
|
26
|
+
const req=requestImpl(url,{method:'GET',headers:{accept:'application/octet-stream'},timeout:15000},ok);
|
|
27
|
+
req.once('error',no);req.once('timeout',()=>req.destroy(Error('DEVICE_INSTALL_DOWNLOAD_TIMEOUT')));req.end();
|
|
28
|
+
});
|
|
29
|
+
if(response.statusCode!==200||response.headers?.location||
|
|
30
|
+
(response.headers?.['content-length']!==undefined&&
|
|
31
|
+
(!/^\d+$/.test(String(response.headers['content-length']))||Number(response.headers['content-length'])>bytesMax))){
|
|
32
|
+
response.destroy?.();deny();
|
|
33
|
+
}
|
|
34
|
+
return response;
|
|
35
|
+
}
|
|
36
|
+
async function consumeBounded(stream,limit){
|
|
37
|
+
let total=0;const chunks=[];
|
|
38
|
+
for await(const data of stream){
|
|
39
|
+
const b=Buffer.isBuffer(data)?data:Buffer.from(data);
|
|
40
|
+
total+=b.length;if(total>limit)deny('DEVICE_INSTALL_DOWNLOAD_TOO_LARGE');
|
|
41
|
+
chunks.push(b);
|
|
42
|
+
}
|
|
43
|
+
return Buffer.concat(chunks);
|
|
44
|
+
}
|
|
45
|
+
export async function acquireVerifiedDevArchive({manifestUrl,archiveUrl,publicKeyPath,
|
|
46
|
+
os,arch,nodeVersion,wsl=false,installedVersion=null,
|
|
47
|
+
consent=false,existingCredentials=false,existingService=false,
|
|
48
|
+
allowedOrigin,requestImpl=httpsRequest,stagingRoot=tmpdir(),loadSigner=loadPinnedDevSigner
|
|
49
|
+
}={}){
|
|
50
|
+
if(typeof allowedOrigin!=='string'||!/^https:\/\/[^/]+$/.test(allowedOrigin))deny();
|
|
51
|
+
const origin=new URL(allowedOrigin);
|
|
52
|
+
if(origin.username||origin.password||origin.hash||origin.search||origin.port&&origin.port!=='443')deny();
|
|
53
|
+
const manifestEndpoint=checkUrl(manifestUrl,origin);
|
|
54
|
+
const archiveEndpoint=checkUrl(archiveUrl,origin);
|
|
55
|
+
if(!manifestEndpoint.pathname.endsWith('.json')||!archiveEndpoint.pathname.endsWith('.tgz'))deny();
|
|
56
|
+
// Signer is pre-pinned in the installed program; server-controlled manifest
|
|
57
|
+
// cannot introduce a replacement trust key.
|
|
58
|
+
const trustedKeys=loadSigner({publicKeyPath});
|
|
59
|
+
const response=await getHttps(manifestEndpoint,{requestImpl,bytesMax:MAX_MANIFEST});
|
|
60
|
+
const raw=await consumeBounded(response,MAX_MANIFEST);
|
|
61
|
+
let manifest;try{manifest=JSON.parse(raw.toString('utf8'));}catch{deny('DEVICE_INSTALL_MANIFEST_DENIED');}
|
|
62
|
+
if(manifest?.signed_fields?.artifact!==basename(archiveEndpoint.pathname))deny('DEVICE_INSTALL_MANIFEST_DENIED');
|
|
63
|
+
const stat=lstatSync(stagingRoot);
|
|
64
|
+
if(!stat.isDirectory()||stat.isSymbolicLink())deny();
|
|
65
|
+
const stage=mkdtempSync(join(stagingRoot,'rs310-verified-'));
|
|
66
|
+
try{
|
|
67
|
+
const artifactPath=join(stage,basename(archiveEndpoint.pathname));
|
|
68
|
+
let count=0;
|
|
69
|
+
const bounded=new Transform({transform(chunk,_encoding,callback){
|
|
70
|
+
count+=chunk.length;
|
|
71
|
+
if(count>MAX_ARTIFACT){callback(Error('DEVICE_INSTALL_DOWNLOAD_TOO_LARGE'));return;}
|
|
72
|
+
callback(null,chunk);
|
|
73
|
+
}});
|
|
74
|
+
const archiveResponse=await getHttps(archiveEndpoint,{requestImpl,bytesMax:MAX_ARTIFACT});
|
|
75
|
+
await pipeline(archiveResponse,bounded,createWriteStream(artifactPath,{flags:'wx',mode:0o600}));
|
|
76
|
+
const decision=planVerifiedInstall({artifactPath,manifest,trustedKeys,os,arch,nodeVersion,wsl,
|
|
77
|
+
installedVersion,existingCredentials,existingService,consent});
|
|
78
|
+
return Object.freeze({...decision,archivePath:artifactPath,stagingDirectory:stage,
|
|
79
|
+
verifiedFromHttps:true,installerExecuted:false,cleanupRequired:true});
|
|
80
|
+
}catch(e){rmSync(stage,{recursive:true,force:true});throw e;}
|
|
81
|
+
}
|
|
82
|
+
export function cleanupVerifiedDevArchive({stagingDirectory,stagingRoot=tmpdir()}={}){
|
|
83
|
+
if(typeof stagingDirectory!=='string'||!stagingDirectory||
|
|
84
|
+
resolve(stagingDirectory)===resolve(stagingRoot)||
|
|
85
|
+
!resolve(stagingDirectory).startsWith(resolve(stagingRoot)+'/')||
|
|
86
|
+
!basename(stagingDirectory).startsWith('rs310-verified-'))deny();
|
|
87
|
+
rmSync(stagingDirectory,{recursive:true,force:true});
|
|
88
|
+
return {cleaned:true,installationPerformed:false};
|
|
89
|
+
}
|