@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
@@ -0,0 +1,62 @@
1
+ // #327 S3: POSIX-only staging of already verified npm archive bytes.
2
+ // No extraction, execution, activation, or credential access occurs here.
3
+ import {createHash,timingSafeEqual,randomBytes} from 'node:crypto';
4
+ import {lstatSync,mkdirSync,openSync,writeSync,fsyncSync,closeSync,linkSync,unlinkSync,readFileSync,realpathSync,constants} from 'node:fs';
5
+ import {resolve,join,dirname} from 'node:path';
6
+ import {verifyTarballBytes} from './safe-update-artifact.mjs';
7
+ const DENY=()=>{throw Error('DEVICE_SAFE_UPDATE_STAGE_DENIED');};
8
+ const VERSION=/^0\.1\.0-beta\.(?:[1-9][0-9]{0,5})$/;
9
+ function privateDirectory(path){
10
+ const st=lstatSync(path);
11
+ if(!st.isDirectory()||st.isSymbolicLink()||st.uid!==process.getuid()||
12
+ (st.mode&0o077)!==0||realpathSync(path)!==path)DENY();
13
+ }
14
+ function safeRoot(path){
15
+ if(process.platform==='win32'||typeof process.getuid!=='function'||
16
+ typeof path!=='string'||!path.startsWith('/')||resolve(path)!==path||path==='/')DENY();
17
+ // Do not follow a symlinked parent, even when the child does not yet exist.
18
+ const parent=dirname(path);
19
+ privateDirectory(parent);
20
+ try{mkdirSync(path,{mode:0o700})}catch(e){if(e.code!=='EEXIST')DENY()}
21
+ privateDirectory(path);
22
+ return path;
23
+ }
24
+ function sameDigest(bytes,wanted){
25
+ const digest=createHash('sha512').update(bytes).digest();
26
+ const expected=Buffer.from(wanted.slice(7),'base64');
27
+ return expected.length===64&&timingSafeEqual(digest,expected);
28
+ }
29
+ export function stageVerifiedTarball(approved,metadata,bytes,{directory}={}){
30
+ try{
31
+ verifyTarballBytes(approved,metadata,bytes);
32
+ if(!VERSION.test(approved.version||''))DENY();
33
+ const root=safeRoot(directory);
34
+ const dest=join(root,approved.version+'.tgz');
35
+ const tmp=join(root,'.staging-'+randomBytes(16).toString('hex'));
36
+ let fd;
37
+ try{
38
+ fd=openSync(tmp,'wx',0o600);
39
+ let off=0;
40
+ while(off<bytes.length){const n=writeSync(fd,bytes,off,bytes.length-off);if(n<=0)DENY();off+=n;}
41
+ fsyncSync(fd);closeSync(fd);fd=undefined;
42
+ // Atomic no-replace publication; rename would silently clobber an existing candidate.
43
+ try{
44
+ linkSync(tmp,dest);
45
+ // Persist the published directory entry before reporting staging success.
46
+ const dirFd=openSync(root,constants.O_RDONLY|constants.O_DIRECTORY);
47
+ try{fsyncSync(dirFd)}finally{closeSync(dirFd)}
48
+ }catch(e){
49
+ if(e.code!=='EEXIST')DENY();
50
+ const st=lstatSync(dest);
51
+ if(!st.isFile()||st.isSymbolicLink()||st.nlink!==1||st.uid!==process.getuid()||
52
+ (st.mode&0o077)!==0||st.size!==bytes.length||
53
+ !sameDigest(readFileSync(dest),approved.sha512))DENY();
54
+ }
55
+ }finally{if(fd!==undefined)closeSync(fd);try{unlinkSync(tmp)}catch(e){if(e.code!=='ENOENT')throw e;}}
56
+ const saved=lstatSync(dest);
57
+ if(!saved.isFile()||saved.isSymbolicLink()||saved.nlink!==1||
58
+ saved.uid!==process.getuid()||(saved.mode&0o077)!==0||saved.size!==bytes.length||
59
+ !sameDigest(readFileSync(dest),approved.sha512))DENY();
60
+ return Object.freeze({path:dest,version:approved.version,sha512:approved.sha512,verified:true,activated:false});
61
+ }catch{DENY()}
62
+ }
@@ -0,0 +1,50 @@
1
+ // #327 S3: pure, fail-closed per-user update journal transitions.
2
+ // A separate Windows ACL-protected persistence adapter applies the returned plan.
3
+ // No registry, credential, network, or process mutation in this module.
4
+ import {isAuthenticatedCiApproval} from './ci-backed-update-approval.mjs';
5
+ const DENY=()=>{throw Error('DEVICE_SAFE_UPDATE_TRANSITION_DENIED');};
6
+ const VERSION=/^0\.1\.0-beta\.([1-9]\d{0,5})$/;
7
+ const PHASES=['staged','activation-pending','health-pending','healthy','rolling-back','rolled-back'];
8
+ function validVersion(v){return typeof v==='string'&&VERSION.test(v);}
9
+ function validJournal(j){
10
+ if(!j||j.schema!==1||!PHASES.includes(j.phase)||!validVersion(j.candidate)||
11
+ !validVersion(j.previous)||!j.deviceId||!j.credentialFingerprint)DENY();
12
+ return j;
13
+ }
14
+ export function prepareTransition(approval,{deviceId,credentialFingerprint}={}){
15
+ if((approval?.proof!=='ed25519-approved-release-intent'&&
16
+ !isAuthenticatedCiApproval(approval))||
17
+ !validVersion(approval.version)||!validVersion(approval.previousVersion)||
18
+ Number(VERSION.exec(approval.version)[1])<=Number(VERSION.exec(approval.previousVersion)[1])||
19
+ typeof deviceId!=='string'||!/^[a-f0-9-]{36}$/.test(deviceId)||
20
+ typeof credentialFingerprint!=='string'||!/^[a-f0-9]{64}$/.test(credentialFingerprint))DENY();
21
+ return Object.freeze({schema:1,phase:'staged',candidate:approval.version,
22
+ previous:approval.previousVersion,deviceId,credentialFingerprint});
23
+ }
24
+ export function advanceTransition(j,event,proof={}){
25
+ validJournal(j);
26
+ const identityMatches=proof.deviceId===j.deviceId&&
27
+ proof.credentialFingerprint===j.credentialFingerprint;
28
+ let phase;
29
+ if(event==='stage-ready'&&j.phase==='staged')phase='activation-pending';
30
+ else if(event==='activated'&&j.phase==='activation-pending')phase='health-pending';
31
+ else if(event==='health-ok'&&j.phase==='health-pending'){
32
+ if(!identityMatches||proof.connected!==true||proof.dcReady!==true||
33
+ proof.usageVerified!==true||proof.oneAgent!==true)DENY();
34
+ phase='healthy';
35
+ }else if(event==='failure'&&['activation-pending','health-pending'].includes(j.phase))
36
+ phase='rolling-back';
37
+ else if(event==='restored'&&j.phase==='rolling-back'){
38
+ if(!identityMatches)DENY();
39
+ phase='rolled-back';
40
+ }else DENY();
41
+ return Object.freeze({...j,phase});
42
+ }
43
+ export function recoverTransition(j){
44
+ validJournal(j);
45
+ // Unfinished activation can never resume directly into candidate execution.
46
+ if(['activation-pending','health-pending','rolling-back'].includes(j.phase))
47
+ return Object.freeze({action:'restore-previous-pin',version:j.previous});
48
+ if(j.phase==='healthy')return Object.freeze({action:'retain-candidate-pin',version:j.candidate});
49
+ return Object.freeze({action:'retain-previous-pin',version:j.previous});
50
+ }
@@ -36,15 +36,41 @@ export function parseWmiAclRows(output,user,{directory=false}={}){
36
36
  }
