@remoteshell/device 0.1.0-beta.1 → 0.1.0-beta.3

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 (85) 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 +233 -9
  15. package/bin/install-acquire.mjs +89 -0
  16. package/bin/install-integrity.mjs +74 -0
  17. package/bin/install-plan.mjs +43 -0
  18. package/bin/native-path-contract.mjs +23 -0
  19. package/bin/remoteshell-device-install.cmd +17 -0
  20. package/bin/remoteshell-device-install.ps1 +17 -0
  21. package/bin/remoteshell-device-install.sh +15 -0
  22. package/bin/remoteshell-device-preflight.cmd +10 -0
  23. package/bin/remoteshell-device-preflight.ps1 +10 -0
  24. package/bin/remoteshell-easy-diagnose.ps1 +32 -0
  25. package/bin/remoteshell-easy-install.ps1 +289 -0
  26. package/bin/remoteshell-easy-install.sh +71 -0
  27. package/bin/remoteshell-easy-uninstall.ps1 +124 -0
  28. package/bin/windows-credential-boundary.mjs +106 -0
  29. package/bin/windows-install-layout.mjs +28 -0
  30. package/bin/windows-native-installer.mjs +91 -0
  31. package/bin/windows-private-store.mjs +163 -0
  32. package/bin/windows-user-lifecycle.mjs +34 -0
  33. package/npm-shrinkwrap.json +8591 -0
  34. package/package.json +14 -5
  35. package/shared/lib/bounded-search-contract.mjs +5 -0
  36. package/shared/lib/dc-generic-policy.mjs +102 -0
  37. package/shared/lib/dc-relay-contract.mjs +42 -0
  38. package/shared/lib/dc-tool-catalog.mjs +67 -0
  39. package/shared/lib/dev-dc-relay-contract.mjs +20 -0
  40. package/shared/lib/dev-paged-output.mjs +32 -0
  41. package/shared/lib/dev-root-exclusions.mjs +56 -0
  42. package/{src/common → shared/lib}/synthetic-write-policy.mjs +0 -1
  43. package/src/config/l2-dev-oci-credential.mjs +39 -0
  44. package/src/config/p2-private-credential.mjs +15 -0
  45. package/src/connection/dev-dogfood-processes.mjs +25 -0
  46. package/src/connection/dev-dogfood-read.mjs +64 -0
  47. package/src/connection/dev-dogfood-task.mjs +113 -0
  48. package/src/connection/dev-dogfood-write.mjs +62 -0
  49. package/src/connection/dev-file-task.mjs +119 -0
  50. package/src/connection/dev-r4-file-task.mjs +56 -0
  51. package/src/connection/dev-read-tools.mjs +134 -0
  52. package/src/connection/dev-root-scopes.mjs +82 -0
  53. package/src/{device-agent → core}/c1-supervisor.mjs +9 -7
  54. package/src/{device-agent → core}/c1-worker.mjs +7 -7
  55. package/src/dc/dc-access-readiness.mjs +31 -0
  56. package/src/dc/dev-dc-relay.mjs +47 -0
  57. package/src/device-agent/main.mjs +1 -230
  58. package/src/gateway-keepalive.mjs +73 -0
  59. package/src/main.mjs +434 -0
  60. package/src/{common → policy}/bounded-search-adapter.mjs +2 -3
  61. package/src/{common → policy}/isolated-read-adapter.mjs +1 -1
  62. package/src/{common → policy}/isolated-read-mount.mjs +1 -1
  63. package/src/{common → policy}/synthetic-auxiliary-adapter.mjs +1 -1
  64. package/src/{common → policy}/synthetic-file-adapter.mjs +1 -1
  65. package/src/{common → policy}/synthetic-file-transaction.mjs +1 -1
  66. package/src/{common → policy}/synthetic-write-adapter.mjs +2 -3
  67. /package/{src/common → shared/lib}/bounded-search-policy.mjs +0 -0
  68. /package/{src/common → shared/lib}/config.mjs +0 -0
  69. /package/{src/common → shared/lib}/contracts.mjs +0 -0
  70. /package/{src/common → shared/lib}/errors.mjs +0 -0
  71. /package/{src/common → shared/lib}/events.mjs +0 -0
  72. /package/{src/common → shared/lib}/execution-policy.mjs +0 -0
  73. /package/{src/common → shared/lib}/isolated-read-boundary.mjs +0 -0
  74. /package/{src/common → shared/lib}/isolated-read-policy.mjs +0 -0
  75. /package/{src/common → shared/lib}/lifecycle-events.mjs +0 -0
  76. /package/{src/common → shared/lib}/runtime-timing.mjs +0 -0
  77. /package/{src/common → shared/lib}/synthetic-auxiliary-policy.mjs +0 -0
  78. /package/{src/common → shared/lib}/tool-registry.mjs +0 -0
  79. /package/src/{device-agent → core}/c1-dc-transport.mjs +0 -0
  80. /package/src/{device-agent → core}/c1-startup.mjs +0 -0
  81. /package/src/{device-agent → core}/fixture.txt +0 -0
  82. /package/src/{common → policy}/synthetic-write-mount.mjs +0 -0
  83. /package/src/{common → policy}/verified-bounded-search.mjs +0 -0
  84. /package/src/{common → policy}/verified-isolated-read.mjs +0 -0
  85. /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,25 @@ 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';
