@remoteshell/device 0.1.0-beta.11 → 0.1.0-beta.17

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 (52) hide show
  1. package/NOTICE +17 -1
  2. package/bin/ci-backed-update-approval.mjs +58 -0
  3. package/bin/dev-agent-client.mjs +1 -1
  4. package/bin/dev-agent-runner.mjs +28 -4
  5. package/bin/dev-api-client.mjs +0 -0
  6. package/bin/dev-auto-worker.mjs +2 -2
  7. package/bin/dev-browser-open.mjs +0 -0
  8. package/bin/dev-dogfood-read.mjs +0 -0
  9. package/bin/dev-heartbeat-service.mjs +0 -0
  10. package/bin/dev-pairing-client.mjs +0 -0
  11. package/bin/dev-secrets.mjs +0 -0
  12. package/bin/dev-setup-recovery.mjs +0 -0
  13. package/bin/dev-signer-pin.mjs +0 -0
  14. package/bin/device.mjs +2 -2
  15. package/bin/direct-npx-runtime.mjs +61 -10
  16. package/bin/enrollment-client.mjs +0 -0
  17. package/bin/install-acquire.mjs +0 -0
  18. package/bin/install-integrity.mjs +0 -0
  19. package/bin/install-plan.mjs +0 -0
  20. package/bin/lifecycle.mjs +0 -0
  21. package/bin/native-path-contract.mjs +0 -0
  22. package/bin/remoteshell-device-install.sh +0 -0
  23. package/bin/remoteshell-easy-install.sh +0 -0
  24. package/bin/remoteshell-npx-entry.ps1 +54 -0
  25. package/bin/remoteshell-npx-entry.sh +34 -0
  26. package/bin/safe-update-artifact.mjs +61 -0
  27. package/bin/safe-update-contract.mjs +78 -0
  28. package/bin/safe-update-stage.mjs +62 -0
  29. package/bin/safe-update-transition.mjs +50 -0
  30. package/bin/windows-acl-wmi-client.mjs +35 -9
  31. package/bin/windows-credential-boundary.mjs +6 -5
  32. package/bin/windows-direct-autostart-runner.mjs +57 -9
  33. package/bin/windows-direct-autostart.mjs +0 -0
  34. package/bin/windows-install-layout.mjs +0 -0
  35. package/bin/windows-native-installer.mjs +1 -1
  36. package/bin/windows-private-store.mjs +10 -10
  37. package/bin/windows-safe-update-coordinator.mjs +67 -0
  38. package/bin/windows-safe-update-journal.mjs +69 -0
  39. package/bin/windows-safe-update-pin.mjs +68 -0
  40. package/bin/windows-safe-update-stage.mjs +59 -0
  41. package/bin/windows-user-lifecycle.mjs +0 -0
  42. package/npm-shrinkwrap.json +407 -27
  43. package/package.json +5 -2
  44. package/shared/lib/contracts.mjs +24 -1
  45. package/shared/lib/dc-tool-catalog.mjs +7 -0
  46. package/src/config/l2-dev-oci-credential.mjs +1 -1
  47. package/src/connection/cp-heartbeat-bootstrap.mjs +24 -0
  48. package/src/connection/dev-cp-heartbeat-worker.mjs +39 -0
  49. package/src/connection/startup-native-proof.mjs +18 -0
  50. package/src/core/c1-worker.mjs +3 -3
  51. package/src/gateway-keepalive.mjs +6 -3
  52. package/src/main.mjs +60 -12
package/NOTICE CHANGED
@@ -3,7 +3,7 @@ RemoteShell device agent — Third-party software notices
3
3
  The RemoteShell-owned portions are proprietary; see LICENSE.
4
4
  Third-party dependencies keep their own licenses and notices. In particular:
5
5
 
6
- * @wonderwhy-er/desktop-commander 0.3.1 — MIT License
6
+ * @wonderwhy-er/desktop-commander 0.3.4 — MIT License
7
7
  Copyright (c) 2024-2025 Eduard Ruzga and Desktop Commander Contributors
8
8
  License is shipped by the installed npm dependency.
9
9
  * @modelcontextprotocol/sdk 1.32.1 — MIT License
@@ -18,3 +18,19 @@ license inventory and review unknown licenses before public release.
18
18
 
19
19
  No license to the Desktop Commander trademark or to third-party code beyond
20
20
  their respective third-party terms is granted by RemoteShell.