37
37
  export function inspectWmiAcl(target,{directory=false,run=spawnSync}={}){
38
38
  const root=process.env.SystemRoot||'C:\\Windows';
39
- const call=(name,args,timeout)=>run(win32.join(root,'System32',name),args,{
40
- shell:false,windowsHide:true,encoding:'utf8',timeout,maxBuffer:8192,
41
- stdio:['ignore','pipe','pipe']});
42
- const who=call('whoami.exe',['/user','/fo','csv','/nh'],10000);
43
- if(who.error||who.signal||who.status!==0)DENY();
39
+ const call=(name,args,timeout,retryTimeout)=>{
40
+ const options={shell:false,windowsHide:true,encoding:'utf8',timeout,maxBuffer:8192,
41
+ stdio:['ignore','pipe','pipe']};
42
+ const tool=win32.join(root,'System32',name);
43
+ let result=run(tool,args,options);
44
+ // Retry only an OS process timeout, never malformed output, denied ACLs,
45
+ // unknown errors or a nonzero tool result. The second proof is independent.
46
+ if(result?.error?.code==='ETIMEDOUT'){
47
+ console.warn('RS_S3_ACL_WMI_RETRY',JSON.stringify({step:name==='whoami.exe'?'identity':'acl',reason:'timeout'}));
48
+ result=run(tool,args,{...options,timeout:retryTimeout});
49
+ }
50
+ return result;
51
+ };
52
+ // Report fixed reason codes only. Never expose the target path, SID,
53
+ // security descriptor, command arguments, or credential contents.
54
+ const reject=(step,reason)=>{
55
+ console.warn('RS_S3_ACL_WMI_DENIED',JSON.stringify({step,reason}));
56
+ DENY();
57
+ };
58
+ const status=(result,step)=>{
59
+ if(result?.error?.code==='ETIMEDOUT')throw Error('DEVICE_WINDOWS_ACL_TIMEOUT');
60
+ if(result?.error)return reject(step,'spawn_error');
61
+ if(result?.signal)return reject(step,'signal');
62
+ if(result?.status!==0)return reject(step,'exit_nonzero');
63
+ };
64
+ // Native whoami can take >10s on a disconnected but authenticated session.
65
+ // Give the verified token query a bounded 20s before the existing single retry.
66
+ const who=call('whoami.exe',['/user','/fo','csv','/nh'],20000,60000);
67
+ status(who,'identity');
44
68
  const user=String(who.stdout||'').match(/S-1-\d+(?:-\d+){1,15}/)?.[0];
45
- if(!SID.test(user||''))DENY();
69
+ if(!SID.test(user||''))reject('identity','invalid_identity');
46
70
  const script=fileURLToPath(new URL('./windows-acl-wmi.js',import.meta.url));
47
- const probe=call('cscript.exe',['//nologo',script,target,directory?'1':'0'],25000);
48
- if(probe.error||probe.signal||probe.status!==0)DENY();
49
- return parseWmiAclRows(probe.stdout,user,{directory});
71
+ const probe=call('cscript.exe',['//nologo',script,target,directory?'1':'0'],25000,75000);
72
+ status(probe,'acl');
73
+ try{return parseWmiAclRows(probe.stdout,user,{directory})}
74
+ catch{reject('acl','invalid_descriptor')}
75
+
50
76
  }