13
30
  const require=createRequire(import.meta.url);
14
31
  const pkg=require('../package.json');
15
32
  const packageRoot=resolve(dirname(fileURLToPath(import.meta.url)),'..');
@@ -47,9 +64,18 @@ function checkReceipt(root){
47
64
  }
48
65
  const installed=JSON.parse(readFileSync(runtimePkg,'utf8'));
49
66
  const dc=JSON.parse(readFileSync(dcPkg,'utf8'));
50
- if(installed.name!==pkg.name||installed.version!==pkg.version||dc.version!=='0.3.0')deny('DEVICE_DEPENDENCY_INVALID');
67
+ if(installed.name!==pkg.name||installed.version!==pkg.version||dc.version!=='0.3.1')deny('DEVICE_DEPENDENCY_INVALID');
51
68
  return data;
52
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
+ }
53
79
  async function status(p){
54
80
  if(!existsSync(p.base))return {installed:false,registered:false,connected:false};
55
81
  checkDir(p.base,{privateMode:true});
@@ -68,8 +94,18 @@ async function status(p){
68
94
  }
69
95
  const unit=join(homedir(),'.config/systemd/user/remoteshell-device.service');
70
96
  const service=existsSync(unit)?userService({action:'status'}):{unitInstalled:false,active:false};
71
- return {installed:true,version:receipt.version,registered:false,mockCredentialStored:hasMock,
72
- connected,gatewayVerified:verified,serviceEnabled:service.enabled===true,serviceActive:service.active===true};
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};
73
109
  }
