@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,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,363 @@
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
+ const require=createRequire(import.meta.url);
31
+ const pkg=require('../package.json');
32
+ const packageRoot=resolve(dirname(fileURLToPath(import.meta.url)),'..');
33
+ const action=process.argv[2];
34
+ const deny=(code='DEVICE_INSTALL_DENIED')=>{throw Error(code);};
35
+ const currentUid=process.getuid?.();
36
+ function checkDir(path,{privateMode=false}={}){
37
+ const stat=lstatSync(path);
38
+ if(!stat.isDirectory()||stat.isSymbolicLink()||(currentUid!==undefined&&stat.uid!==currentUid)||(privateMode&&(stat.mode&0o777)!==0o700))deny();
39
+ }
40
+ function ensureDir(path,{privateMode=false}={}){
41
+ if(!existsSync(path))mkdirSync(path,{mode:0o700});
42
+ checkDir(path,{privateMode});
43
+ }
44
+ function paths(){
45
+ const home=homedir();
46
+ if(!home||!home.startsWith('/')||resolve(home)==='/')deny();
47
+ checkDir(home);
48
+ const local=join(home,'.local'),share=join(local,'share');
49
+ const base=join(share,'remoteshell-device');
50
+ return {local,share,base,install:join(base,'install')};
51
+ }
52
+ function checkReceipt(root){
53
+ const receiptPath=join(root,'receipt.json');
54
+ if(!existsSync(receiptPath))deny();
55
+ const st=lstatSync(receiptPath);
56
+ if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o777)!==0o600||(currentUid!==undefined&&st.uid!==currentUid)||st.size>2048)deny();
57
+ const data=JSON.parse(readFileSync(receiptPath,'utf8'));
58
+ if(data?.schema!==1||data.version!==pkg.version||data.distribution!=='synthetic-private'||data.registered!==false||data.serviceEnabled!==false)deny();
59
+ const runtimePkg=join(root,'node_modules','@remoteshell','device','package.json');
60
+ const dcPkg=join(root,'node_modules','@wonderwhy-er','desktop-commander','package.json');
61
+ for(const file of [runtimePkg,dcPkg]){
62
+ const s=lstatSync(file);
63
+ if(!s.isFile()||s.isSymbolicLink())deny();
64
+ }
65
+ const installed=JSON.parse(readFileSync(runtimePkg,'utf8'));
66
+ const dc=JSON.parse(readFileSync(dcPkg,'utf8'));
67
+ if(installed.name!==pkg.name||installed.version!==pkg.version||dc.version!=='0.3.1')deny('DEVICE_DEPENDENCY_INVALID');
68
+ return data;
69
+ }
70
+ async function confirmReenrollment(){
71
+ console.error('기존 장치 등록이 취소되었거나 인증이 만료되었습니다. 다시 등록하기');
72
+ if(!process.stdin.isTTY||!process.stderr.isTTY)deny('DEVICE_REREGISTRATION_CONFIRM_REQUIRED');
73
+ const prompt=createInterface({input:process.stdin,output:process.stderr});
74
+ try{
75
+ const answer=(await prompt.question('새 장치로 다시 등록할까요? [y/N]: ')).trim().toLowerCase();
76
+ return answer==='y'||answer==='yes';
77
+ }finally{prompt.close();}
78
+ }
79
+ async function status(p){
80
+ if(!existsSync(p.base))return {installed:false,registered:false,connected:false};
81
+ checkDir(p.base,{privateMode:true});
82
+ if(!existsSync(p.install))return {installed:false,registered:false,connected:false};
83
+ checkDir(p.install,{privateMode:true});
84
+ const receipt=checkReceipt(p.install);
85
+ const store=join(p.base,'credentials'),credential=join(store,'device.json');
86
+ const hasMock=existsSync(credential);
87
+ if(hasMock)readDeviceCredential({storageDir:store}); // refuse tampered credentials
88
+ let verified=false,connected=false;
89
+ if(hasMock&&process.env.RS_GATEWAY_URL){
90
+ try{
91
+ const online=await gatewayStatus({gatewayUrl:process.env.RS_GATEWAY_URL,caFile:process.env.RS_CA_FILE});
92
+ verified=online.gatewayVerified;connected=online.connected;
93
+ }catch{verified=false;connected=false;}
94
+ }
95
+ const unit=join(homedir(),'.config/systemd/user/remoteshell-device.service');
96
+ const service=existsSync(unit)?userService({action:'status'}):{unitInstalled:false,active:false};
97
+ const dev=devLocalStatus({storageDir:join(p.base,'dev-credentials')});
98
+ let devRuntime;
99
+ try{const status=controlDevHeartbeatService({action:'status'});
100
+ devRuntime={devUnitInstalled:status.unitInstalled,devProcessRunning:status.running,
101
+ devAutostartEnabled:status.autostartEnabled};
102
+ }catch{devRuntime={devUnitInstalled:'unknown',devProcessRunning:'unknown',devAutostartEnabled:'unknown'};}
103
+ return {installed:true,version:receipt.version,registered:dev.devRegistered,...devRuntime,mockCredentialStored:hasMock,
104
+ connected,gatewayVerified:verified,serviceEnabled:service.enabled===true,serviceActive:service.active===true,
105
+ // The on-device status command cannot prove a remote DC catalog is live.
106
+ // The authenticated owner /dev/devices page resolves this independently.
107
+ heartbeatState:dev.devRegistered?'unverified':'not-registered',
108
+ dcReadiness:'unverified',...dev};
109
+ }
110
+ function install(p){
111
+ if(platform()!=='linux')deny('DEVICE_PLATFORM_UNSUPPORTED');
112
+ for(const d of [p.local,p.share])ensureDir(d);
113
+ ensureDir(p.base,{privateMode:true});
114
+ if(existsSync(p.install))deny('DEVICE_ALREADY_INSTALLED');
115
+ const staging=join(p.base,'.install-'+randomUUID());
116
+ mkdirSync(staging,{mode:0o700});
117
+ try{
118
+ // Package is fetched by npx before this command. Dependencies are pinned;
119
+ // ignore lifecycle scripts and do not execute any downloaded program.
120
+ // Installing directly from a directory makes npm link the ephemeral npx
121
+ // cache. Pack first to ensure the installed Agent survives npx cache cleanup.
122
+ const packed=spawnSync('npm',['pack',packageRoot,'--ignore-scripts','--json','--pack-destination',staging],{
123
+ encoding:'utf8',timeout:30000,maxBuffer:1048576,stdio:'pipe'
124
+ });
125
+ if(packed.error||packed.signal||packed.status!==0)deny('DEVICE_INSTALL_PACKAGE_FAILED');
126
+ let meta;
127
+ try{meta=JSON.parse(packed.stdout);}catch{deny('DEVICE_INSTALL_PACKAGE_FAILED');}
128
+ const entry=Array.isArray(meta)?meta[0]:meta['@remoteshell/device'];
129
+ if(entry?.filename!==`remoteshell-device-${pkg.version}.tgz`)deny('DEVICE_INSTALL_PACKAGE_FAILED');
130
+ const archive=join(staging,entry.filename);
131
+ const result=spawnSync('npm',['install','--prefix',staging,'--ignore-scripts','--no-audit','--no-fund','--no-package-lock','--no-save',archive],{
132
+ encoding:'utf8',timeout:120000,maxBuffer:65536,stdio:'pipe'
133
+ });
134
+ if(result.error||result.signal||result.status!==0)deny('DEVICE_INSTALL_DEPENDENCY_FAILED');
135
+ rmSync(archive,{force:true});
136
+ writeFileSync(join(staging,'receipt.json'),JSON.stringify({
137
+ schema:1,version:pkg.version,distribution:'synthetic-private',registered:false,serviceEnabled:false
138
+ })+'\n',{flag:'wx',mode:0o600});
139
+ checkReceipt(staging);
140
+ if(existsSync(p.install))deny('DEVICE_ALREADY_INSTALLED');
141
+ renameSync(staging,p.install);
142
+ return {installed:true,version:pkg.version,registered:false,connected:false,serviceEnabled:false,
143
+ next:'enrollment-not-yet-implemented'};
144
+ }finally{if(existsSync(staging))rmSync(staging,{recursive:true,force:true});}
145
+ }
146
+ function uninstall(p){
147
+ if(!existsSync(p.base))return {removed:false};
148
+ checkDir(p.base,{privateMode:true});
149
+ if(!existsSync(p.install))return {removed:false};
150
+ checkDir(p.install,{privateMode:true});
151
+ checkReceipt(p.install);
152
+ const unit=join(homedir(),'.config/systemd/user/remoteshell-device.service');
153
+ if(existsSync(unit))deny('DEVICE_UNIT_MUST_BE_REMOVED_FIRST');
154
+ const devUnit=join(homedir(),'.config/systemd/user/remoteshell-device-dev-heartbeat.service');
155
+ if(existsSync(devUnit))deny('DEVICE_UNIT_MUST_BE_REMOVED_FIRST');
156
+ // No service was installed by this CLI version. No other product folder,
157
+ // credentials, existing P4 unit or release is touched.
158
+ rmSync(p.install,{recursive:true,force:false});
159
+ return {removed:true,credentialsPreserved:true,systemdUntouched:true};
160
+ }
161
+ try{
162
+ if(action==='install-preflight'&&process.argv.length===3){
163
+ let wsl=false;
164
+ if(platform()==='linux'){try{wsl=/microsoft|wsl/i.test(readFileSync('/proc/version','utf8'));}catch{}}
165
+ console.log(JSON.stringify(installPreflight({os:platform(),arch:process.arch,nodeVersion:process.version,wsl})));
166
+ }
167
+ else if(action==='windows-layout'&&process.argv.length===3){
168
+ if(platform()!=='win32')deny('DEVICE_PLATFORM_UNSUPPORTED');
169
+ console.log(JSON.stringify(windowsInstallLayout({
170
+ home:homedir(),localAppData:process.env.LOCALAPPDATA,os:platform()
171
+ })));
172
+ }
173
+ else if(action==='windows-pair'&&process.argv.length===4){
174
+ if(platform()!=='win32')deny('DEVICE_PLATFORM_UNSUPPORTED');
175
+ const home=homedir();
176
+ const layout=windowsInstallLayout({home,localAppData:process.env.LOCALAPPDATA});
177
+ if(!statusWindowsNative({home,localAppData:process.env.LOCALAPPDATA,version:pkg.version}).installed)
178
+ deny('DEVICE_WINDOWS_INSTALL_DENIED');
179
+ ensureWindowsPrivateStore(layout.credentials,{home});
180
+ const previous=devLocalStatus({storageDir:layout.credentials});
181
+ if(previous.devRegistered)deny('DEVICE_ALREADY_REGISTERED');
182
+ const result=await devPairDevice({base:process.argv[3],storageDir:layout.credentials,
183
+ onApprove:url=>console.log(JSON.stringify({next:'approve-device-in-browser',
184
+ approval_url:url,ownerApprovalRequired:true}))});
185
+ console.log(JSON.stringify({...result,runMode:'not-started',
186
+ dcReady:false,autostart:false,next:'windows-start-worker'}));
187
+ }
188
+ else if(action==='install-download-verify'&&process.argv.length===7){
189
+ // Download to a private temporary staging folder and verify with the
190
+ // independently pinned DEV signer; never run or install the archive.
191
+ const [allowedOrigin,manifestUrl,archiveUrl,publicKeyPath]=process.argv.slice(3);
192
+ let wsl=false;
193
+ if(platform()==='linux'){try{wsl=/microsoft|wsl/i.test(readFileSync('/proc/version','utf8'));}catch{}}
194
+ const result=await acquireVerifiedDevArchive({allowedOrigin,manifestUrl,archiveUrl,
195
+ publicKeyPath,os:platform(),arch:process.arch,nodeVersion:process.version,wsl});
196
+ console.log(JSON.stringify(result));
197
+ }
198
+ else if(action==='install-verify'&&process.argv.length===6){
199
+ // Offline only. The manifest/public key cannot establish their own trust:
200
+ // the signer is accepted only after matching the independently pinned DEV key.
201
+ const [artifactPath,manifestPath,keyPath]=process.argv.slice(3);
202
+ const stat=lstatSync(manifestPath);
203
+ if(!stat.isFile()||stat.isSymbolicLink()||stat.size<1||stat.size>8192)
204
+ deny('DEVICE_INSTALL_MANIFEST_DENIED');
205
+ let manifest;
206
+ try{manifest=JSON.parse(readFileSync(manifestPath,'utf8'));}catch{deny('DEVICE_INSTALL_MANIFEST_DENIED');}
207
+ const trustedKeys=loadPinnedDevSigner({publicKeyPath:keyPath});
208
+ let wsl=false;
209
+ if(platform()==='linux'){try{wsl=/microsoft|wsl/i.test(readFileSync('/proc/version','utf8'));}catch{}}
210
+ const result=planVerifiedInstall({artifactPath,manifest,trustedKeys,
211
+ os:platform(),arch:process.arch,nodeVersion:process.version,wsl});
212
+ console.log(JSON.stringify(result));
213
+ }
214
+ 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'){
215
+ // Opt-in native Windows lifecycle: no implicit account registration or service modification.
216
+ if(platform()!=='win32')deny('DEVICE_PLATFORM_UNSUPPORTED');
217
+ const operation=action.slice('windows-service-'.length);
218
+ // Only a paired, version-checked per-user installation may own this task.
219
+ // No SYSTEM service, RDC task, credentials or installer-cache entry is used.
220
+ const home=homedir(),localAppData=process.env.LOCALAPPDATA;
221
+ const layout=windowsInstallLayout({home,localAppData});
222
+ const native=statusWindowsNative({home,localAppData,version:pkg.version});
223
+ if(!native.installed)deny('DEVICE_WINDOWS_INSTALL_DENIED');
224
+ const registered=devOfficialRegistration({storageDir:layout.credentials});
225
+ if(['install','start'].includes(operation)&&!registered)deny('DEVICE_ENROLLMENT_DENIED');
226
+ const script=join(layout.install,'node_modules','@remoteshell','device','bin','device.mjs');
227
+ if(!existsSync(script))deny('DEVICE_WINDOWS_INSTALL_DENIED');
228
+ const result=runWindowsUserPlan({action:operation,nodeBin:process.execPath,
229
+ agentScript:script},{confirmed:true});
230
+ console.log(JSON.stringify({...result,registered:!!registered,deviceId:registered?.deviceId,
231
+ next:operation==='install'?'run-windows-service-start':'verify-device-in-owner-ui'}));
232
+ }
233
+ else if(action==='version'||action==='--version'){console.log(pkg.version);}
234
+ else if(action==='dev-check'&&process.argv.length===4)console.log(JSON.stringify(await probeDev({url:process.argv[3]})));
235
+ else if(action==='dev-enroll'&&process.argv.length===5){
236
+ const p=paths();ensureDir(p.local);ensureDir(p.share);ensureDir(p.base,{privateMode:true});
237
+ console.log(JSON.stringify(await devEnroll({base:process.argv[3],enrollmentId:process.argv[4],storageDir:join(p.base,'dev-credentials'),capability:readDevCapabilityFromStdin()})));
238
+ }
239
+ else if(action==='dev-heartbeat'&&process.argv.length===3){
240
+ const home=homedir();
241
+ const p=platform()==='win32'?windowsInstallLayout({home,localAppData:process.env.LOCALAPPDATA}):paths();
242
+ const storageDir=join(p.base,'dev-credentials');
243
+ const child=startOfficialWorker({home,install:p.install,storageDir});
244
+ if(!child){
245
+ const abort=new AbortController();
246
+ process.once('SIGINT',()=>abort.abort());process.once('SIGTERM',()=>abort.abort());
247
+ console.log(JSON.stringify(await devHeartbeatForeground({storageDir,signal:abort.signal})));
248
+ }
249
+ }
250
+ else if(action==='dev-heartbeat-once'&&process.argv.length===3){
251
+ const home=homedir();
252
+ const p=platform()==='win32'?windowsInstallLayout({home,localAppData:process.env.LOCALAPPDATA}):paths();
253
+ console.log(JSON.stringify(await devHeartbeatOnce({storageDir:join(p.base,'dev-credentials')})));
254
+ }
255
+ else if(action==='dev-agent-run'&&process.argv.length===6){
256
+ const p=paths();checkReceipt(p.install);
257
+ const rootId=process.argv[4],rootPath=process.argv[5];
258
+ const credentialFile=join(p.base,'dev-credentials','device.json');
259
+ devLocalStatus({storageDir:join(p.base,'dev-credentials')});
260
+ const mainFile=join(p.install,'node_modules/@remoteshell/device/src/device-agent/main.mjs');
261
+ const child=runDevAgentWorker({gatewayUrl:process.argv[3],credentialFile,rootId,rootPath,
262
+ mainFile,home:homedir()});
263
+ child.once('error',()=>deny('DEVICE_DEV_AGENT_RUN_DENIED'));
264
+ child.once('exit',(code,signal)=>{if(signal)process.kill(process.pid,signal);else process.exitCode=code??1;});
265
+ }
266
+ else if(action==='setup'&&process.argv.length>=4&&process.argv.length<=6){
267
+ const mode=process.argv[4]??'foreground';
268
+ const confirmLinger=process.argv[5]==='--confirm-linger';
269
+ if(!['foreground','manual','login','boot'].includes(mode)||
270
+ (process.argv.length===6&&!confirmLinger)||
271
+ (confirmLinger&&mode!=='boot'))deny('DEVICE_DEV_SERVICE_DENIED');
272
+ const p=paths();
273
+ const base=process.argv[3];
274
+ // Install first, then request browser owner consent. On failure the CLI must
275
+ // never claim registration or an enabled background service.
276
+ if(!existsSync(p.install))install(p);
277
+ else checkReceipt(p.install);
278
+ const credentialDir=join(p.base,'dev-credentials');
279
+ const already=devLocalStatus({storageDir:credentialDir});
280
+ const pairDevice=options=>devPairDevice({base,storageDir:credentialDir,...options,
281
+ onApprove:url=>{
282
+ console.log(JSON.stringify({next:'approve-device-in-browser',approval_url:url}));
283
+ openDevApproval(url,{base});
284
+ }});
285
+ let out;
286
+ if(already.devRegistered){
287
+ try{
288
+ out=await resumeRegisteredDevice({localStatus:already,
289
+ heartbeatOnce:()=>devHeartbeatOnce({storageDir:credentialDir})});
290
+ }catch(e){
291
+ if(e?.message!=='DEVICE_DEV_CREDENTIAL_REVOKED')throw e;
292
+ out=await recoverRevokedDevice({localStatus:already,
293
+ confirmReplacement:confirmReenrollment,pairDevice});
294
+ }
295
+ }else out=await pairDevice();
296
+ if(mode==='foreground'){
297
+ const child=startOfficialWorker({home:homedir(),install:p.install,storageDir:credentialDir});
298
+ console.log(JSON.stringify({...out,runMode:'foreground',autostart:false,
299
+ next:child?'dc-worker-starting':'foreground-running'}));
300
+ if(!child){
301
+ const abort=new AbortController();
302
+ process.once('SIGINT',()=>abort.abort());process.once('SIGTERM',()=>abort.abort());
303
+ console.log(JSON.stringify(await devHeartbeatForeground({storageDir:credentialDir,signal:abort.signal})));
304
+ }
305
+ }else{
306
+ const service=configureDevHeartbeatService({mode,confirmLinger});
307
+ console.log(JSON.stringify({...out,runMode:mode,serviceEnabled:service.enabled,
308
+ serviceStarted:service.started,next:'dc-worker-connecting'}));
309
+ }
310
+ }
311
+ else if(action==='dev-mode'&&process.argv.length>=4&&process.argv.length<=5){
312
+ const mode=process.argv[3],confirmed=process.argv[4]==='--confirm-linger';
313
+ if(!['manual','login','boot'].includes(mode)||
314
+ (process.argv.length===5&&!confirmed)||(confirmed&&mode!=='boot'))deny('DEVICE_DEV_SERVICE_DENIED');
315
+ console.log(JSON.stringify(configureDevHeartbeatService({mode,confirmLinger:confirmed})));
316
+ }
317
+ else if(action==='dev-run-once'&&process.argv.length===3){
318
+ const p=paths();const storageDir=join(p.base,'dev-credentials');
319
+ const child=startOfficialWorker({home:homedir(),install:p.install,storageDir});
320
+ console.log(JSON.stringify({runMode:'foreground',autostart:false,registeredPreserved:true,
321
+ next:child?'dc-worker-starting':'heartbeat-running'}));
322
+ if(!child){
323
+ const abort=new AbortController();
324
+ process.once('SIGINT',()=>abort.abort());process.once('SIGTERM',()=>abort.abort());
325
+ console.log(JSON.stringify(await devHeartbeatForeground({storageDir,signal:abort.signal})));
326
+ }
327
+ }
328
+ else if(['dev-start','dev-stop','dev-status','dev-autostart-enable','dev-autostart-disable'].includes(action)&&process.argv.length===3){
329
+ const actions={'dev-start':'start','dev-stop':'stop','dev-status':'status','dev-autostart-enable':'autostart-enable','dev-autostart-disable':'autostart-disable'};
330
+ console.log(JSON.stringify(controlDevHeartbeatService({action:actions[action]})));
331
+ }
332
+ else if(action==='dev-service-uninstall'&&process.argv.length===3)console.log(JSON.stringify(uninstallDevHeartbeatService()));
333
+ else if(action==='install'&&process.argv.length===3){
334
+ let wsl=false;
335
+ if(platform()==='linux'){try{wsl=/microsoft|wsl/i.test(readFileSync('/proc/version','utf8'));}catch{}}
336
+ // The non-executing preflight is a necessary gate for installation too.
337
+ // Its own JSON output is not proof of an installed or connected Agent.
338
+ installPreflight({os:platform(),arch:process.arch,nodeVersion:process.version,wsl});
339
+ console.log(JSON.stringify(platform()==='win32'?installWindowsNative({home:homedir(),localAppData:process.env.LOCALAPPDATA,packageRoot,version:pkg.version}):install(paths())));
340
+ }
341
+ else if(action==='status'&&process.argv.length===3){
342
+ if(platform()==='win32'){
343
+ const home=homedir();
344
+ const layout=windowsInstallLayout({home,localAppData:process.env.LOCALAPPDATA});
345
+ const state=statusWindowsNative({home,localAppData:process.env.LOCALAPPDATA,version:pkg.version});
346
+ const registered=devOfficialRegistration({storageDir:layout.credentials});
347
+ console.log(JSON.stringify({...state,registered:!!registered,deviceId:registered?.deviceId,
348
+ connected:false,dcReady:false,heartbeatState:registered?'unverified':'not-registered'}));
349
+ }else console.log(JSON.stringify(await status(paths())));
350
+ }
351
+ 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())));
352
+ 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})));
353
+ 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)})));
354
+ 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})));
355
+ else if(['update','register'].includes(action)){
356
+ console.error('DEVICE_ONBOARDING_NOT_READY');
357
+ process.exitCode=2;
358
+ }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;}
359
+ }catch(e){
360
+ 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']);
361
+ console.error(codes.has(e.message)?e.message:'DEVICE_INSTALL_DENIED');
362
+ process.exitCode=1;
363
+ }
@@ -0,0 +1,105 @@
1
+ // Device-side enrollment CONSUMER. Local synthetic fixture only until #123
2
+ // specifies/ships an authenticated Agent-credential envelope API.
3
+ // Does not implement a Control Plane, owner approval, a database, or a token issuer.
4
+ import {generateKeyPairSync,sign,verify,createHash,randomBytes,createPublicKey,createPrivateKey} from 'node:crypto';
5
+ import {existsSync,lstatSync,mkdirSync,writeFileSync,readFileSync,renameSync,rmSync} from 'node:fs';
6
+ import {join} from 'node:path';
7
+ const FAIL='DEVICE_ENROLLMENT_DENIED';
8
+ const deny=()=>{throw Error(FAIL);};
9
+ const b64=b=>Buffer.from(b).toString('base64url');
10
+ const sha=b=>createHash('sha256').update(b).digest('hex');
11
+ const validId=id=>typeof id==='string'&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id);
12
+ const canonical=data=>JSON.stringify(data);
13
+ const own=(path,mode)=>{
14
+ const s=lstatSync(path);
15
+ if(!s.isFile()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(s.mode&0o777)!==mode)deny();
16
+ };
17
+ function privateDir(path){
18
+ if(!existsSync(path))mkdirSync(path,{mode:0o700});
19
+ const s=lstatSync(path);
20
+ if(!s.isDirectory()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(s.mode&0o777)!==0o700)deny();
21
+ }
22
+ function atomicFile(path,data){
23
+ if(existsSync(path))deny();
24
+ const temp=path+'.tmp-'+b64(randomBytes(12));
25
+ try{writeFileSync(temp,data,{mode:0o600,flag:'wx'});renameSync(temp,path);}finally{rmSync(temp,{force:true});}
26
+ }
27
+ export function prepareDeviceProof({enrollmentId,challenge,consumer='remoteshell-device.v0.1',keypair}={}){
28
+ // PROPOSED v0.1 proof: canonical JSON + Ed25519. Real wire contract is unapproved.
29
+ if(!validId(enrollmentId)||typeof challenge!=='string'||challenge.length<24||challenge.length>2048||
30
+ consumer!=='remoteshell-device.v0.1')deny();
31
+ const keys=keypair||generateKeyPairSync('ed25519');
32
+ const publicKey=keys.publicKey.export({type:'spki',format:'der'});
33
+ const nonce=b64(randomBytes(32));
34
+ const payload={v:'rs-device-proof-mock-v0.1',enrollment_id:enrollmentId,challenge_hash:sha(challenge),consumer,public_key:b64(publicKey),nonce};
35
+ const message=canonical(payload);
36
+ const signature=b64(sign(null,Buffer.from(message),keys.privateKey));
37
+ return {payload,signature,privateKey:keys.privateKey,publicKey:keys.publicKey};
38
+ }
39
+ export function verifyPreparedProof(proof){
40
+ if(proof?.payload?.v!=='rs-device-proof-mock-v0.1'||typeof proof.signature!=='string')deny();
41
+ const publicKey=createPublicKey({key:Buffer.from(proof.payload.public_key,'base64url'),type:'spki',format:'der'});
42
+ if(!verify(null,Buffer.from(canonical(proof.payload)),publicKey,Buffer.from(proof.signature,'base64url')))deny();
43
+ return true;
44
+ }
45
+ export function acceptMockCredential({proof,response,fixtureIssuerPublicKey,storageDir,now=Date.now()}={}){
46
+ // Fail closed: a raw/unverified credential or real CP v4 metadata response is
47
+ // never accepted. This fixture format is NOT the supplier API contract.
48
+ if(!proof?.privateKey||!fixtureIssuerPublicKey||!response||response.format!=='rs-device-credential-mock-v0.1')deny();
49
+ try{
50
+ const actualKey=b64(createPublicKey(proof.privateKey).export({type:'spki',format:'der'}));
51
+ if(actualKey!==proof.payload?.public_key||!verifyPreparedProof(proof))deny();
52
+ }catch{deny();}
53
+ if(!validId(response.device_id)||typeof response.credential!=='string'||response.credential.length<32||
54
+ response.credential.length>512||response.approved!==true||
55
+ response.public_key!==proof.payload.public_key||response.enrollment_id!==proof.payload.enrollment_id||
56
+ !Number.isSafeInteger(response.expires_at)||response.expires_at<=now||
57
+ typeof response.signature!=='string')deny();
58
+ const {signature,...body}=response;
59
+ if(!verify(null,Buffer.from(canonical(body)),fixtureIssuerPublicKey,Buffer.from(signature,'base64url')))deny();
60
+ // This path is a disposable synthetic credential store. Never place the
61
+ // credential in stdout, command arguments, web session, npm package, or logs.
62
+ privateDir(storageDir);
63
+ const file=join(storageDir,'device.json');
64
+ atomicFile(file,JSON.stringify({device_id:response.device_id,credential:response.credential})+'\n');
65
+ own(file,0o600);
66
+ return {saved:true,device_id:response.device_id,credentialReturned:false,provider:'mock'};
67
+ }
68
+ export function readDeviceCredential({storageDir}={}){
69
+ const stat=lstatSync(storageDir);
70
+ if(!stat.isDirectory()||stat.isSymbolicLink()||(stat.mode&0o777)!==0o700||stat.uid!==process.getuid?.())deny();
71
+ const file=join(storageDir,'device.json');
72
+ own(file,0o600);
73
+ const value=JSON.parse(readFileSync(file,'utf8'));
74
+ if(Object.keys(value).sort().join(',')!=='credential,device_id'||!validId(value.device_id)||
75
+ typeof value.credential!=='string'||value.credential.length<32)deny();
76
+ return value;
77
+ }
78
+
79
+ export function loadOrCreateMockDeviceKey({storageDir}={}){
80
+ if(!storageDir||typeof storageDir!=='string'||!storageDir.startsWith('/'))deny();
81
+ privateDir(storageDir);
82
+ const file=join(storageDir,'device-key.pem');
83
+ if(!existsSync(file)){
84
+ const pair=generateKeyPairSync('ed25519');
85
+ atomicFile(file,pair.privateKey.export({type:'pkcs8',format:'pem'}));
86
+ }
87
+ own(file,0o600);
88
+ const pem=readFileSync(file,'utf8');
89
+ if(pem.length>8192||!pem.includes('BEGIN PRIVATE KEY'))deny();
90
+ try{
91
+ const privateKey=createPrivateKey(pem);
92
+ if(privateKey.asymmetricKeyType!=='ed25519')deny();
93
+ return {privateKey,publicKey:createPublicKey(privateKey)};
94
+ }catch{deny();}
95
+ }
96
+ // Local mock-only credential revocation; real CP revoke must be confirmed
97
+ // by the authoritative provider before invoking this cleanup.
98
+ export function clearMockCredentialAfterRevoke({storageDir}={}){
99
+ privateDir(storageDir);
100
+ const file=join(storageDir,'device.json');
101
+ if(!existsSync(file))return {cleared:false,provider:'mock'};
102
+ own(file,0o600);
103
+ rmSync(file);
104
+ return {cleared:true,provider:'mock',deviceKeyPreserved:true};
105
+ }
@@ -0,0 +1,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
+ }