@@ -53,9 +53,10 @@ export function validateWindowsAclSnapshot(snapshot){
53
53
  }
54
54
  export function inspectWindowsCredentialAcl({
55
55
  file,home,os=process.platform,lstat=lstatSync,realpath=realpathSync,
56
- run=spawnSync
56
+ run=spawnSync,maxFileSize=8192
57
57
  }={}){
58
- if(os!=='win32')DENY();
58
+ if(os!=='win32'||!Number.isSafeInteger(maxFileSize)||
59
+ maxFileSize<1||maxFileSize>32*1024*1024)DENY();
59
60
  try{
60
61
  canonicalWindowsLocalFile(home);
61
62
  isWindowsChildPath(file,home);
@@ -65,7 +66,7 @@ export function inspectWindowsCredentialAcl({
65
66
  if(!root.isDirectory()||root.isSymbolicLink()||
66
67
  !dir.isDirectory()||dir.isSymbolicLink()||
67
68
  !stat.isFile()||stat.isSymbolicLink()||
68
- stat.nlink!==1||stat.size<1||stat.size>8192)DENY();
69
+ stat.nlink!==1||stat.size<1||stat.size>maxFileSize)DENY();
69
70
  if(win32.normalize(realpath(file)).toLowerCase()!==file.toLowerCase()||
70
71
  win32.normalize(realpath(parent)).toLowerCase()!==parent.toLowerCase())DENY();
71
72
  if(run===spawnSync){
@@ -86,7 +87,7 @@ export function inspectWindowsCredentialAcl({
86
87
  const snapshot=JSON.parse(child.stdout);
87
88
  validateWindowsAclSnapshot(snapshot?.parent);
88
89
  return validateWindowsAclSnapshot(snapshot?.file);
89
- }catch{DENY();}
90
+ }catch(error){if(error?.message==='DEVICE_WINDOWS_ACL_TIMEOUT')throw error;DENY();}
90
91
  }
91
92
 
92
93
  // Verify one directory's own protected ACL without creating any files.
@@ -109,5 +110,5 @@ export function inspectWindowsPrivateDirectoryAcl({directory,home,os=process.pla
109
110
  });
110
111
  if(child.error||child.signal||child.status!==0||typeof child.stdout!=='string'||child.stdout.length>8192)DENY();
111
112
  return validateWindowsAclSnapshot(JSON.parse(child.stdout)?.file);
112
- }catch{DENY();}
113
+ }catch(error){if(error?.message==='DEVICE_WINDOWS_ACL_TIMEOUT')throw error;DENY();}
113
114
  }
@@ -8,12 +8,55 @@ const root=dirname(fileURLToPath(import.meta.url));
8
8
  const FAIL=()=>{process.exitCode=1;};