74
110
  function install(p){
75
111
  if(platform()!=='linux')deny('DEVICE_PLATFORM_UNSUPPORTED');
@@ -115,25 +151,213 @@ function uninstall(p){
115
151
  checkReceipt(p.install);
116
152
  const unit=join(homedir(),'.config/systemd/user/remoteshell-device.service');
117
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');
118
156
  // No service was installed by this CLI version. No other product folder,
119
157
  // credentials, existing P4 unit or release is touched.
120
158
  rmSync(p.install,{recursive:true,force:false});
121
159
  return {removed:true,credentialsPreserved:true,systemdUntouched:true};
122
160
  }
123
161
  try{
124
- if(action==='version'||action==='--version'){console.log(pkg.version);}
125
- else if(action==='install'&&process.argv.length===3)console.log(JSON.stringify(install(paths())));
126
- else if(action==='status'&&process.argv.length===3)console.log(JSON.stringify(await status(paths())));
127
- else if(action==='uninstall'&&process.argv.length===3)console.log(JSON.stringify(uninstall(paths())));
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())));
128
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})));
129
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)})));
130
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})));
131
355
  else if(['update','register'].includes(action)){
132
356
  console.error('DEVICE_ONBOARDING_NOT_READY');
133
357
  process.exitCode=2;
134
- }else{console.error('Usage: remoteshell-device version|install|status|uninstall');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;}
135
359
  }catch(e){
136
- const codes=new Set(['DEVICE_INSTALL_DENIED','DEVICE_PLATFORM_UNSUPPORTED','DEVICE_ALREADY_INSTALLED','DEVICE_DEPENDENCY_INVALID','DEVICE_INSTALL_DEPENDENCY_FAILED','DEVICE_INSTALL_PACKAGE_FAILED','DEVICE_LIFECYCLE_DENIED','DEVICE_ENROLLMENT_DENIED','DEVICE_UNIT_MUST_BE_REMOVED_FIRST']);
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']);
137
361
  console.error(codes.has(e.message)?e.message:'DEVICE_INSTALL_DENIED');
138
362
  process.exitCode=1;
139
363
  }