21
+
22
+
23
+ Additional exact-version DC 0.3.4 dependency notices:
24
+ * node-forge 1.4.4 — (BSD-3-Clause OR GPL-2.0), BSD-3-Clause option.
25
+ Copyright and permission terms are shipped with the installed node-forge dependency.
26
+ Registry metadata: https://www.npmjs.com/package/node-forge/v/1.4.4
27
+ * Optional @img/sharp-libvips-* 1.3.4 — LGPL-3.0-or-later, with further
28
+ component license obligations for prebuilt image-processing libraries.
29
+ https://www.npmjs.com/package/@img/sharp-libvips-linux-x64/v/1.3.4
30
+ Source and component license inventory: https://github.com/lovell/sharp-libvips
31
+ * jszip 3.10.2 / pizzip 3.3.0 — MIT is the chosen alternative
32
+ to their separately offered GPL licenses; preserve installed license notices.
33
+
34
+ These summaries do not replace installed dependency license texts, and do
35
+ not substitute for the LGPL source/copy obligations applicable to optional
36
+ native binaries. Publication requires separate documented legal clearance.
@@ -0,0 +1,58 @@
1
+ // #327 limited beta A: Github Actions OIDC publishing is the trusted approval source.
2
+ // Never treat registry metadata or a user-supplied 'proof' string as authorization.
3
+ const accepted=new WeakSet();
4
+ const DENY=()=>{throw Error('DEVICE_CI_UPDATE_APPROVAL_DENIED');};
5
+ const SHA=/^[a-f0-9]{40}$/;
6
+ const INTEGRITY=/^sha512-[A-Za-z0-9+/]{86}==$/;
7
+ const VERSION=/^0\.1\.0-beta\.([1-9]\d{0,5})$/;
8
+ const REPO='lkhkhk/RemoteShell';
9
+ const WORKFLOW='npm-beta-release.yml';
10
+ function number(v){const m=VERSION.exec(v||'');if(!m)DENY();return Number(m[1]);}
11
+ function stepSucceeded(job,name){return job.steps?.some(s=>s.name===name&&s.conclusion==='success');}
12
+ function verifyRecord({run,jobs,manifest,currentVersion,expected}){
13
+ if(!run||!Array.isArray(jobs)||!manifest||!expected)DENY();
14
+ if(run.repository?.full_name!==REPO||run.name!=='RemoteShell npm beta release'||
15
+ run.event!=='workflow_dispatch'||run.head_branch!=='work/327-install-five-path-e2e'||
16
+ run.status!=='completed'||run.conclusion!=='success'||run.run_attempt!==1||
17
+ !['.github/workflows/'+WORKFLOW,
18
+ REPO+'/.github/workflows/'+WORKFLOW+'@refs/heads/work/327-install-five-path-e2e']
19
+ .includes(run.path))DENY();
20
+ if(!SHA.test(run.head_sha||'')||run.head_sha!==expected.sourceSha||
21
+ !Number.isSafeInteger(run.id)||String(run.id)!==String(expected.runId))DENY();
22
+ if(number(expected.version)<=number(currentVersion)||!INTEGRITY.test(expected.sha512||''))DENY();
23
+ if(manifest.package!=='@remoteshell/device'||manifest.version!==expected.version||
24
+ manifest.sourceSha!==expected.sourceSha||manifest.integrity!==expected.sha512||
25
+ manifest.distTag!=='beta'||manifest.sha256!==expected.sha256)DENY();
26
+ const verified=jobs.find(j=>j.name==='verify-package');
27
+ const published=jobs.find(j=>j.name==='auto-publish-beta');
28
+ if(!verified||verified.conclusion!=='success'||!published||
29
+ published.conclusion!=='success'||!stepSucceeded(published,'Direct trusted-publisher beta release (never latest)')||
30
+ !stepSucceeded(published,'Verify registry integrity, beta tag and unchanged latest'))DENY();
31
+ return {package:manifest.package,version:manifest.version,previousVersion:currentVersion,
32
+ sourceSha:manifest.sourceSha,sha512:manifest.integrity,runId:String(run.id),
33
+ proof:'github-oidc-verified-release'};
34
+ }
35
+ export function isAuthenticatedCiApproval(value){return Boolean(value&&accepted.has(value));}
36
+ export async function approveFromAuthenticatedGithub({token,runId,currentVersion,expected,manifest,fetcher=fetch}={}){
37
+ if(typeof token!=='string'||token.length<10||token.length>4096||
38
+ !Number.isSafeInteger(runId)||runId<=0||typeof fetcher!=='function')DENY();
39
+ const root='https://api.github.com/repos/'+REPO+'/actions/';
40
+ const request=async path=>{
41
+ const response=await fetcher(root+path,{redirect:'error',headers:{
42
+ authorization:'Bearer '+token,accept:'application/vnd.github+json',
43
+ 'x-github-api-version':'2022-11-28'
44
+ },signal:AbortSignal.timeout(15000)});
45
+ if(response.status!==200||response.ok!==true)DENY();
46
+ return response.json();
47
+ };
48
+ try{
49
+ const run=await request('runs/'+runId);
50
+ const data=await request('runs/'+runId+'/jobs?per_page=100');
51
+ if(data.total_count>100||!Array.isArray(data.jobs))DENY();
52
+ const record=verifyRecord({run,jobs:data.jobs,manifest,currentVersion,
53
+ expected:{...expected,runId}});
54
+ const approval=Object.freeze(record);
55
+ accepted.add(approval);
56
+ return approval;
57
+ }catch{DENY()}
58
+ }
@@ -139,7 +139,7 @@ function readState(store,{allowLocal=false,os=process.platform,home=homedir(),
139
139
  path=join(store,'device.json');
140
140
  state=JSON.parse(readPrivate(path));
141
141
  }
142
- }catch{deny();}
142
+ }catch(error){if(error?.message==='DEVICE_WINDOWS_ACL_TIMEOUT')throw error;deny();}
143
143
  if(state?.version!==1||!idPattern.test(state.device_id||'')||
144
144
  typeof state.device_credential!=='string'||state.device_credential.length<24||
145
145
  !Number.isSafeInteger(state.sequence)||state.sequence<0)deny();
@@ -8,17 +8,30 @@ import {inspectWindowsCredentialAcl} from './windows-credential-boundary.mjs';
8
8
  import {spawn} from 'node:child_process';
9
9
  const DENY=()=>{throw Error('DEVICE_DEV_AGENT_RUN_DENIED');};
10
10
  const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