9
9
  function validPath(x){return typeof x==='string'&&/^[A-Za-z]:\\/.test(x)&&
10
10
  !/[\r\n"'&|<>%]/.test(x)&&!x.split('\\').includes('..');}
11
+ // Only an explicit native Windows ACL scheduling timeout may be retried.
12
+ // A genuine authorization denial, update failure, or unknown exit is terminal.
13
+ export function isTransientStartupFailure({code,stderr}={}){
14
+ return Number.isInteger(code)&&code!==0&&typeof stderr==='string'&&
15
+ /(?:^|\r?\n)DEVICE_WINDOWS_ACL_TIMEOUT(?:\r?\n|$)/.test(stderr);
16
+ }
17
+ export function startupRetryDelay(attempt,random=Math.random){
18
+ if(!Number.isSafeInteger(attempt)||attempt<1||typeof random!=='function')
19
+ throw Error('DEVICE_STARTUP_RETRY_INVALID');
20
+ const jitter=Number(random());
21
+ if(!Number.isFinite(jitter)||jitter<0||jitter>=1)throw Error('DEVICE_STARTUP_RETRY_INVALID');
22
+ return Math.min(60000,10000*2**Math.min(attempt-1,3))+Math.floor(jitter*1000);
23
+ }
24
+ // S3: a crash during activation must never boot an unverified candidate.
25
+ // This self-contained guard is copied with the persistent runner on new installs.
26
+ export function resolveStartupVersion(config,journal){
27
+ if(!config||typeof config.version!=='string'||!/^0\.1\.0-beta\.[1-9]\d*$/.test(config.version))
28
+ throw Error('DEVICE_DIRECT_AUTOSTART_CONFIG_DENIED');
29
+ if(journal===null)return config.version; // pre-S3 installations
30
+ const fields=['schema','phase','candidate','previous','deviceId','credentialFingerprint'];
31
+ if(!journal||typeof journal!=='object'||Array.isArray(journal)||
32
+ JSON.stringify(Object.keys(journal).sort())!==JSON.stringify(fields.sort())||
33
+ journal.schema!==1||!/^0\.1\.0-beta\.[1-9]\d*$/.test(journal.previous)||
34
+ !/^0\.1\.0-beta\.[1-9]\d*$/.test(journal.candidate)||
35
+ !/^[a-f0-9-]{36}$/.test(journal.deviceId)||
36
+ !/^[a-f0-9]{64}$/.test(journal.credentialFingerprint))
37
+ throw Error('DEVICE_DIRECT_AUTOSTART_JOURNAL_DENIED');
38
+ const phase=journal.phase;
39
+ if(['activation-pending','health-pending','rolling-back'].includes(phase)){
40
+ if(![journal.previous,journal.candidate].includes(config.version))
41
+ throw Error('DEVICE_DIRECT_AUTOSTART_JOURNAL_DENIED');
42
+ return journal.previous;
43
+ }
44
+ if(['staged','rolled-back'].includes(phase)&&config.version===journal.previous)
45
+ return journal.previous;
46
+ if(phase==='healthy'&&config.version===journal.candidate)
47
+ return journal.candidate;
48
+ throw Error('DEVICE_DIRECT_AUTOSTART_JOURNAL_DENIED');
49
+ }
11
50
  let config=null;
12
51
  try{
13
52
  const data=JSON.parse(readFileSync(join(root,'direct-autostart.json'),'utf8'));
14
53
  if(data.schema!==1||!/^0\.1\.0-beta\.\d+$/.test(data.version)||
15
54
  !validPath(data.node)||!validPath(data.npmCli))throw Error('INVALID_CONFIG');
16
- config=data;
55
+ let journal=null;
56
+ try{
57
+ journal=JSON.parse(readFileSync(join(root,'direct-update-journal.json'),'utf8'));
58
+ }catch(e){if(e?.code!=='ENOENT')throw e;}
59
+ config={...data,version:resolveStartupVersion(data,journal)};
17
60
  }catch{console.error('DEVICE_DIRECT_AUTOSTART_CONFIG_DENIED');FAIL();}
18
61
  if(config){
19
62
  // Windows login tasks do not inherit an interactive shell's PATH.
@@ -31,20 +74,25 @@ if(config){
31
74
  const child=spawn(config.node,args,{shell:false,windowsHide:true,
32
75
  stdio:['ignore','ignore','pipe'],env});
33
76
  let errors='',settled=false;
34
- child.stderr?.on('data',chunk=>{if(errors.length<2048)errors+=String(chunk).slice(0,2048-errors.length);});
35
- const finish=code=>{if(!settled){settled=true;resolve({code,cacheMiss:/ENOTCACHED/i.test(errors)})}};
77
+ child.stderr?.on('data',chunk=>{errors=(errors+String(chunk)).slice(-2048);});
78
+ const finish=code=>{if(!settled){settled=true;resolve({code,cacheMiss:/ENOTCACHED/i.test(errors),transientAcl:isTransientStartupFailure({code,stderr:errors})})}};
36
79
  child.once('error',()=>finish(1));
37
80
  child.once('exit',code=>finish(code??1));
38
81
  });
39
82
  try{
40
83
  // No network for normal logons. Only an explicit cache miss may fetch
41
84
  // the exact same immutable version; never substitute @beta or @latest.
42
- const first=await execute(true);
43
- if(first.code!==0){
44
- if(first.cacheMiss){
45
- const retry=await execute(false);
46
- if(retry.code!==0)FAIL();
47
- }else FAIL();
85
+ // The same pinned immutable version is retried after temporary native ACL
86
+ // timeouts. No re-enrollment, credential change or immediate restart loop.
87
+ for(let retries=0;;){
88
+ const first=await execute(true);
89
+ const result=first.code!==0&&first.cacheMiss?await execute(false):first;
90
+ if(result.code===0)break;
91
+ if(!result.transientAcl){FAIL();break;}
92
+ retries=Math.min(retries+1,8);
93
+ const delay=startupRetryDelay(retries);
94
+ console.warn('RS_STARTUP_RETRY',JSON.stringify({reason:'native_acl_timeout',delay_ms:delay}));
95
+ await new Promise(resolve=>setTimeout(resolve,delay));
48
96
  }
49
97
  }catch{FAIL();}
50
98
  }
File without changes
File without changes
@@ -23,7 +23,7 @@ function receipt(install,expected){
23
23
  const data=JSON.parse(readFileSync(file,'utf8'));
24
24
  if(data?.schema!==1||data.version!==expected||data.distribution!=='synthetic-private'||
25
25
  data.registered!==false||data.serviceEnabled!==false)fail();
26
- for(const [name,version] of [['@remoteshell/device',expected],['@wonderwhy-er/desktop-commander','0.3.1']]){
26
+ for(const [name,version] of [['@remoteshell/device',expected],['@wonderwhy-er/desktop-commander','0.3.4']]){
27
27
  const p=win32.join(install,'node_modules',...name.split('/'),'package.json');
28
28
  const s=lstatSync(p);
29
29
  if(!s.isFile()||s.isSymbolicLink()||JSON.parse(readFileSync(p,'utf8')).version!==version)fail();
@@ -93,33 +93,33 @@ export function ensureWindowsPrivateStore(store,{home=homedir(),run=spawnSync}={
93
93
  checkStore(store,{home});
94
94
  inspectWindowsPrivateDirectoryAcl({directory:store,home});
95
95
  return Object.freeze({ready:true,created:!existed,aclVerified:true});
96
- }catch{deny();}
96
+ }catch(error){if(error?.message==='DEVICE_WINDOWS_ACL_TIMEOUT')throw error;deny();}
97
97
  }
98
- function verifyFile(file,{home=homedir()}={}){
98
+ function verifyFile(file,{home=homedir(),maxFileSize=8192}={}){
99
99
  const store=win32.dirname(file);
100
100
  checkStore(store,{home});
101
101
  // The native file snapshot also checks its protected parent directory.
102
102
  // Avoid a duplicate PowerShell invocation in every credential operation.
103
- inspectWindowsCredentialAcl({file,home});
103
+ inspectWindowsCredentialAcl({file,home,maxFileSize});
104
104
  }
105
105
  // Seal a newly created exclusive lock using the same owner/SYSTEM ACL proof
106
106
  // as credentials. Used by #327 S2 for Windows logoff/reboot recovery.
107
- export function sealWindowsPrivateFile(file,{home=homedir()}={}){
107
+ export function sealWindowsPrivateFile(file,{home=homedir(),maxFileSize=8192}={}){
108
108
  try{
109
109
  const store=win32.dirname(file);
110
110
  checkStore(store,{home});
111
111
  const stat=lstatSync(file);
112
112
  if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1)deny();
113
113
  sealAcl(file);
114
- verifyFile(file,{home});
114
+ verifyFile(file,{home,maxFileSize});
115
115
  return true;
116
- }catch{deny();}
116
+ }catch(error){if(error?.message==='DEVICE_WINDOWS_ACL_TIMEOUT')throw error;deny();}
117
117
  }
118
118
  export function readWindowsPrivate(file,{home=homedir()}={}){
119
119
  try{
120
120
  verifyFile(file,{home});
121
121
  return readFileSync(file,'utf8');
122
- }catch{deny();}
122
+ }catch(error){if(error?.message==='DEVICE_WINDOWS_ACL_TIMEOUT')throw error;deny();}
123
123
  }
124
124
  // A one-use update capability keeps the old credential ACL verification and
125
125
  // the new credential ACL verification, without re-launching PowerShell twice
@@ -141,9 +141,9 @@ export function readWindowsPrivateForUpdate(file,{home=homedir()}={}){
141
141
  current.ctimeMs!==stat.ctimeMs||readFileSync(file,'utf8')!==initial)deny();
142
142
  return atomicWindowsPrivate(file,value,{replace:true,home,
143
143
  [verifiedUpdate]:true});
144
- }catch{deny();}
144
+ }catch(error){if(error?.message==='DEVICE_WINDOWS_ACL_TIMEOUT')throw error;deny();}
145
145
  }});