@@ -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
+ }
@@ -0,0 +1,74 @@
1
+ // #310: non-executing installer preflight aligned with the existing DEV
2
+ // artifact-delivery schema v2 and the independently pinned Ed25519 key.
3
+ // Trust anchors come from the installer, never from a downloaded manifest.
4
+ import {createHash,createPublicKey,verify as verifySignature,timingSafeEqual} from 'node:crypto';
5
+ import {openSync,closeSync,readSync,lstatSync,fstatSync,constants} from 'node:fs';
6
+ import {basename} from 'node:path';
7
+ const MAX_BYTES=128*1024*1024;
8
+ const fail=code=>{throw Object.assign(new Error(code),{code});};
9
+ const versionOk=v=>typeof v==='string'&&/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(v);
10
+ const hashOk=x=>typeof x==='string'&&/^[0-9a-f]{64}$/.test(x);
11
+ const nameOk=x=>typeof x==='string'&&/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}\.tgz$/.test(x)&&!x.includes('..');
12
+ export function installPreflight({os,arch,nodeVersion,wsl=false}={}){
13
+ const supported=(os==='win32'||os==='linux')&&['x64','arm64'].includes(arch);
14
+ const major=Number(/^v?(\d+)(?:\.|$)/.exec(nodeVersion||'')?.[1]);
15
+ if(!supported)fail('DEVICE_INSTALL_OS_UNSUPPORTED');
16
+ if(wsl)fail('DEVICE_INSTALL_WSL_BETA_EXCLUDED');
17
+ if(!Number.isInteger(major)||major<22)fail('DEVICE_INSTALL_NODE_UNSUPPORTED');
18
+ return Object.freeze({preflight:'PASS',os,arch,nodeMajor:major,automaticInstall:false,
19
+ installationReady:false,requiresOwnerConsent:true});
20
+ }
21
+ export function verifySignedInstallArchive({artifactPath,manifest,trustedKeys,os,arch,nodeVersion,wsl=false}={}){
22
+ installPreflight({os,arch,nodeVersion,wsl});
23
+ const fields=manifest?.signed_fields;
24
+ if(!manifest||typeof manifest!=='object'||Array.isArray(manifest)||
25
+ Object.keys(manifest).sort().join(',')!=='algorithm,public_key_sha256,signature,signed_fields'||
26
+ manifest.algorithm!=='ed25519'||!hashOk(manifest.public_key_sha256)||
27
+ typeof manifest.signature!=='string'||!/^[A-Za-z0-9_-]{86}$/.test(manifest.signature)||
28
+ !fields||typeof fields!=='object'||Array.isArray(fields)||
29
+ fields.schema_version!==2||fields.channel!=='private-dev'||fields.public_release!==false||
30
+ fields.package!=='@remoteshell/device'||!versionOk(fields.version)||
31
+ fields.os!==os||fields.arch!==arch||!nameOk(fields.artifact)||
32
+ fields.artifact!==basename(artifactPath||'')||!Number.isSafeInteger(fields.bytes)||
33
+ fields.bytes<1||fields.bytes>MAX_BYTES||!hashOk(fields.sha256)||
34
+ typeof fields.source_head!=='string'||!/^[a-f0-9]{40}$/.test(fields.source_head)||
35
+ typeof fields.feature!=='string'||fields.feature.length>150)
36
+ fail('DEVICE_INSTALL_MANIFEST_DENIED');
37
+ const trusted=trustedKeys&&Object.hasOwn(trustedKeys,manifest.public_key_sha256)?
38
+ trustedKeys[manifest.public_key_sha256]:null;
39
+ if(!trusted)fail('DEVICE_INSTALL_TRUST_ANCHOR_MISSING');
40
+ let key;
41
+ try{key=trusted?.type==='public'&&trusted?.asymmetricKeyType==='ed25519'?trusted:createPublicKey(trusted);}
42
+ catch{fail('DEVICE_INSTALL_TRUST_ANCHOR_INVALID');}
43
+ if(key.asymmetricKeyType!=='ed25519'||key.type!=='public')fail('DEVICE_INSTALL_TRUST_ANCHOR_INVALID');
44
+ const fingerprint=createHash('sha256').update(key.export({type:'spki',format:'der'})).digest('hex');
45
+ if(fingerprint!==manifest.public_key_sha256)fail('DEVICE_INSTALL_TRUST_ANCHOR_INVALID');
46
+ const signature=Buffer.from(manifest.signature,'base64url');
47
+ if(signature.length!==64||!verifySignature(null,Buffer.from(JSON.stringify(fields),'utf8'),key,signature))
48
+ fail('DEVICE_INSTALL_SIGNATURE_DENIED');
49
+ let fd;
50
+ try{
51
+ const st=lstatSync(artifactPath);
52
+ if(!st.isFile()||st.isSymbolicLink()||st.size!==fields.bytes)fail('DEVICE_INSTALL_ARTIFACT_DENIED');
53
+ fd=openSync(artifactPath,constants.O_RDONLY | (constants.O_NOFOLLOW||0));
54
+ const first=fstatSync(fd);
55
+ if(!first.isFile()||first.dev!==st.dev||first.ino!==st.ino||first.size!==st.size)
56
+ fail('DEVICE_INSTALL_ARTIFACT_DENIED');
57
+ const hash=createHash('sha256'),buffer=Buffer.alloc(65536);
58
+ let remaining=st.size;
59
+ while(remaining>0){
60
+ const count=readSync(fd,buffer,0,Math.min(buffer.length,remaining),null);
61
+ if(count<=0)fail('DEVICE_INSTALL_ARTIFACT_DENIED');
62
+ hash.update(buffer.subarray(0,count));remaining-=count;
63
+ }
64
+ const after=fstatSync(fd);
65
+ if(after.size!==first.size||after.mtimeMs!==first.mtimeMs||after.ino!==first.ino)
66
+ fail('DEVICE_INSTALL_ARTIFACT_DENIED');
67
+ const actual=Buffer.from(hash.digest('hex'),'hex');
68
+ if(!timingSafeEqual(actual,Buffer.from(fields.sha256,'hex')))
69
+ fail('DEVICE_INSTALL_CHECKSUM_DENIED');
70
+ }catch(e){if(e?.code?.startsWith('DEVICE_INSTALL_'))throw e;fail('DEVICE_INSTALL_ARTIFACT_DENIED');}
71
+ finally{if(fd!==undefined)closeSync(fd);}
72
+ return Object.freeze({verified:true,version:fields.version,os,arch,sha256:fields.sha256,
73
+ signingKeyFingerprint:fingerprint,channel:fields.channel,installed:false,registered:false});
74
+ }
@@ -0,0 +1,43 @@
1
+ // #310 Shared, non-executing installation decision. Both OS entrypoints must
2
+ // consume one verified artifact; this module never runs it or changes credentials.
3
+ import {verifySignedInstallArchive} from './install-integrity.mjs';
4
+ const fail=code=>{throw Error(code);};
5
+ function semver(value){
6
+ if(typeof value!=='string'||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(value))
7
+ fail('DEVICE_INSTALL_VERSION_DENIED');
8
+ return value.split('-')[0].split('.').map(Number);
9
+ }
10
+ function compare(a,b){
11
+ const av=semver(a),bv=semver(b);
12
+ for(let i=0;i<3;i++){if(av[i]>bv[i])return 1;if(av[i]<bv[i])return -1;}
13
+ // Never infer prerelease ordering or treat a prerelease as a final release.
14
+ if(a===b)return 0;
15
+ fail('DEVICE_INSTALL_VERSION_REVIEW_REQUIRED');
16
+ }
17
+ export function planVerifiedInstall({
18
+ artifactPath,manifest,trustedKeys,os,arch,nodeVersion,wsl=false,
19
+ installedVersion=null,existingCredentials=false,existingService=false,
20
+ consent=false
21
+ }={}){
22
+ // Validate before making a version or installation decision, even on no-op.
23
+ const verified=verifySignedInstallArchive({
24
+ artifactPath,manifest,trustedKeys,os,arch,nodeVersion,wsl
25
+ });
26
+ if(typeof existingCredentials!=='boolean'||typeof existingService!=='boolean'||
27
+ typeof consent!=='boolean')fail('DEVICE_INSTALL_STATE_DENIED');
28
+ const result=installedVersion===null?'fresh':
29
+ compare(verified.version,installedVersion)===0?'already-installed':
30
+ compare(verified.version,installedVersion)>0?'upgrade':'downgrade';
31
+ if(result==='downgrade')fail('DEVICE_INSTALL_DOWNGRADE_DENIED');
32
+ if(existingService&&installedVersion===null)fail('DEVICE_INSTALL_STATE_DENIED');
33
+ return Object.freeze({
34
+ verified:true,os,arch,version:verified.version,
35
+ signingKeyFingerprint:verified.signingKeyFingerprint,
36
+ artifactSha256:verified.sha256,action:result,
37
+ // Installing, replacing, service enabling and re-enrollment are separate
38
+ // later steps and require an explicit consent/restore plan.
39
+ next:consent?'OS_INSTALL_APPROVAL_REQUIRED':'USER_CONSENT_REQUIRED',
40
+ approvedToExecute:false,installed:false,deviceRegistered:false,
41
+ credentialsPreserved:true,existingCredentials,existingService
42
+ });
43
+ }
@@ -0,0 +1,23 @@
1
+ // #310 Windows lexical path boundary for offline planning only. This is NOT
2
+ // proof of NTFS ownership/ACLs, reparse-point freedom, or an approved Root.
3
+ import {win32} from 'node:path';
4
+ const deny=()=>{throw Error('DEVICE_WINDOWS_PATH_DENIED');};
5
+ const reserved=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
6
+ export function canonicalWindowsLocalFile(path){
7
+ if(typeof path!=='string'||path.length<4||path.length>1024||!(/^[A-Za-z]:\\/.test(path)))
8
+ deny();
9
+ // Reject UNC, device namespaces, forward slashes, ADS, env interpolation and
10
+ // shell metacharacters before a name can be used in a task argument.
11
+ if(/[\x00-\x1f\x7f"<>|?*\/&^%]/.test(path)||path.slice(2).includes(':'))deny();
12
+ const segments=path.slice(3).split('\\');
13
+ if(segments.length===0||segments.some(x=>!x||x==='.'||x==='..'||/[. ]$/.test(x)||reserved.test(x)))deny();
14
+ const normalized=win32.normalize(path);
15
+ if(normalized!==path)deny(); // no invisible normalization changes
16
+ return path;
17
+ }
18
+ export function isWindowsChildPath(path,root){
19
+ const child=canonicalWindowsLocalFile(path),parent=canonicalWindowsLocalFile(root);
20
+ const rel=win32.relative(parent,child);
21
+ if(!rel||rel==='..'||rel.startsWith('..\\')||win32.isAbsolute(rel))deny();
22
+ return true;
23
+ }
@@ -0,0 +1,17 @@
1
+ @echo off
2
+ setlocal DisableDelayedExpansion
3
+ rem #310: package-local Windows bootstrap; no network download or privileged task.
4
+ rem Only run from an independently verified private package within this user profile.
5
+ if not "%~1"=="" (
6
+ echo DEVICE_INSTALL_ARGS_DENIED 1>&2
7
+ exit /b 2
8
+ )
9
+ where node >nul 2>nul
10
+ if errorlevel 1 (
11
+ echo DEVICE_INSTALL_NODE_UNSUPPORTED 1>&2
12
+ exit /b 1
13
+ )
14
+ node "%~dp0device.mjs" install-preflight
15
+ if errorlevel 1 exit /b %errorlevel%
16
+ node "%~dp0device.mjs" install
17
+ exit /b %errorlevel%
@@ -0,0 +1,17 @@
1
+ # #310: package-local Windows bootstrap. Does not download or elevate.
2
+ # Run only from the verified private package in the current user's profile.
3
+ $ErrorActionPreference = 'Stop'
4
+ if ($args.Count -ne 0) {
5
+ [Console]::Error.WriteLine('DEVICE_INSTALL_ARGS_DENIED')
6
+ exit 2
7
+ }
8
+ $node = Get-Command node -CommandType Application -ErrorAction SilentlyContinue
9
+ if ($null -eq $node) {
10
+ [Console]::Error.WriteLine('DEVICE_INSTALL_NODE_UNSUPPORTED')
11
+ exit 1
12
+ }
13
+ $entry = Join-Path $PSScriptRoot 'device.mjs'
14
+ & $node.Source $entry install-preflight
15
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
16
+ & $node.Source $entry install
17
+ exit $LASTEXITCODE
@@ -0,0 +1,15 @@
1
+ #!/bin/sh
2
+ # #310: package-local Linux bootstrap; never executes downloaded shell text.
3
+ # Download/verify/signature trust must be handled before invoking this script.
4
+ set -eu
5
+ if [ "$#" -ne 0 ]; then
6
+ echo DEVICE_INSTALL_ARGS_DENIED >&2
7
+ exit 2
8
+ fi
9
+ if ! command -v node >/dev/null 2>&1; then
10
+ echo DEVICE_INSTALL_NODE_UNSUPPORTED >&2
11
+ exit 1
12
+ fi
13
+ entry_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
14
+ node "$entry_dir/device.mjs" install-preflight
15
+ node "$entry_dir/device.mjs" install
@@ -0,0 +1,10 @@
1
+ @echo off
2
+ setlocal DisableDelayedExpansion
3
+ rem Windows native preflight only. No download, enrollment or service mutation.
4
+ where node >nul 2>nul
5
+ if errorlevel 1 (
6
+ echo DEVICE_INSTALL_NODE_UNSUPPORTED 1>&2
7
+ exit /b 1
8
+ )
9
+ node "%~dp0device.mjs" install-preflight
10
+ exit /b %errorlevel%
@@ -0,0 +1,10 @@
1
+ # Windows native preflight only. No download, enrollment or service mutation.
2
+ $ErrorActionPreference = 'Stop'
3
+ $node = Get-Command node -CommandType Application -ErrorAction SilentlyContinue
4
+ if ($null -eq $node) {
5
+ [Console]::Error.WriteLine('DEVICE_INSTALL_NODE_UNSUPPORTED')
6
+ exit 1
7
+ }
8
+ $entry = Join-Path $PSScriptRoot 'device.mjs'
9
+ & $node.Source $entry install-preflight
10
+ exit $LASTEXITCODE