11
- export function devAgentWorkerEnv({gatewayUrl,credentialFile,rootId,rootPath,mainFile,home},baseEnv=process.env,{
11
+ export function devAgentWorkerEnv({gatewayUrl,credentialFile,rootId,rootPath,mainFile,home,caFile},baseEnv=process.env,{
12
12
  os=process.platform,lstat=lstatSync,realpath=realpathSync,inspectWindows=inspectWindowsCredentialAcl
13
13
  }={}){
14
14
  let gateway;try{gateway=new URL(gatewayUrl);}catch{DENY();}
15
15
  const loopback=['127.0.0.1','localhost','[::1]'].includes(gateway?.hostname);
16
16
  const publicDevGateway=gateway?.protocol==='https:'&&gateway?.hostname==='ailab-remoteshell.duckdns.org'&&
17
17
  gateway?.pathname==='/gateway/v1/';
18
+ const isolatedDevGateway=gateway?.protocol==='https:'&&caFile&&gateway?.pathname==='/gateway/v1/';
18
19
  if(!gateway||gateway.username||gateway.password||gateway.search||gateway.hash||
19
- (gateway.pathname!=='/'&&!publicDevGateway)||
20
+ (gateway.pathname!=='/'&&!publicDevGateway&&!isolatedDevGateway)||
20
21
  !(gateway.protocol==='https:'||gateway.protocol==='http:'&&loopback)||
21
22
  !UUID.test(rootId||''))DENY();
23
+ if(caFile!==undefined){
24
+ if(gateway.protocol!=='https:'||typeof caFile!=='string'||!caFile.startsWith('/')||
25
+ resolve(caFile)!==caFile||os==='win32')DENY();
26
+ try{
27
+ const parentPath=dirname(caFile),parent=lstat(parentPath),parentCanonical=realpath(parentPath);
28
+ const f=lstat(caFile),canonical=realpath(caFile);
29
+ if(!parent.isDirectory()||parent.isSymbolicLink()||parent.uid!==process.getuid?.()||
30
+ (parent.mode&0o777)!==0o700||parentCanonical!==parentPath||
31
+ !f.isFile()||f.isSymbolicLink()||f.uid!==process.getuid?.()||
32
+ (f.mode&0o077)!==0||f.size<1||f.size>65536||canonical!==caFile)DENY();
33
+ }catch{DENY();}
34
+ }
22
35
  if(os==='win32'){
23
36
  try{
24
37
  for(const p of [home,rootPath,credentialFile,mainFile])canonicalWindowsLocalFile(p);
@@ -45,12 +58,23 @@ export function devAgentWorkerEnv({gatewayUrl,credentialFile,rootId,rootPath,mai
45
58
  entry.isSymbolicLink()||!entry.isFile())DENY();
46
59
  }catch{DENY();}
47
60
  }else DENY();
61
+ // Built-in Windows whoami/cscript ACL validators need actual profile paths.
62
+ // Do not inherit arbitrary parent environment values or weaken ACL checks.
63
+ const windowsEnv=os==='win32'?{
64
+ SystemRoot:baseEnv.SystemRoot||'C:\\Windows',WINDIR:baseEnv.SystemRoot||'C:\\Windows',
65
+ USERPROFILE:home,APPDATA:win32.join(home,'AppData','Roaming'),
66
+ LOCALAPPDATA:win32.join(home,'AppData','Local'),
67
+ TEMP:win32.join(home,'AppData','Local','Temp'),TMP:win32.join(home,'AppData','Local','Temp'),
68
+ HOMEDRIVE:home.slice(0,2),HOMEPATH:home.slice(2),
69
+ ProgramData:win32.join(win32.parse(home).root,'ProgramData')
70
+ }:{};
48
71
  return Object.freeze({PATH:baseEnv.PATH||baseEnv.Path||(os==='win32'?'':'/usr/bin:/bin'),HOME:home,
49
- ...(os==='win32'?{SystemRoot:baseEnv.SystemRoot||'C:\\Windows'}:{}),RS_P2_MODE:'true',
72
+ ...windowsEnv,RS_P2_MODE:'true',
50
73
  RS_55A_TEST_MODE:'true',RS_55A_ROOT:'.',RS_55B_TEST_MODE:'false',RS_55C1_TEST_MODE:'false',
51
74
  RS_L2_DEV_AGENT:'true',RS_L2_DEV_CREDENTIAL_FILE:credentialFile,RS_GATEWAY_URL:gateway.href,
52
75
  ...(gateway.protocol==='https:'?{RS_ENABLE_REMOTE:'true'}:{}),
53
- RS_L2_D1_ROOT_ID:rootId,RS_L2_D1_ROOT:rootPath});
76
+ RS_L2_D1_ROOT_ID:rootId,RS_L2_D1_ROOT:rootPath,
77
+ ...(caFile?{RS_CA_FILE:caFile}:{})});
54
78
  }
55
79
  export function runDevAgentWorker(options,{spawnImpl=spawn,baseEnv=process.env,nodeBin=process.execPath}={}){
56
80
  const env=devAgentWorkerEnv(options,baseEnv),child=spawnImpl(nodeBin,[options.mainFile],{
File without changes
@@ -4,11 +4,11 @@ import {join} from 'node:path';
4
4
  import {devOfficialRegistration} from './dev-agent-client.mjs';
5
5
  import {runDevAgentWorker} from './dev-agent-runner.mjs';
6
6
  export const OFFICIAL_DEV_GATEWAY='https://ailab-remoteshell.duckdns.org/gateway/v1/';
7
- export function officialWorkerOptions({home,install,storageDir}={}){
7
+ export function officialWorkerOptions({home,install,storageDir,gatewayUrl=OFFICIAL_DEV_GATEWAY,caFile}={}){
8
8
  const registration=devOfficialRegistration({storageDir});
9
9
  if(!registration)return null;
10
10
  return Object.freeze({
11
- gatewayUrl:OFFICIAL_DEV_GATEWAY,credentialFile:join(storageDir,'device.json'),
11
+ gatewayUrl, ...(caFile?{caFile}:{}),credentialFile:join(storageDir,'device.json'),
12
12
  rootId:registration.deviceId,rootPath:home,home,
13
13
  mainFile:join(install,'node_modules/@remoteshell/device/src/device-agent/main.mjs')
14
14
  });
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
package/bin/device.mjs CHANGED
@@ -280,7 +280,7 @@ try{
280
280
  devLocalStatus({storageDir:join(p.base,'dev-credentials')});
281
281
  const mainFile=join(p.install,'node_modules/@remoteshell/device/src/device-agent/main.mjs');
282
282
  const child=runDevAgentWorker({gatewayUrl:process.argv[3],credentialFile,rootId,rootPath,
283
- mainFile,home:homedir()});
283
+ mainFile,home:homedir(),...(process.env.RS_DEV_AGENT_CA_FILE?{caFile:process.env.RS_DEV_AGENT_CA_FILE}:{})});
284
284
  child.once('error',()=>deny('DEVICE_DEV_AGENT_RUN_DENIED'));
285
285
  child.once('exit',(code,signal)=>{if(signal)process.kill(process.pid,signal);else process.exitCode=code??1;});
286
286
  }
@@ -378,7 +378,7 @@ try{
378
378
  process.exitCode=2;
379
379
  }else{console.error('Usage: remoteshell-device version|install|setup https://host/dev/ [foreground|manual|login|boot --confirm-linger]|dev-run-once|dev-mode manual|login|boot [--confirm-linger]|dev-start|dev-stop|dev-status|dev-autostart-enable|dev-autostart-disable|status|dev-service-uninstall|uninstall|dev-check https://host/dev/|dev-enroll https://host/dev/ ENROLLMENT_ID < capability-file|dev-heartbeat|dev-heartbeat-once|dev-agent-run GATEWAY_URL ROOT_ID ABSOLUTE_ROOT');process.exitCode=2;}
380
380
  }catch(e){
381
- const codes=new Set(['DEVICE_INSTALL_DENIED','DEVICE_INSTALL_MANIFEST_DENIED','DEVICE_INSTALL_TRUST_ANCHOR_INVALID','DEVICE_INSTALL_TRUST_ANCHOR_MISSING','DEVICE_INSTALL_SIGNATURE_DENIED','DEVICE_INSTALL_CHECKSUM_DENIED','DEVICE_INSTALL_ARTIFACT_DENIED','DEVICE_INSTALL_VERSION_DENIED','DEVICE_INSTALL_VERSION_REVIEW_REQUIRED','DEVICE_INSTALL_DOWNGRADE_DENIED','DEVICE_INSTALL_DOWNLOAD_DENIED','DEVICE_INSTALL_DOWNLOAD_TIMEOUT','DEVICE_INSTALL_DOWNLOAD_TOO_LARGE','DEVICE_INSTALL_STATE_DENIED','DEVICE_PLATFORM_UNSUPPORTED','DEVICE_INSTALL_OS_UNSUPPORTED','DEVICE_INSTALL_WSL_BETA_EXCLUDED','DEVICE_INSTALL_NODE_UNSUPPORTED','DEVICE_ALREADY_INSTALLED','DEVICE_DEPENDENCY_INVALID','DEVICE_INSTALL_DEPENDENCY_FAILED','DEVICE_INSTALL_PACKAGE_FAILED','DEVICE_LIFECYCLE_DENIED','DEVICE_WINDOWS_LIFECYCLE_DENIED','DEVICE_WINDOWS_WORKER_NOT_READY','DEVICE_WINDOWS_LAYOUT_DENIED','DEVICE_WINDOWS_PRIVATE_STORE_DENIED','DEVICE_ALREADY_REGISTERED','DEVICE_WINDOWS_INSTALL_DENIED','DEVICE_ENROLLMENT_DENIED','DEVICE_DEV_PROBE_DENIED','DEVICE_DEV_AGENT_DENIED','DEVICE_DEV_ENROLLMENT_INPUT_DENIED','DEVICE_UNIT_MUST_BE_REMOVED_FIRST','DEVICE_PAIRING_DENIED','DEVICE_REREGISTRATION_CONFIRM_REQUIRED','DEVICE_REREGISTRATION_CANCELLED','DEVICE_DEV_CREDENTIAL_REVOKED','DEVICE_DEV_SERVICE_DENIED','L2_DEV_CREDENTIAL_DENIED','DEVICE_DIRECT_PLATFORM_DENIED','DEVICE_DIRECT_LEGACY_INSTALLED','DEVICE_DIRECT_OWNER_DENIED','DEVICE_DIRECT_LOCK_DENIED','DEVICE_DIRECT_ALREADY_RUNNING','DEVICE_DIRECT_STALE_LOCK','DEVICE_DIRECT_REGISTRATION_REQUIRED','DEVICE_DIRECT_PACKAGE_INVALID','DEVICE_DIRECT_EXISTING_SERVICE','DEVICE_DIRECT_SERVICE_UNVERIFIED','DEVICE_DIRECT_SERVICE_TIMEOUT','DEVICE_DIRECT_AUTOSTART_DENIED']);
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','DEVICE_WINDOWS_ACL_TIMEOUT']);
382
382
  console.error(codes.has(e.message)?e.message:'DEVICE_INSTALL_DENIED');
383
383
  process.exitCode=1;
384
384
  }
@@ -60,9 +60,24 @@ function privateLockDir(p){
60
60
  }
61
61
  return p.storageDir;
62
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
- }}={}){
63
+ // Windows may return EPERM to an ordinary user for an already-exited PID.
64
+ // Reclaim a stale lock only if an independent OS query proves PID absence.
65
+ // Any uncertainty (access denial, timeout, malformed PID, probe error) stays fail-closed.
66
+ export function directLockPidAlive(id,{os=platform(),kill=process.kill.bind(process),run=spawnSync}={}){
67
+ if(!Number.isSafeInteger(id)||id<=1)return true;
68
+ try{kill(id,0);return true;}catch(e){
69
+ if(e?.code==='ESRCH')return false;
70
+ if(e?.code!=='EPERM'||os!=='win32')return true;
71
+ }
72
+ const binary=win32.join(process.env.SystemRoot||'C:\\Windows','System32','WindowsPowerShell','v1.0','powershell.exe');
73
+ const command=`try { Get-Process -Id ${id} -ErrorAction Stop | Out-Null; exit 10 } catch [Microsoft.PowerShell.Commands.ProcessCommandException] { exit 11 } catch { exit 12 }`;
74
+ let result;
75
+ try{result=run(binary,['-NoProfile','-NonInteractive','-Command',command],{
76
+ shell:false,windowsHide:true,encoding:'utf8',timeout:20000,maxBuffer:4096,stdio:'pipe'
77
+ });}catch{return true;}
78
+ return !(result?.status===11&&!result.error&&!result.signal);
79
+ }
80
+ export function acquireDirectLock(p,{pid=process.pid,alive=directLockPidAlive}={}){
66
81
  const dir=privateLockDir(p),lock=join(dir,'direct-run.lock'),reap=join(dir,'direct-run.reap.lock');
67
82
  const nonce=randomUUID();
68
83
  const create=()=>{
@@ -84,6 +99,7 @@ export function acquireDirectLock(p,{pid=process.pid,alive=id=>{
84
99
  };
85
100
  };
86
101
  try{return create();}catch(e){
102
+ if(e?.message==='DEVICE_WINDOWS_ACL_TIMEOUT')throw e;
87
103
  if(e.code!=='EEXIST')FAIL('DEVICE_DIRECT_LOCK_DENIED');
88
104
  }
89
105
  // Windows logoff/reboot and Linux systemd can kill the npm wrapper before
@@ -102,10 +118,10 @@ export function acquireDirectLock(p,{pid=process.pid,alive=id=>{
102
118
  bytes=readFileSync(lock,'utf8');prior=JSON.parse(bytes);
103
119
  if(!Number.isSafeInteger(prior?.pid)||prior.pid<=1)
104
120
  FAIL('DEVICE_DIRECT_STALE_LOCK');
105
- }catch{FAIL('DEVICE_DIRECT_STALE_LOCK');}
121
+ }catch(e){if(e?.message==='DEVICE_WINDOWS_ACL_TIMEOUT')throw e;FAIL('DEVICE_DIRECT_STALE_LOCK');}
106
122
  if(alive(prior.pid))FAIL('DEVICE_DIRECT_ALREADY_RUNNING');
107
123
  let mutex;
108
- try{mutex=openSync(reap,'wx',0o600);}catch{FAIL('DEVICE_DIRECT_STALE_LOCK');}
124
+ try{mutex=openSync(reap,'wx',0o600);}catch(e){if(e?.message==='DEVICE_WINDOWS_ACL_TIMEOUT')throw e;FAIL('DEVICE_DIRECT_STALE_LOCK');}
109
125
  try{
110
126
  const current=lstatSync(lock);
111
127
  if(current.dev!==snapshot.dev||current.ino!==snapshot.ino||
@@ -121,6 +137,7 @@ export function acquireDirectLock(p,{pid=process.pid,alive=id=>{
121
137
  rmSync(reap,{force:true});
122
138
  }
123
139
  try{return create();}catch(e){
140
+ if(e?.message==='DEVICE_WINDOWS_ACL_TIMEOUT')throw e;
124
141
  if(e.code==='EEXIST')FAIL('DEVICE_DIRECT_ALREADY_RUNNING');
125
142
  FAIL('DEVICE_DIRECT_LOCK_DENIED');
126
143
  }
@@ -133,23 +150,57 @@ export async function directRegister(p,{pair=devPairDevice,onApprove=url=>consol
133
150
  const result=await pair({base:DIRECT_DEV_URL,storageDir:p.storageDir,onApprove});
134
151
  return {...result,reused:false};
135
152
  }
136
- export async function directRun(p,{packageRoot,runWorker=runDevAgentWorker,guard=requireNoLegacyInstall}={}){
153
+ export async function directRun(p,{packageRoot,runWorker=runDevAgentWorker,guard=requireNoLegacyInstall,onStage,lock=acquireDirectLock,registrationProof=devOfficialRegistration,wait=ms=>new Promise(resolve=>setTimeout(resolve,ms))}={}){
154
+ const started=Date.now();
155
+ const stage=name=>{if(p.os!=='win32'&&!onStage)return;
156
+ const event=Object.freeze({stage:name,elapsed_ms:Math.max(0,Date.now()-started)});
157
+ try{if(onStage)onStage(event);else console.error('RS_S3_DIRECT_STARTUP '+JSON.stringify(event))}catch{}
158
+ };
159
+ stage('preflight_begin');
137
160
  guard(p);
138
- const registration=devOfficialRegistration({storageDir:p.storageDir});
161
+ stage('preflight_ok');
162
+ // Under Windows CPU contention, an otherwise valid private ACL proof can
163
+ // time out. Only that explicit native timeout permits a fresh bounded proof.
164
+ // Missing/revoked/malformed registration remains fail-closed.
165
+ let registration;
166
+ for(let attempt=1;attempt<=3;attempt++){
167
+ try{registration=registrationProof({storageDir:p.storageDir});break;}
168
+ catch(e){
169
+ if(p.os!=='win32'||e?.message!=='DEVICE_WINDOWS_ACL_TIMEOUT'||attempt===3)throw e;
170
+ stage('registration_acl_timeout_retry');
171
+ await wait(1500*attempt);
172
+ }
173
+ }
139
174
  if(!registration)FAIL('DEVICE_DIRECT_REGISTRATION_REQUIRED');
175
+ stage('registration_ok');
140
176
  const mainFile=join(packageRoot,'src/device-agent/main.mjs');
141
177
  if(!existsSync(mainFile))FAIL('DEVICE_DIRECT_PACKAGE_INVALID');
142
- const release=acquireDirectLock(p);
178
+ stage('package_ok');
179
+ // Slow Windows native ACL checks may time out under CPU contention.
180
+ // Retry only explicit timeout; each attempt performs a fresh full proof.
181
+ // ACL denial, malformed ownership and active locks are never retried.
182
+ let release;
183
+ for(let attempt=1;attempt<=3;attempt++){
184
+ try{release=lock(p);break;}
185
+ catch(e){
186
+ if(p.os!=='win32'||e?.message!=='DEVICE_WINDOWS_ACL_TIMEOUT'||attempt===3)throw e;
187
+ stage('lock_acl_timeout_retry');
188
+ await wait(1500*attempt);
189
+ }
190
+ }
191
+ stage('lock_ok');
143
192
  // Also clean on normal process exit when the npm parent receives SIGTERM.
144
193
  process.once('exit',release);
145
194
  try{
195
+ stage('worker_validation_begin');
146
196
  const child=runWorker({gatewayUrl:GATEWAY,credentialFile:join(p.storageDir,'device.json'),
147
197
  rootId:registration.deviceId,rootPath:p.home,home:p.home,mainFile});
198
+ stage('worker_spawned');
148
199
  return await new Promise((ok,fail)=>{
149
200
  const onInt=()=>child.kill('SIGINT'),onTerm=()=>child.kill('SIGTERM');
150
201
  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});});
202
+ child.once('error',error=>{stage('worker_error');cleanup();fail(error);});
203
+ child.once('exit',(code,signal)=>{stage('worker_exit');cleanup();ok({exitCode:signal?1:(code??1),signal:signal||null});});
153
204
  process.once('SIGINT',onInt);process.once('SIGTERM',onTerm);
154
205
  });
155
206
  }finally{process.removeListener('exit',release);release();}
File without changes
File without changes
File without changes
File without changes
package/bin/lifecycle.mjs CHANGED
File without changes
File without changes
File without changes
File without changes
@@ -0,0 +1,54 @@
1
+ # #327 A: private verified Windows kit -> pinned npx.cmd; no legacy install.
2
+ param([switch]$CheckOnly,[switch]$Preflight,[switch]$Register,[switch]$Run)
3
+ $ErrorActionPreference='Stop'
4
+ $ProgressPreference='SilentlyContinue'
5
+ function Deny([string]$code,[int]$rc=1){[Console]::Error.WriteLine($code);exit $rc}
6
+ $selection=@($CheckOnly.IsPresent,$Preflight.IsPresent,$Register.IsPresent,$Run.IsPresent)|Where-Object {$_}
7
+ if($selection.Count -gt 1){Deny 'DEVICE_NPX_ARGS_DENIED' 2}
8
+ if($selection.Count -eq 0){$Preflight=$true}
9
+ $source=Split-Path -Parent $MyInvocation.MyCommand.Path
10
+ $manifestPath=Join-Path $source 'manifest.json'
11
+ $node=Join-Path $source 'runtime\node.exe'
12
+ $npmCli=Join-Path $source 'runtime\node_modules\npm\bin\npm-cli.js'
13
+ $npx=Join-Path $source 'runtime\npx.cmd'
14
+ $archive=Join-Path $source 'agent.tgz'
15
+ try {
16
+ if(-not(Test-Path -LiteralPath $manifestPath -PathType Leaf)){Deny 'DEVICE_NPX_MANIFEST_MISSING'}
17
+ $manifest=Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json
18
+ if($manifest.schema -ne 1 -or $manifest.platform -ne 'win32' -or $manifest.arch -ne 'x64' -or $manifest.devOnly -ne $true){Deny 'DEVICE_NPX_MANIFEST_DENIED'}
19
+ if([Environment]::Is64BitOperatingSystem -ne $true){Deny 'DEVICE_NPX_ARCH_DENIED'}
20
+ $files=@{node=$node;npm=$npmCli;npx=$npx;archive=$archive}
21
+ foreach($key in @('node','npm','npx','archive')){
22
+ if(-not(Test-Path -LiteralPath $files[$key] -PathType Leaf)){Deny ('DEVICE_NPX_FILE_MISSING_'+$key)}
23
+ $hash=(Get-FileHash -LiteralPath $files[$key] -Algorithm SHA256).Hash.ToLowerInvariant()
24
+ if($hash -ne $manifest.sha256.$key){Deny ('DEVICE_NPX_HASH_DENIED_'+$key)}
25
+ }
26
+ $v=& $node --version
27
+ if($LASTEXITCODE -ne 0 -or $v -notmatch '^v22\.'){Deny 'NODE22_REQUIRED'}
28
+ & $node $npmCli --version | Out-Null
29
+ if($LASTEXITCODE -ne 0){Deny 'NPM_BUNDLE_INVALID'}
30
+ if($CheckOnly){Write-Host 'DEVICE_NPX_CHECK_PASS';exit 0}
31
+ $local=[Environment]::GetFolderPath('LocalApplicationData')
32
+ if(-not $local -or -not(Test-Path -LiteralPath $local -PathType Container)){Deny 'DEVICE_HOME_DENIED'}
33
+ $userHome=[Environment]::GetFolderPath('UserProfile')
34
+ if(-not $userHome -or -not(Test-Path -LiteralPath $userHome -PathType Container)){Deny 'DEVICE_HOME_DENIED'}
35
+ $disk=[IO.Path]::GetPathRoot($local)
36
+ $free=([IO.DriveInfo]::new($disk)).AvailableFreeSpace
37
+ if($free -lt 3GB){Deny 'DEVICE_NPX_SPACE_DENIED'}
38
+ $action=if($Preflight){'install-preflight'}elseif($Register){'register'}else{'run'}
39
+ if($Register -or $Run){
40
+ $identity=[Security.Principal.WindowsIdentity]::GetCurrent()
41
+ $principal=New-Object Security.Principal.WindowsPrincipal($identity)
42
+ if($identity.IsSystem -or $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)){Deny 'DEVICE_NPX_USER_REQUIRED'}
43
+ }
44
+ $env:PATH=(Join-Path $source 'runtime')+';'+$env:PATH
45
+ $env:npm_config_ignore_scripts='true'
46
+ $env:npm_config_audit='false'
47
+ $env:npm_config_fund='false'
48
+ # npx.cmd delegates to the same npm exec core used by direct Windows npx.
49
+ & $npx '--yes' ('--package=file:'+$archive) '--' 'remoteshell-device' $action
50
+ exit $LASTEXITCODE
51
+ }catch{
52
+ [Console]::Error.WriteLine('DEVICE_NPX_ENTRY_FAILED')
53
+ exit 1
54
+ }
@@ -0,0 +1,34 @@
1
+ #!/bin/sh
2
+ # #327 A: private verified kit -> the one npx CLI, without legacy install/setup.
3
+ set -eu
4
+ umask 077
5
+ case "${1:---preflight}" in
6
+ --check-only) action=check ;;
7
+ --preflight) action=install-preflight ;;
8
+ --register) action=register ;;
9
+ --run) action=run ;;
10
+ *) echo DEVICE_NPX_ARGS_DENIED >&2; exit 2 ;;
11
+ esac
12
+ [ "$#" -le 1 ] || { echo DEVICE_NPX_ARGS_DENIED >&2; exit 2; }
13
+ [ "$(id -u)" -ne 0 ] || { echo DO_NOT_RUN_AS_ROOT >&2; exit 1; }
14
+ [ "$(uname -s)" = Linux ] && [ "$(uname -m)" = x86_64 ] || { echo DEVICE_PLATFORM_DENIED >&2; exit 1; }
15
+ case "$(cat /proc/version 2>/dev/null || true)" in *icrosoft*|*WSL*) echo WSL_BETA_EXCLUDED >&2; exit 1;; esac
16
+ base=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
17
+ [ -n "${HOME:-}" ] && [ -d "$HOME" ] && [ "$HOME" != / ] || { echo DEVICE_HOME_DENIED >&2; exit 1; }
18
+ [ "$(stat -c %u "$HOME")" = "$(id -u)" ] && [ ! -L "$HOME" ] || { echo DEVICE_HOME_OWNER_DENIED >&2; exit 1; }
19
+ for file in manifest.sha256 runtime/node runtime/node_modules/npm/bin/npx-cli.js agent.tgz; do
20
+ [ -f "$base/$file" ] && [ ! -L "$base/$file" ] || { echo DEVICE_NPX_KIT_MISSING >&2; exit 1; }
21
+ done
22
+ (cd "$base" && sha256sum -c manifest.sha256 >/dev/null) || { echo DEVICE_NPX_HASH_DENIED >&2; exit 1; }
23
+ case "$("$base/runtime/node" --version)" in v22.*) :;; *) echo NODE22_REQUIRED >&2; exit 1;; esac
24
+ "$base/runtime/node" "$base/runtime/node_modules/npm/bin/npm-cli.js" --version >/dev/null 2>&1 || { echo NPM_BUNDLE_INVALID >&2; exit 1; }
25
+ "$base/runtime/node" "$base/runtime/node_modules/npm/bin/npx-cli.js" --version >/dev/null 2>&1 || { echo NPX_BUNDLE_INVALID >&2; exit 1; }
26
+ [ "$action" != check ] || { echo DEVICE_NPX_CHECK_PASS; exit 0; }
27
+ free_kb=$(df -Pk "$HOME" | awk 'END{print $4}')
28
+ free_inodes=$(df -Pi "$HOME" | awk 'END{print $4}')
29
+ [ "${free_kb:-0}" -ge 3145728 ] && [ "${free_inodes:-0}" -ge 10000 ] || { echo DEVICE_NPX_SPACE_DENIED >&2; exit 1; }
30
+ # The package is private and unpublished; use its exact verified local bytes.
31
+ # Preserve the user's existing credentials and autostart. Register is explicit.
32
+ export PATH="$base/runtime:$PATH"
33
+ export npm_config_ignore_scripts=true npm_config_audit=false npm_config_fund=false
34
+ exec "$base/runtime/node" "$base/runtime/node_modules/npm/bin/npx-cli.js" --yes "--package=file:$base/agent.tgz" -- remoteshell-device "$action"
@@ -0,0 +1,61 @@
1
+ // #327 S3: retrieve the exact npm tarball only after signed release approval.
2
+ // This module does not install, execute, or switch a running Agent.
3
+ import {createHash,timingSafeEqual} from 'node:crypto';
4
+ import {validateRegistryUpdateMetadata} from './safe-update-contract.mjs';
5
+
6
+ const DENY=()=>{throw Error('DEVICE_SAFE_UPDATE_ARTIFACT_DENIED');};
7
+ const LIMIT=32*1024*1024;
8
+ const OFFICIAL='registry.npmjs.org';
9
+
10
+ export function exactTarballUrl(approved,metadata){
11
+ validateRegistryUpdateMetadata(approved,metadata);
12
+ const uri=metadata?.dist?.tarball;
13
+ if(typeof uri!=='string'||uri.length>512)DENY();
14
+ let u;
15
+ try{u=new URL(uri)}catch{DENY()}
16
+ const expected='/@remoteshell/device/-/device-'+approved.version+'.tgz';
17
+ if(u.protocol!=='https:'||u.hostname!==OFFICIAL||u.port||
18
+ u.username||u.password||u.search||u.hash||u.pathname!==expected)DENY();
19
+ return u.toString();
20
+ }
21
+
22
+ export function verifyTarballBytes(approved,metadata,bytes){
23
+ exactTarballUrl(approved,metadata);
24
+ if(!Buffer.isBuffer(bytes)||bytes.length<20||bytes.length>LIMIT)DENY();
25
+ const wanted=Buffer.from(approved.sha512.slice('sha512-'.length),'base64');
26
+ const got=createHash('sha512').update(bytes).digest();
27
+ if(wanted.length!==64||got.length!==64||!timingSafeEqual(got,wanted))DENY();
28
+ // npm tgz is gzip, not a serialized command or arbitrary response body.
29
+ if(bytes[0]!==0x1f||bytes[1]!==0x8b||bytes[2]!==0x08)DENY();
30
+ return Object.freeze({version:approved.version,bytes:bytes.length,
31
+ integrity:approved.sha512,verified:true});
32
+ }
33
+ export async function retrieveVerifiedTarball(approved,metadata,{
34
+ fetcher=fetch,timeoutMs=30000
35
+ }={}){
36
+ const uri=exactTarballUrl(approved,metadata);
37
+ if(!Number.isSafeInteger(timeoutMs)||timeoutMs<1000||timeoutMs>120000)DENY();
38
+ let response;
39
+ try{
40
+ response=await fetcher(uri,{method:'GET',redirect:'error',
41
+ signal:AbortSignal.timeout(timeoutMs)});
42
+ }catch{DENY()}
43
+ if(!response||response.ok!==true||response.status!==200||!response.body)DENY();
44
+ const type=response.headers?.get?.('content-type')||'';
45
+ if(type&&!/^(application\/octet-stream|application\/x-gzip|application\/gzip)(;|$)/i.test(type))DENY();
46
+ const hint=response.headers?.get?.('content-length');
47
+ if(hint!==null&&hint!==undefined&&(!/^\d+$/.test(hint)||Number(hint)>LIMIT))DENY();
48
+ const pieces=[];
49
+ let size=0;
50
+ try{
51
+ for await(const part of response.body){
52
+ if(!(part instanceof Uint8Array)||part.length===0)DENY();
53
+ size+=part.length;
54
+ if(size>LIMIT)DENY();
55
+ pieces.push(Buffer.from(part));
56
+ }
57
+ }catch{DENY()}
58
+ const result=Buffer.concat(pieces,size);
59
+ return Object.freeze({receipt:verifyTarballBytes(approved,metadata,result),
60
+ bytes:result});
61
+ }
@@ -0,0 +1,78 @@
1
+ // #327 S3: verified-update decision gate. No automatic registry dist-tag trust.
2
+ // Only a separately authenticated, signed release intent can authorize updates.
3
+ // An untrusted npm version string, web response, or user-writable manifest never can.
4
+ import {verify,createPublicKey,createHash} from 'node:crypto';
5
+ import {isAuthenticatedCiApproval} from './ci-backed-update-approval.mjs';
6
+
7
+ const DENY=()=>{throw Error('DEVICE_SAFE_UPDATE_DENIED');};
8
+ const VERSION=/^0\.1\.0-beta\.(\d{1,6})$/;
9
+ const SHA=/^[a-f0-9]{40}$/;
10
+ const DIGEST=/^sha512-([A-Za-z0-9+/]{86}==)$/;
11
+ const ID=/^[A-Za-z0-9_-]{1,64}$/;
12
+ const SAFE_PROPERTIES=['schema','package','channel','version','sourceSha','sha512','runId','publishedAt','expiresAt','keyId'];
13
+ const AUTHOR='lkhkhk/RemoteShell';
14
+ const PACKAGE='@remoteshell/device';
15
+
16
+ function parseVersion(s){
17
+ const match=VERSION.exec(s||'');
18
+ if(!match)DENY();
19
+ const n=Number(match[1]);
20
+ if(!Number.isSafeInteger(n)||String(n)!==match[1]||n<4)DENY();
21
+ return n;
22
+ }
23
+ function exactKeys(value,expected){
24
+ if(value===null||typeof value!=='object'||Array.isArray(value))DENY();
25
+ const keys=Object.keys(value).sort(),allowed=[...expected].sort();
26
+ if(JSON.stringify(keys)!==JSON.stringify(allowed))DENY();
27
+ }
28
+ export function validatedUpdateIntent(value,{currentVersion,now=Date.now()}={}){
29
+ exactKeys(value,[...SAFE_PROPERTIES,'signature']);
30
+ if(value.schema!==1||value.package!==PACKAGE||value.channel!=='beta'||!SHA.test(value.sourceSha||'')||
31
+ !DIGEST.test(value.sha512||'')||!ID.test(value.keyId||'')||
32
+ typeof value.runId!=='string'||!/^[1-9]\d{6,15}$/.test(value.runId))DENY();
33
+ const prior=parseVersion(currentVersion),next=parseVersion(value.version);
34
+ if(next<=prior)DENY(); // rollback version is never an automatic update proposal
35
+ if(!Number.isSafeInteger(now))DENY();
36
+ const issued=Date.parse(value.publishedAt),expiry=Date.parse(value.expiresAt);
37
+ if(!Number.isFinite(issued)||!Number.isFinite(expiry)||issued>now+300000||
38
+ now>=expiry||expiry-issued>7*86400000||expiry<=issued)DENY();
39
+ if(typeof value.signature!=='string'||!/^[A-Za-z0-9+/]{86}==$/.test(value.signature))DENY();
40
+ return Object.freeze({...value,previousVersion:currentVersion});
41
+ }
42
+ export function canonicalUpdateIntent(value){
43
+ const data={};
44
+ for(const k of SAFE_PROPERTIES)data[k]=value[k];
45
+ return Buffer.from(JSON.stringify(data)+'\n','utf8');
46
+ }
47
+ export function verifySignedUpdateIntent(value,{currentVersion,now=Date.now(),trustedPublicKeys}={}){
48
+ const intent=validatedUpdateIntent(value,{currentVersion,now});
49
+ const pem=trustedPublicKeys?.[intent.keyId];
50
+ if(typeof pem!=='string'||pem.length>4096)DENY();
51
+ let key;
52
+ try{key=createPublicKey(pem)}catch{DENY()}
53
+ if(key.asymmetricKeyType!=='ed25519')DENY();
54
+ let ok=false;
55
+ try{ok=verify(null,canonicalUpdateIntent(intent),key,Buffer.from(intent.signature,'base64'))}catch{DENY()}
56
+ if(!ok)DENY();
57
+ return Object.freeze({
58
+ package:intent.package,version:intent.version,previousVersion:currentVersion,
59
+ sourceSha:intent.sourceSha,sha512:intent.sha512,runId:intent.runId,
60
+ proof:'ed25519-approved-release-intent'
61
+ });
62
+ }
63
+ export function validateRegistryUpdateMetadata(approved,metadata){
64
+ if(!approved||(approved.proof!=='ed25519-approved-release-intent'&&
65
+ !isAuthenticatedCiApproval(approved))||!metadata)DENY();
66
+ if(metadata.name!==approved.package||metadata.version!==approved.version||
67
+ metadata.dist?.integrity!==approved.sha512)DENY();
68
+ // Registry responses can corroborate integrity; they cannot independently approve.
69
+ return Object.freeze({version:approved.version,previousVersion:approved.previousVersion,
70
+ integrity:approved.sha512,sourceSha:approved.sourceSha,verified:true});
71
+ }
72
+ export function safeUpdateDecision({approved,registry,cachedVersion,connected,healthy,credentialsSame}={}){
73
+ const check=validateRegistryUpdateMetadata(approved,registry);
74
+ if(cachedVersion!==check.version) return Object.freeze({action:'stage-exact-version',version:check.version});
75
+ if(!connected||!healthy||credentialsSame!==true)
76
+ return Object.freeze({action:'rollback',version:check.previousVersion,reason:'health-or-credential-check'});
77
+ return Object.freeze({action:'commit',version:check.version,previousVersion:check.previousVersion});
78
+ }