146
- }catch{deny();}
146
+ }catch(error){if(error?.message==='DEVICE_WINDOWS_ACL_TIMEOUT')throw error;deny();}
147
147
  }
148
148
  export function atomicWindowsPrivate(file,value,{replace=false,home=homedir(),run=spawnSync,...proof}={}){
149
149
  let temp;
@@ -171,6 +171,6 @@ export function atomicWindowsPrivate(file,value,{replace=false,home=homedir(),ru
171
171
  sealAcl(file,{run});
172
172
  verifyFile(file,{home});
173
173
  return Object.freeze({written:true,aclVerified:true});
174
- }catch{deny();
174
+ }catch(error){if(error?.message==='DEVICE_WINDOWS_ACL_TIMEOUT')throw error;deny();
175
175
  }finally{if(temp&&existsSync(temp))rmSync(temp,{force:true});}
176
176
  }
@@ -0,0 +1,67 @@
1
+ // #327 S3: transaction sequencing for an externally approved Windows update.
2
+ // The caller supplies verified health/identity checks and guarantees quiescence.
3
+ // Production activation remains disabled until the trusted runner is integrated.
4
+ import {advanceTransition,recoverTransition} from './safe-update-transition.mjs';
5
+ import {isAuthenticatedCiApproval} from './ci-backed-update-approval.mjs';
6
+ const DENY=()=>{throw Error('DEVICE_SAFE_UPDATE_COORDINATOR_DENIED');};
7
+ function matches(j,identity){
8
+ if(!j||!identity||j.deviceId!==identity.deviceId||
9
+ j.credentialFingerprint!==identity.credentialFingerprint)DENY();
10
+ }
11
+ function requireFunctions(v){for(const x of v)if(typeof x!=='function')DENY();}
12
+ export async function activateWindowsCandidate({readJournal,persistJournal,changePin,
13
+ verifyHealth,identity,approved,candidateVerified,quiescent}={}){
14
+ requireFunctions([readJournal,persistJournal,changePin,verifyHealth]);
15
+ if(quiescent!==true||candidateVerified!==true||
16
+ (approved?.proof!=='ed25519-approved-release-intent'&& !isAuthenticatedCiApproval(approved)))DENY();
17
+ let j=await readJournal();
18
+ matches(j,identity);
19
+ if(j.phase!=='staged'||j.candidate!==approved.version||
20
+ j.previous!==approved.previousVersion)DENY();
21
+ let entered=false;
22
+ try{
23
+ j=advanceTransition(j,'stage-ready');
24
+ await persistJournal(j);entered=true;
25
+ await changePin({action:'activate',approved,candidateVerified:true,quiescent:true,...identity});
26
+ j=advanceTransition(j,'activated');
27
+ await persistJournal(j);
28
+ const health=await verifyHealth({candidate:j.candidate,deviceId:identity.deviceId});
29
+ j=advanceTransition(j,'health-ok',{...health,...identity});
30
+ await persistJournal(j);
31
+ return Object.freeze({phase:'healthy',version:j.candidate});
32
+ }catch(error){
33
+ if(!entered)throw error;
34
+ // If any step failed, attempt to restore prior pin before returning failure.
35
+ // If rollback itself fails, leave the journal pending for startup recovery.
36
+ try{
37
+ const stored=await readJournal();
38
+ matches(stored,identity);
39
+ if(stored.phase==='healthy')throw Error('ALREADY_HEALTHY');
40
+ const failing=stored.phase==='rolling-back'?stored:advanceTransition(stored,'failure');
41
+ if(stored.phase!=='rolling-back')await persistJournal(failing);
42
+ await changePin({action:'restore',quiescent:true,...identity});
43
+ await persistJournal(advanceTransition(failing,'restored',identity));
44
+ }catch{DENY()}
45
+ DENY();
46
+ }
47
+ }
48
+ export async function recoverWindowsCandidate({readJournal,persistJournal,changePin,
49
+ identity,quiescent}={}){
50
+ requireFunctions([readJournal,persistJournal,changePin]);
51
+ if(quiescent!==true)DENY();
52
+ let j=await readJournal();
53
+ if(!j)return Object.freeze({action:'no-update-journal'});
54
+ matches(j,identity);
55
+ const decision=recoverTransition(j);
56
+ if(decision.action!=='restore-previous-pin')
57
+ return Object.freeze({action:decision.action,version:decision.version,changed:false});
58
+ try{
59
+ if(j.phase!=='rolling-back'){
60
+ j=advanceTransition(j,'failure');
61
+ await persistJournal(j);
62
+ }
63
+ await changePin({action:'restore',quiescent:true,...identity});
64
+ await persistJournal(advanceTransition(j,'restored',identity));
65
+ return Object.freeze({action:'restored-previous-pin',version:j.previous});
66
+ }catch{DENY()}
67
+ }
@@ -0,0 +1,69 @@
1
+ // #327 S3 Windows update journal persisted using existing owner/SYSTEM-only ACL.
2
+ import {existsSync} from 'node:fs';
3
+ import {homedir,platform} from 'node:os';
4
+ import {win32} from 'node:path';
5
+ import {directPaths} from './direct-npx-runtime.mjs';
6
+ import {canonicalWindowsLocalFile,isWindowsChildPath} from './native-path-contract.mjs';
7
+ import {atomicWindowsPrivate,readWindowsPrivate,readWindowsPrivateForUpdate,
8
+ ensureWindowsPrivateStore} from './windows-private-store.mjs';
9
+ import {recoverTransition} from './safe-update-transition.mjs';
10
+ const DENY=()=>{throw Error('DEVICE_SAFE_UPDATE_JOURNAL_DENIED');};
11
+ const allowed=['schema','phase','candidate','previous','deviceId','credentialFingerprint'];
12
+ function canonicalJournal(j){
13
+ if(!j||typeof j!=='object'||Array.isArray(j)||
14
+ JSON.stringify(Object.keys(j).sort())!==JSON.stringify([...allowed].sort()))DENY();
15
+ recoverTransition(j); // fail closed on malformed states before writing
16
+ return JSON.stringify(Object.fromEntries(allowed.map(k=>[k,j[k]])))+'\n';
17
+ }
18
+ export function journalPath({home=homedir(),localAppData=process.env.LOCALAPPDATA,
19
+ os=platform()}={}){
20
+ if(os!=='win32')DENY();
21
+ const dir=directPaths({home,localAppData,os}).storageDir;
22
+ const file=win32.join(dir,'direct-update-journal.json');
23
+ canonicalWindowsLocalFile(file);
24
+ isWindowsChildPath(file,dir);
25
+ return {file,dir,home};
26
+ }
27
+ export function readUpdateJournal({home=homedir(),localAppData=process.env.LOCALAPPDATA,
28
+ os=platform(),exists=existsSync,read=readWindowsPrivate}={}){
29
+ const {file}=journalPath({home,localAppData,os});
30
+ if(!exists(file))return null;
31
+ let j;
32
+ try{j=JSON.parse(read(file,{home}));canonicalJournal(j)}catch{DENY()}
33
+ return Object.freeze(j);
34
+ }
35
+ export function persistUpdateJournal(j,{home=homedir(),localAppData=process.env.LOCALAPPDATA,
36
+ os=platform(),exists=existsSync,ensure=ensureWindowsPrivateStore,
37
+ write=atomicWindowsPrivate,readForUpdate=readWindowsPrivateForUpdate}={}){
38
+ const {file,dir}=journalPath({home,localAppData,os});
39
+ const body=canonicalJournal(j);
40
+ try{
41
+ ensure(dir,{home});
42
+ if(exists(file)){
43
+ const cap=readForUpdate(file,{home});
44
+ const old=JSON.parse(cap.content);
45
+ canonicalJournal(old);
46
+ // Never reuse a journal across devices or silently skip state changes.
47
+ if(old.deviceId!==j.deviceId||old.credentialFingerprint!==j.credentialFingerprint||
48
+ old.previous!==j.previous||old.candidate!==j.candidate)DENY();
49
+ const valid={
50
+ staged:['activation-pending'],
51
+ 'activation-pending':['health-pending','rolling-back'],
52
+ 'health-pending':['healthy','rolling-back'],
53
+ 'rolling-back':['rolled-back'],
54
+ healthy:[], 'rolled-back':[]
55
+ };
56
+ if(!valid[old.phase]?.includes(j.phase))DENY();
57
+ cap.replace(body);
58
+ }else{
59
+ if(j.phase!=='staged')DENY();
60
+ write(file,body,{home});
61
+ }
62
+ return Object.freeze({saved:true,phase:j.phase,credentialsPreserved:true});
63
+ }catch{DENY()}
64
+ }
65
+ export function inspectRecoveryJournal(options){
66
+ const record=readUpdateJournal(options);
67
+ if(!record)return Object.freeze({action:'no-update-journal'});
68
+ return recoverTransition(record);
69
+ }
@@ -0,0 +1,68 @@
1
+ // #327 S3: protected fixed-version pin adapter; no registry or process changes.
2
+ import {homedir,platform} from 'node:os';
3
+ import {win32} from 'node:path';
4
+ import {directPaths} from './direct-npx-runtime.mjs';
5
+ import {canonicalWindowsLocalFile,isWindowsChildPath} from './native-path-contract.mjs';
6
+ import {readWindowsPrivateForUpdate} from './windows-private-store.mjs';
7
+ import {readUpdateJournal} from './windows-safe-update-journal.mjs';
8
+ import {isAuthenticatedCiApproval} from './ci-backed-update-approval.mjs';
9
+ const DENY=()=>{throw Error('DEVICE_SAFE_UPDATE_PIN_DENIED');};
10
+ const VERSION=/^0\.1\.0-beta\.[1-9]\d{0,5}$/;
11
+ const DEVICE=/^[a-f0-9-]{36}$/;
12
+ const FINGERPRINT=/^[a-f0-9]{64}$/;
13
+ const exact=(obj,keys)=>obj&&typeof obj==='object'&&!Array.isArray(obj)&&
14
+ JSON.stringify(Object.keys(obj).sort())===JSON.stringify([...keys].sort());
15
+ export function verifyWindowsPinConfig(value){
16
+ if(!exact(value,['schema','version','node','npmCli'])||value.schema!==1||
17
+ !VERSION.test(value.version)||typeof value.node!=='string'||typeof value.npmCli!=='string')DENY();
18
+ for(const path of [value.node,value.npmCli]){
19
+ try{canonicalWindowsLocalFile(path)}catch{DENY()}
20
+ if(/\\(?:_npx|Temp)\\/i.test(path))DENY();
21
+ }
22
+ if(!/\\node\.exe$/i.test(value.node)||!/\\npm-cli\.js$/i.test(value.npmCli))DENY();
23
+ return Object.freeze({...value});
24
+ }
25
+ function assertContext(j,{deviceId,credentialFingerprint}){
26
+ if(!j||j.schema!==1||!DEVICE.test(deviceId||'')||!FINGERPRINT.test(credentialFingerprint||'')||
27
+ j.deviceId!==deviceId||j.credentialFingerprint!==credentialFingerprint||
28
+ !VERSION.test(j.previous||'')||!VERSION.test(j.candidate||''))DENY();
29
+ }
30
+ export function planWindowsPinChange(j,config,{
31
+ action,deviceId,credentialFingerprint,quiescent=false,candidateVerified=false,approved
32
+ }={}){
33
+ assertContext(j,{deviceId,credentialFingerprint});
34
+ const current=verifyWindowsPinConfig(config);
35
+ if(quiescent!==true)DENY();
36
+ let next;
37
+ if(action==='activate'){
38
+ if(j.phase!=='activation-pending'||candidateVerified!==true||
39
+ (approved?.proof!=='ed25519-approved-release-intent'&& !isAuthenticatedCiApproval(approved))||
40
+ approved.version!==j.candidate||
41
+ approved.previousVersion!==j.previous||current.version!==j.previous)DENY();
42
+ next=j.candidate;
43
+ }else if(action==='restore'){
44
+ if(!['activation-pending','health-pending','rolling-back'].includes(j.phase)||
45
+ ![j.previous,j.candidate].includes(current.version))DENY();
46
+ next=j.previous;
47
+ }else DENY();
48
+ return Object.freeze({previous:current.version,next,changed:current.version!==next,
49
+ config:Object.freeze({...current,version:next}),action});
50
+ }
51
+ export function applyWindowsPinChange({home=homedir(),localAppData=process.env.LOCALAPPDATA,
52
+ os=platform(),action,deviceId,credentialFingerprint,quiescent,candidateVerified,approved,
53
+ readJournal=readUpdateJournal,readForUpdate=readWindowsPrivateForUpdate}={}){
54
+ try{
55
+ if(os!=='win32')DENY();
56
+ const storage=directPaths({home,localAppData,os}).storageDir;
57
+ const file=win32.join(storage,'direct-autostart.json');
58
+ canonicalWindowsLocalFile(file);isWindowsChildPath(file,storage);
59
+ const journal=readJournal({home,localAppData,os});
60
+ const cap=readForUpdate(file,{home});
61
+ const config=JSON.parse(cap.content);
62
+ const plan=planWindowsPinChange(journal,config,{action,deviceId,credentialFingerprint,
63
+ quiescent,candidateVerified,approved});
64
+ if(plan.changed)cap.replace(JSON.stringify(plan.config)+'\n');
65
+ return Object.freeze({action:plan.action,from:plan.previous,to:plan.next,
66
+ changed:plan.changed,credentialsPreserved:true});
67
+ }catch{DENY()}
68
+ }
@@ -0,0 +1,59 @@
1
+ // #327 S3: Windows per-user private staging of a CI- or signature-verified npm tarball.
2
+ // Never extracts, executes, installs, changes HKCU, or modifies credentials.
3
+ import {randomBytes,createHash,timingSafeEqual} from 'node:crypto';
4
+ import {homedir,platform} from 'node:os';
5
+ import {win32} from 'node:path';
6
+ import {openSync,writeSync,fsyncSync,closeSync,linkSync,unlinkSync,lstatSync,readFileSync,existsSync} from 'node:fs';
7
+ import {directPaths} from './direct-npx-runtime.mjs';
8
+ import {canonicalWindowsLocalFile,isWindowsChildPath} from './native-path-contract.mjs';
9
+ import {verifyTarballBytes} from './safe-update-artifact.mjs';
10
+ import {ensureWindowsPrivateStore,sealWindowsPrivateFile} from './windows-private-store.mjs';
11
+ import {inspectWindowsCredentialAcl} from './windows-credential-boundary.mjs';
12
+ const DENY=()=>{throw Error('DEVICE_WINDOWS_UPDATE_STAGE_DENIED');};
13
+ const VERSION=/^0\.1\.0-beta\.[1-9]\d{0,5}$/;
14
+ function same(bytes,wanted){
15
+ const actual=createHash('sha512').update(bytes).digest();
16
+ const expected=Buffer.from(wanted.slice(7),'base64');
17
+ return expected.length===64&&timingSafeEqual(actual,expected);
18
+ }
19
+ export function stageWindowsVerifiedTarball(approved,metadata,bytes,{
20
+ home=homedir(),localAppData=process.env.LOCALAPPDATA,os=platform(),
21
+ ensure=ensureWindowsPrivateStore,seal=sealWindowsPrivateFile,
22
+ inspect=inspectWindowsCredentialAcl
23
+ }={}){
24
+ let temp=null,fd;
25
+ try{
26
+ if(os!=='win32'||!VERSION.test(approved?.version||''))DENY();
27
+ verifyTarballBytes(approved,metadata,bytes);
28
+ const dir=directPaths({home,localAppData,os}).storageDir;
29
+ const dest=win32.join(dir,'direct-update-'+approved.version+'.tgz');
30
+ for(const p of [dest]){canonicalWindowsLocalFile(p);isWindowsChildPath(p,dir);}
31
+ ensure(dir,{home});
32
+ temp=win32.join(dir,'direct-update-'+randomBytes(16).toString('hex')+'.tmp');
33
+ canonicalWindowsLocalFile(temp);isWindowsChildPath(temp,dir);
34
+ fd=openSync(temp,'wx',0o600);
35
+ let offset=0;
36
+ while(offset<bytes.length){
37
+ const n=writeSync(fd,bytes,offset,bytes.length-offset);
38
+ if(n<=0)DENY();
39
+ offset+=n;
40
+ }
41
+ fsyncSync(fd);closeSync(fd);fd=undefined;
42
+ seal(temp,{home,maxFileSize:32*1024*1024});
43
+ try{linkSync(temp,dest)}catch(e){
44
+ if(e.code!=='EEXIST')DENY();
45
+ }
46
+ // Removing the temporary link must leave exactly one private immutable candidate.
47
+ unlinkSync(temp);temp=null;
48
+ inspect({file:dest,home,maxFileSize:32*1024*1024});
49
+ const st=lstatSync(dest);
50
+ if(!st.isFile()||st.isSymbolicLink()||st.nlink!==1||
51
+ st.size!==bytes.length||!same(readFileSync(dest),approved.sha512))DENY();
52
+ return Object.freeze({path:dest,version:approved.version,verified:true,
53
+ activated:false,sha512:approved.sha512,bytes:st.size});
54
+ }catch{DENY()}
55
+ finally{
56
+ if(fd!==undefined)try{closeSync(fd)}catch{}
57
+ if(temp&&existsSync(temp))try{unlinkSync(temp)}catch{}
58
+ }
59
+ }
File without changes