@remoteshell/device 0.0.0-stage → 0.1.0-beta.10

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 (93) 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 +384 -0
  15. package/bin/direct-npx-runtime.mjs +150 -0
  16. package/bin/enrollment-client.mjs +105 -0
  17. package/bin/install-acquire.mjs +89 -0
  18. package/bin/install-integrity.mjs +74 -0
  19. package/bin/install-plan.mjs +43 -0
  20. package/bin/lifecycle.mjs +172 -0
  21. package/bin/native-path-contract.mjs +23 -0
  22. package/bin/remoteshell-device-install.cmd +17 -0
  23. package/bin/remoteshell-device-install.ps1 +17 -0
  24. package/bin/remoteshell-device-install.sh +15 -0
  25. package/bin/remoteshell-device-preflight.cmd +10 -0
  26. package/bin/remoteshell-device-preflight.ps1 +10 -0
  27. package/bin/remoteshell-easy-diagnose.ps1 +32 -0
  28. package/bin/remoteshell-easy-install.ps1 +292 -0
  29. package/bin/remoteshell-easy-install.sh +71 -0
  30. package/bin/remoteshell-easy-uninstall.ps1 +128 -0
  31. package/bin/windows-acl-wmi-client.mjs +50 -0
  32. package/bin/windows-acl-wmi.js +43 -0
  33. package/bin/windows-credential-boundary.mjs +113 -0
  34. package/bin/windows-direct-autostart-runner.mjs +50 -0
  35. package/bin/windows-direct-autostart.mjs +110 -0
  36. package/bin/windows-install-layout.mjs +28 -0
  37. package/bin/windows-native-installer.mjs +91 -0
  38. package/bin/windows-private-store.mjs +176 -0
  39. package/bin/windows-user-lifecycle.mjs +34 -0
  40. package/npm-shrinkwrap.json +8591 -0
  41. package/package.json +27 -4
  42. package/shared/lib/bounded-search-contract.mjs +5 -0
  43. package/shared/lib/bounded-search-policy.mjs +24 -0
  44. package/shared/lib/config.mjs +14 -0
  45. package/shared/lib/contracts.mjs +26 -0
  46. package/shared/lib/dc-generic-policy.mjs +102 -0
  47. package/shared/lib/dc-relay-contract.mjs +42 -0
  48. package/shared/lib/dc-tool-catalog.mjs +67 -0
  49. package/shared/lib/dev-dc-relay-contract.mjs +20 -0
  50. package/shared/lib/dev-paged-output.mjs +32 -0
  51. package/shared/lib/dev-root-exclusions.mjs +56 -0
  52. package/shared/lib/errors.mjs +9 -0
  53. package/shared/lib/events.mjs +5 -0
  54. package/shared/lib/execution-policy.mjs +41 -0
  55. package/shared/lib/isolated-read-boundary.mjs +50 -0
  56. package/shared/lib/isolated-read-policy.mjs +29 -0
  57. package/shared/lib/lifecycle-events.mjs +13 -0
  58. package/shared/lib/runtime-timing.mjs +9 -0
  59. package/shared/lib/synthetic-auxiliary-policy.mjs +21 -0
  60. package/shared/lib/synthetic-write-policy.mjs +52 -0
  61. package/shared/lib/tool-registry.mjs +58 -0
  62. package/src/config/l2-dev-oci-credential.mjs +39 -0
  63. package/src/config/p2-private-credential.mjs +15 -0
  64. package/src/connection/dev-dogfood-processes.mjs +25 -0
  65. package/src/connection/dev-dogfood-read.mjs +64 -0
  66. package/src/connection/dev-dogfood-task.mjs +113 -0
  67. package/src/connection/dev-dogfood-write.mjs +62 -0
  68. package/src/connection/dev-file-task.mjs +119 -0
  69. package/src/connection/dev-r4-file-task.mjs +56 -0
  70. package/src/connection/dev-read-tools.mjs +134 -0
  71. package/src/connection/dev-root-scopes.mjs +82 -0
  72. package/src/core/c1-dc-transport.mjs +26 -0
  73. package/src/core/c1-startup.mjs +22 -0
  74. package/src/core/c1-supervisor.mjs +111 -0
  75. package/src/core/c1-worker.mjs +88 -0
  76. package/src/core/fixture.txt +2 -0
  77. package/src/dc/dc-access-readiness.mjs +31 -0
  78. package/src/dc/dev-dc-relay.mjs +47 -0
  79. package/src/device-agent/main.mjs +1 -0
  80. package/src/gateway-keepalive.mjs +73 -0
  81. package/src/main.mjs +436 -0
  82. package/src/policy/bounded-search-adapter.mjs +115 -0
  83. package/src/policy/isolated-read-adapter.mjs +50 -0
  84. package/src/policy/isolated-read-mount.mjs +27 -0
  85. package/src/policy/synthetic-auxiliary-adapter.mjs +75 -0
  86. package/src/policy/synthetic-file-adapter.mjs +26 -0
  87. package/src/policy/synthetic-file-transaction.mjs +87 -0
  88. package/src/policy/synthetic-write-adapter.mjs +151 -0
  89. package/src/policy/synthetic-write-mount.mjs +23 -0
  90. package/src/policy/verified-bounded-search.mjs +12 -0
  91. package/src/policy/verified-isolated-read.mjs +15 -0
  92. package/src/policy/verified-synthetic-write.mjs +14 -0
  93. package/README.md +0 -3
@@ -0,0 +1,113 @@
1
+ // #310 Native Windows credential ACL assessment. Read only; no ACL repair or
2
+ // privilege escalation. PowerShell receives the path in an environment value,
3
+ // not in a shell argument. Windows worker still remains gated separately.
4
+ import {spawnSync} from 'node:child_process';
5
+ import {lstatSync,realpathSync} from 'node:fs';
6
+ import {win32} from 'node:path';
7
+ import {canonicalWindowsLocalFile,isWindowsChildPath} from './native-path-contract.mjs';
8
+ import {inspectWmiAcl} from './windows-acl-wmi-client.mjs';
9
+ const DENY=()=>{throw Error('DEVICE_WINDOWS_ACL_DENIED');};
10
+ const SID=/^S-1-\d+(?:-\d+){1,15}$/;
11
+ const SYSTEM='S-1-5-18';
12
+ const ADMINISTRATORS='S-1-5-32-544';
13
+ // PowerShell Get-Acl must run under the actual Windows user profile. A
14
+ // SystemRoot-only environment makes initialization intermittently time out
15
+ // on Windows Task Scheduler. Pass only OS/user environment essentials, not
16
+ // PATH, PSModulePath, executable names or arbitrary parent environment.
17
+ function aclChildEnv(systemRoot,target,directory){
18
+ const e={SystemRoot:systemRoot,WINDIR:systemRoot,
19
+ RS310_ACL_TARGET:target,RS310_ACL_DIR:directory?'1':'0'};
20
+ for(const key of ['USERPROFILE','APPDATA','LOCALAPPDATA','TEMP','TMP','HOMEDRIVE','HOMEPATH','ProgramData']){
21
+ const v=process.env[key];
22
+ if(typeof v==='string'&&v.length>0&&v.length<4096)e[key]=v;
23
+ }
24
+ return e;
25
+ }
26
+ const SCRIPT=[
27
+ '$ErrorActionPreference = "Stop"',
28
+ '$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()',
29
+ 'function Read-PrivateAcl([string]$target) {',
30
+ ' $acl = Get-Acl -LiteralPath $target',
31
+ ' $owner = $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value',
32
+ ' $rules = @($acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier]) | ForEach-Object {',
33
+ ' @{ sid = $_.IdentityReference.Value; inherited = $_.IsInherited; access = $_.AccessControlType.ToString(); rights = [int64]$_.FileSystemRights }',
34
+ ' })',
35
+ ' return @{ user = $identity.User.Value; owner = $owner; protected = $acl.AreAccessRulesProtected; rules = $rules }',
36
+ '}',
37
+ '$file = $env:RS310_ACL_TARGET',
38
+ '$parent = if ($env:RS310_ACL_DIR -eq "1") { $file } else { Split-Path -Parent $file }',
39
+ '@{ file = (Read-PrivateAcl $file); parent = (Read-PrivateAcl $parent) } | ConvertTo-Json -Compress -Depth 6'
40
+ ].join('; ');
41
+ export function validateWindowsAclSnapshot(snapshot){
42
+ const {user,owner,protected:aclProtected,rules}=snapshot||{};
43
+ if(!SID.test(user||'')||owner!==user||aclProtected!==true||!Array.isArray(rules)||rules.length<1)DENY();
44
+ let ownerAllowed=false;
45
+ for(const rule of rules){
46
+ if(!SID.test(rule?.sid||'')||rule.inherited!==false||rule.access!=='Allow'||
47
+ !Number.isSafeInteger(rule.rights)||rule.rights<0)DENY();
48
+ if(![user,SYSTEM,ADMINISTRATORS].includes(rule.sid))DENY();
49
+ if(rule.sid===user)ownerAllowed=true;
50
+ }
51
+ if(!ownerAllowed)DENY();
52
+ return Object.freeze({ownerVerified:true,restrictedAcl:true,credentialReadiness:'acl-only'});
53
+ }
54
+ export function inspectWindowsCredentialAcl({
55
+ file,home,os=process.platform,lstat=lstatSync,realpath=realpathSync,
56
+ run=spawnSync
57
+ }={}){
58
+ if(os!=='win32')DENY();
59
+ try{
60
+ canonicalWindowsLocalFile(home);
61
+ isWindowsChildPath(file,home);
62
+ const parent=win32.dirname(file);
63
+ canonicalWindowsLocalFile(parent);
64
+ const root=lstat(home),dir=lstat(parent),stat=lstat(file);
65
+ if(!root.isDirectory()||root.isSymbolicLink()||
66
+ !dir.isDirectory()||dir.isSymbolicLink()||
67
+ !stat.isFile()||stat.isSymbolicLink()||
68
+ stat.nlink!==1||stat.size<1||stat.size>8192)DENY();
69
+ if(win32.normalize(realpath(file)).toLowerCase()!==file.toLowerCase()||
70
+ win32.normalize(realpath(parent)).toLowerCase()!==parent.toLowerCase())DENY();
71
+ if(run===spawnSync){
72
+ const snapshot=inspectWmiAcl(file);
73
+ validateWindowsAclSnapshot(snapshot.parent);
74
+ return validateWindowsAclSnapshot(snapshot.file);
75
+ }
76
+ const systemRoot=process.env.SystemRoot||'C:\\Windows';
77
+ canonicalWindowsLocalFile(systemRoot+'\\System32');
78
+ const powerShell=win32.join(systemRoot,'System32','WindowsPowerShell','v1.0','powershell.exe');
79
+ const child=run(powerShell,['-NoProfile','-NonInteractive','-EncodedCommand',
80
+ Buffer.from(SCRIPT,'utf16le').toString('base64')],{
81
+ shell:false,windowsHide:true,encoding:'utf8',timeout:20000,maxBuffer:16384,
82
+ env:aclChildEnv(systemRoot,file,false),
83
+ stdio:'pipe'
84
+ });
85
+ if(child.error||child.signal||child.status!==0||typeof child.stdout!=='string'||child.stdout.length>8192)DENY();
86
+ const snapshot=JSON.parse(child.stdout);
87
+ validateWindowsAclSnapshot(snapshot?.parent);
88
+ return validateWindowsAclSnapshot(snapshot?.file);
89
+ }catch{DENY();}
90
+ }
91
+
92
+ // Verify one directory's own protected ACL without creating any files.
93
+ export function inspectWindowsPrivateDirectoryAcl({directory,home,os=process.platform,
94
+ lstat=lstatSync,realpath=realpathSync,run=spawnSync}={}){
95
+ if(os!=='win32')DENY();
96
+ try{
97
+ canonicalWindowsLocalFile(home);
98
+ isWindowsChildPath(directory,home);
99
+ const st=lstat(directory);
100
+ if(!st.isDirectory()||st.isSymbolicLink()||
101
+ win32.normalize(realpath(directory)).toLowerCase()!==directory.toLowerCase())DENY();
102
+ if(run===spawnSync)return validateWindowsAclSnapshot(inspectWmiAcl(directory,{directory:true}).file);
103
+ const systemRoot=process.env.SystemRoot||'C:\\Windows';
104
+ const ps=win32.join(systemRoot,'System32','WindowsPowerShell','v1.0','powershell.exe');
105
+ const child=run(ps,['-NoProfile','-NonInteractive','-EncodedCommand',
106
+ Buffer.from(SCRIPT,'utf16le').toString('base64')],{
107
+ shell:false,windowsHide:true,encoding:'utf8',timeout:20000,maxBuffer:16384,
108
+ env:aclChildEnv(systemRoot,directory,true),stdio:'pipe'
109
+ });
110
+ if(child.error||child.signal||child.status!==0||typeof child.stdout!=='string'||child.stdout.length>8192)DENY();
111
+ return validateWindowsAclSnapshot(JSON.parse(child.stdout)?.file);
112
+ }catch{DENY();}
113
+ }
@@ -0,0 +1,50 @@
1
+ // #327 S2: single-user fixed-version Windows logon runner.
2
+ // Small persistent launcher; npm package remains in the normal npx cache.
3
+ import {readFileSync,writeFileSync} from 'node:fs';
4
+ import {dirname,join} from 'node:path';
5
+ import {fileURLToPath} from 'node:url';
6
+ import {spawn} from 'node:child_process';
7
+ const root=dirname(fileURLToPath(import.meta.url));
8
+ const FAIL=()=>{process.exitCode=1;};
9
+ function validPath(x){return typeof x==='string'&&/^[A-Za-z]:\\/.test(x)&&
10
+ !/[\r\n"'&|<>%]/.test(x)&&!x.split('\\').includes('..');}
11
+ let config=null;
12
+ try{
13
+ const data=JSON.parse(readFileSync(join(root,'direct-autostart.json'),'utf8'));
14
+ if(data.schema!==1||!/^0\.1\.0-beta\.\d+$/.test(data.version)||
15
+ !validPath(data.node)||!validPath(data.npmCli))throw Error('INVALID_CONFIG');
16
+ config=data;
17
+ }catch{console.error('DEVICE_DIRECT_AUTOSTART_CONFIG_DENIED');FAIL();}
18
+ if(config){
19
+ // Windows login tasks do not inherit an interactive shell's PATH.
20
+ // npm may start node by name, so expose only the selected runtime in
21
+ // this child process. Never change machine or user environment settings.
22
+ const env={...process.env,PUPPETEER_SKIP_DOWNLOAD:'true',
23
+ npm_config_ignore_scripts:'true',npm_config_omit:'optional',
24
+ npm_config_audit:'false',npm_config_fund:'false'};
25
+ const originalPath=Object.entries(env).find(([key])=>key.toLowerCase()==='path')?.[1]||'';
26
+ for(const key of Object.keys(env))if(key.toLowerCase()==='path')delete env[key];
27
+ env.Path=[dirname(config.node),originalPath].filter(Boolean).join(';');
28
+ const execute=offline=>new Promise(resolve=>{
29
+ const args=[config.npmCli,'exec','--yes',...(offline?['--offline']:[]),
30
+ '--package=@remoteshell/device@'+config.version,'--','remoteshell-device','run'];
31
+ const child=spawn(config.node,args,{shell:false,windowsHide:true,
32
+ stdio:['ignore','ignore','pipe'],env});
33
+ 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)})}};
36
+ child.once('error',()=>finish(1));
37
+ child.once('exit',code=>finish(code??1));
38
+ });
39
+ try{
40
+ // No network for normal logons. Only an explicit cache miss may fetch
41
+ // 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();
48
+ }
49
+ }catch{FAIL();}
50
+ }
@@ -0,0 +1,110 @@
1
+ // #327 S2. Opt-in per-user Windows login autostart for exact public npx.
2
+ // No install/clone, no credential mutation and no other user's startup keys.
3
+ import {spawnSync} from 'node:child_process';
4
+ import {existsSync,readFileSync,rmSync} from 'node:fs';
5
+ import {homedir} from 'node:os';
6
+ import {win32} from 'node:path';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {devOfficialRegistration} from './dev-agent-client.mjs';
9
+ import {directPaths,requireNoLegacyInstall} from './direct-npx-runtime.mjs';
10
+ import {atomicWindowsPrivate,readWindowsPrivate,ensureWindowsPrivateStore} from './windows-private-store.mjs';
11
+ import {canonicalWindowsLocalFile,isWindowsChildPath} from './native-path-contract.mjs';
12
+ import {inspectWindowsCredentialAcl} from './windows-credential-boundary.mjs';
13
+ const VALUE='RemoteShell-Direct-npx';
14
+ const KEY='HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run';
15
+ const DENY=()=>{throw Error('DEVICE_DIRECT_AUTOSTART_DENIED');};
16
+ function execReg(args,{run=spawnSync}={}){
17
+ const root=process.env.SystemRoot||'C:\\Windows';
18
+ const result=run(win32.join(root,'System32','reg.exe'),args,{
19
+ shell:false,windowsHide:true,encoding:'utf8',timeout:10000,maxBuffer:8192,stdio:'pipe'});
20
+ if(result?.error||result?.signal||![0,1].includes(result?.status))DENY();
21
+ return result;
22
+ }
23
+ function paths({home=homedir(),localAppData=process.env.LOCALAPPDATA,os=process.platform}={}){
24
+ if(os!=='win32')DENY();
25
+ const p=directPaths({home,localAppData,os});
26
+ const runner=win32.join(p.storageDir,'direct-autostart-runner.mjs');
27
+ const config=win32.join(p.storageDir,'direct-autostart.json');
28
+ for(const x of [runner,config]){canonicalWindowsLocalFile(x);isWindowsChildPath(x,p.storageDir);}
29
+ return {p,runner,config};
30
+ }
31
+ export function exactAutostartVersion(value){
32
+ if(typeof value!=='string'||!/^0\.1\.0-beta\.\d+$/.test(value))DENY();
33
+ return value;
34
+ }
35
+ function stableExec({node=process.execPath,npmCli=process.env.npm_execpath,home=homedir()}={}){
36
+ for(const x of [node,npmCli]){canonicalWindowsLocalFile(x);if(!existsSync(x))DENY();}
37
+ // npm's executable must be from a persistent install, not an ephemeral _npx.
38
+ for(const x of [node,npmCli]){
39
+ if(/[/\\]_npx[/\\]/i.test(x)||/[/\\]Temp[/\\]/i.test(x))DENY();
40
+ }
41
+ if(!/node\.exe$/i.test(node)||!/npm-cli\.js$/i.test(npmCli))DENY();
42
+ return {node,npmCli};
43
+ }
44
+ function runValue(node,runner){return '"'+node+'" "'+runner+'"';}
45
+ function current({run}={}){
46
+ const result=execReg(['query',KEY,'/v',VALUE],{run});
47
+ if(result.status===1)return null;
48
+ const match=String(result.stdout||'').split(/\r?\n/)
49
+ .find(x=>new RegExp('^\\s*'+VALUE+'\\s+REG_SZ\\s+','i').test(x));
50
+ if(!match)DENY();
51
+ const v=match.replace(new RegExp('^\\s*'+VALUE+'\\s+REG_SZ\\s+','i'),'').trim();
52
+ if(!v)DENY();
53
+ return v;
54
+ }
55
+ export function directAutostartStatus({run}={}){
56
+ const value=current({run});
57
+ return {enabled:value!==null,registered:undefined,scope:'current-Windows-user'};
58
+ }
59
+ export function enableDirectAutostart({version,home=homedir(),localAppData=process.env.LOCALAPPDATA,
60
+ node=process.execPath,npmCli=process.env.npm_execpath,run=spawnSync}={}){
61
+ exactAutostartVersion(version);
62
+ const {p,runner,config}=paths({home,localAppData});
63
+ requireNoLegacyInstall(p);
64
+ const registration=devOfficialRegistration({storageDir:p.storageDir});
65
+ if(!registration)DENY();
66
+ ensureWindowsPrivateStore(p.storageDir,{home});
67
+ const exe=stableExec({node,npmCli,home});
68
+ const command=runValue(exe.node,runner);
69
+ const active=current({run});
70
+ if(active!==null){
71
+ if(active!==command)DENY();
72
+ const stored=JSON.parse(readWindowsPrivate(config,{home}));
73
+ if(stored.version!==version||stored.node!==exe.node||stored.npmCli!==exe.npmCli)DENY();
74
+ return {enabled:true,version,reused:true,credentialsPreserved:true};
75
+ }
76
+ if(existsSync(runner)||existsSync(config))DENY(); // incomplete install: investigate, never overwrite.
77
+ const source=readFileSync(fileURLToPath(new URL('./windows-direct-autostart-runner.mjs',import.meta.url)),'utf8');
78
+ let wroteRunner=false,wroteConfig=false;
79
+ try{
80
+ atomicWindowsPrivate(runner,source,{home});wroteRunner=true;
81
+ atomicWindowsPrivate(config,JSON.stringify({schema:1,version,...exe})+'\n',{home});
82
+ wroteConfig=true;
83
+ const result=execReg(['add',KEY,'/v',VALUE,'/t','REG_SZ','/d',command,'/f'],{run});
84
+ if(result.status!==0)DENY();
85
+ }catch(error){
86
+ // Only files created by this invocation are ever removed on failure.
87
+ if(wroteConfig)rmSync(config,{force:true});
88
+ if(wroteRunner)rmSync(runner,{force:true});
89
+ throw error;
90
+ }
91
+ return {enabled:true,version,reused:false,credentialsPreserved:true,deviceId:registration.deviceId};
92
+ }
93
+ export function disableDirectAutostart({home=homedir(),localAppData=process.env.LOCALAPPDATA,
94
+ node=process.execPath,run=spawnSync}={}){
95
+ const {runner,config}=paths({home,localAppData});
96
+ const value=current({run});
97
+ if(value===null)return {enabled:false,changed:false,credentialsPreserved:true};
98
+ if(!value.endsWith(' "'+runner+'"'))DENY();
99
+ const result=execReg(['delete',KEY,'/v',VALUE,'/f'],{run});
100
+ if(result.status!==0)DENY();
101
+ // Explicit disable revokes only this user's launcher, never credentials.
102
+ // Existing running Agent is not killed here; stop is an independent action.
103
+ for(const file of [config,runner]){
104
+ if(existsSync(file)){
105
+ inspectWindowsCredentialAcl({file,home});
106
+ rmSync(file);
107
+ }
108
+ }
109
+ return {enabled:false,changed:true,credentialsPreserved:true};
110
+ }
@@ -0,0 +1,28 @@
1
+ // #310 Non-executing Windows per-user installation layout. No directories are
2
+ // created and no existing DC/RDC/RS credentials are copied or replaced.
3
+ import {win32} from 'node:path';
4
+ import {canonicalWindowsLocalFile,isWindowsChildPath} from './native-path-contract.mjs';
5
+ const deny=()=>{throw Error('DEVICE_WINDOWS_LAYOUT_DENIED');};
6
+ export function windowsInstallLayout({home,localAppData,os='win32'}={}){
7
+ if(os!=='win32')deny();
8
+ try{
9
+ canonicalWindowsLocalFile(home);
10
+ // Remote launchers may omit LOCALAPPDATA even when the authenticated Windows
11
+ // profile has its standard Local AppData directory. Derive only that path;
12
+ // never accept a missing profile root or repair an explicitly foreign value.
13
+ const resolvedLocalAppData=localAppData===undefined||localAppData===null||localAppData===''?
14
+ win32.join(home,'AppData','Local'):localAppData;
15
+ canonicalWindowsLocalFile(resolvedLocalAppData);
16
+ isWindowsChildPath(resolvedLocalAppData,home);
17
+ const base=win32.join(resolvedLocalAppData,'RemoteShell','DeviceAgent');
18
+ const install=win32.join(base,'install');
19
+ const credentials=win32.join(base,'dev-credentials');
20
+ for(const path of [base,install,credentials]){
21
+ canonicalWindowsLocalFile(path);
22
+ isWindowsChildPath(path,home);
23
+ }
24
+ return Object.freeze({platform:'win32',base,install,credentials,
25
+ executableReady:false,permissionsVerified:false,created:false,
26
+ userScopeOnly:true,existingCredentialsPreserved:true});
27
+ }catch{deny();}
28
+ }
@@ -0,0 +1,91 @@
1
+ // #310 Windows native user package installation. No service or enrollment.
2
+ // A package-only stage is never reported as Agent connected/DC ready.
3
+ import {existsSync,lstatSync,mkdirSync,readFileSync,writeFileSync,renameSync,rmSync,realpathSync} from 'node:fs';
4
+ import {win32} from 'node:path';
5
+ import {randomUUID} from 'node:crypto';
6
+ import {spawnSync} from 'node:child_process';
7
+ import {windowsInstallLayout} from './windows-install-layout.mjs';
8
+ import {canonicalWindowsLocalFile,isWindowsChildPath} from './native-path-contract.mjs';
9
+ const fail=(code='DEVICE_WINDOWS_INSTALL_DENIED')=>{throw Error(code);};
10
+ function secureDirectory(path,{allowCreate=false}={}){
11
+ canonicalWindowsLocalFile(path);
12
+ if(!existsSync(path)){
13
+ if(!allowCreate)fail();
14
+ mkdirSync(path,{recursive:true});
15
+ }
16
+ const st=lstatSync(path);
17
+ if(!st.isDirectory()||st.isSymbolicLink()||win32.normalize(realpathSync(path)).toLowerCase()!==path.toLowerCase())fail();
18
+ }
19
+ function receipt(install,expected){
20
+ const file=win32.join(install,'receipt.json');
21
+ const st=lstatSync(file);
22
+ if(!st.isFile()||st.isSymbolicLink()||st.size>2048)fail();
23
+ const data=JSON.parse(readFileSync(file,'utf8'));
24
+ if(data?.schema!==1||data.version!==expected||data.distribution!=='synthetic-private'||
25
+ data.registered!==false||data.serviceEnabled!==false)fail();
26
+ for(const [name,version] of [['@remoteshell/device',expected],['@wonderwhy-er/desktop-commander','0.3.1']]){
27
+ const p=win32.join(install,'node_modules',...name.split('/'),'package.json');
28
+ const s=lstatSync(p);
29
+ if(!s.isFile()||s.isSymbolicLink()||JSON.parse(readFileSync(p,'utf8')).version!==version)fail();
30
+ }
31
+ return data;
32
+ }
33
+ export function installWindowsNative({
34
+ home,localAppData,packageRoot,version,nodeBin=process.execPath,run=spawnSync
35
+ }={}){
36
+ const layout=windowsInstallLayout({home,localAppData});
37
+ const {base,install}=layout;
38
+ // LOCALAPPDATA can be absent in remote sessions; use the validated layout.
39
+ const effectiveLocalAppData=win32.dirname(win32.dirname(base));
40
+ for(const p of [home,effectiveLocalAppData,win32.dirname(base),base])secureDirectory(p,{allowCreate:p!==home});
41
+ if(existsSync(install))fail('DEVICE_ALREADY_INSTALLED');
42
+ canonicalWindowsLocalFile(packageRoot);isWindowsChildPath(packageRoot,home);
43
+ // Only resolve npm's trusted installed JavaScript entrypoint. Avoid .cmd,
44
+ // powershell, shell:true and untrusted command interpolation.
45
+ const npmCli=win32.join(win32.dirname(nodeBin),'node_modules','npm','bin','npm-cli.js');
46
+ const st=lstatSync(npmCli);
47
+ if(!st.isFile()||st.isSymbolicLink())fail();
48
+ const staging=win32.join(base,'.install-'+randomUUID());
49
+ mkdirSync(staging);
50
+ try{
51
+ const options={shell:false,windowsHide:true,encoding:'utf8',stdio:'pipe',timeout:120000,maxBuffer:1048576};
52
+ const pack=run(nodeBin,[npmCli,'pack',packageRoot,'--ignore-scripts','--json','--pack-destination',staging],options);
53
+ if(pack.error||pack.signal||pack.status!==0)fail('DEVICE_INSTALL_PACKAGE_FAILED');
54
+ let data;try{data=JSON.parse(pack.stdout);}catch{fail('DEVICE_INSTALL_PACKAGE_FAILED');}
55
+ const entry=Array.isArray(data)?data[0]:null;
56
+ if(entry?.filename!==`remoteshell-device-${version}.tgz`)fail('DEVICE_INSTALL_PACKAGE_FAILED');
57
+ const archive=win32.join(staging,entry.filename);
58
+ // A cold public npm install may need several minutes for the pinned DC dependency tree.
59
+ // Keep the quick local pack limit above, but do not abort a healthy dependency fetch at 120s.
60
+ const installed=run(nodeBin,[npmCli,'install','--prefix',staging,'--ignore-scripts','--no-audit','--no-fund','--no-package-lock','--no-save',archive],{...options,timeout:900000});
61
+ if(installed.error?.code==='ETIMEDOUT')fail('DEVICE_INSTALL_DEPENDENCY_TIMEOUT');
62
+ if(installed.error||installed.signal||installed.status!==0)fail('DEVICE_INSTALL_DEPENDENCY_FAILED');
63
+ rmSync(archive,{force:true});
64
+ writeFileSync(win32.join(staging,'receipt.json'),JSON.stringify({
65
+ schema:1,version,distribution:'synthetic-private',registered:false,serviceEnabled:false
66
+ })+'\n',{flag:'wx'});
67
+ receipt(staging,version);
68
+ if(existsSync(install))fail('DEVICE_ALREADY_INSTALLED');
69
+ renameSync(staging,install);
70
+ return Object.freeze({installed:true,version,registered:false,connected:false,
71
+ dcReady:false,serviceEnabled:false,credentialsPreserved:true,runMode:'not-started',
72
+ next:'owner-consent-and-worker-not-ready'});
73
+ }finally{if(existsSync(staging))rmSync(staging,{recursive:true,force:true});}
74
+ }
75
+ export function statusWindowsNative({home,localAppData,version}={}){
76
+ const p=windowsInstallLayout({home,localAppData});
77
+ if(!existsSync(p.install))return {installed:false,registered:false,connected:false,dcReady:false};
78
+ secureDirectory(p.install);
79
+ receipt(p.install,version);
80
+ return {installed:true,version,registered:false,connected:false,dcReady:false,
81
+ serviceEnabled:false,credentialsPreserved:true};
82
+ }
83
+ export function uninstallWindowsNative({home,localAppData,version}={}){
84
+ const p=windowsInstallLayout({home,localAppData});
85
+ if(!existsSync(p.install))return {removed:false};
86
+ secureDirectory(p.install);receipt(p.install,version);
87
+ // Service operations are still explicitly disabled; delete only the package
88
+ // created by this installer. Never touch separate credentials or RDC.
89
+ rmSync(p.install,{recursive:true,force:false});
90
+ return {removed:true,credentialsPreserved:true,serviceUntouched:true};
91
+ }
@@ -0,0 +1,176 @@
1
+ // Windows native owner-paired DEV credential storage.
2
+ // No existing RDC/RS credential is read, copied, imported or overwritten.
3
+ import {spawnSync} from 'node:child_process';
4
+ import {existsSync,lstatSync,mkdirSync,readFileSync,realpathSync,renameSync,rmSync,writeFileSync} from 'node:fs';
5
+ import {homedir} from 'node:os';
6
+ import {randomBytes} from 'node:crypto';
7
+ import {win32} from 'node:path';
8
+ import {canonicalWindowsLocalFile,isWindowsChildPath} from './native-path-contract.mjs';
9
+ import {inspectWindowsCredentialAcl,inspectWindowsPrivateDirectoryAcl} from './windows-credential-boundary.mjs';
10
+
11
+ const deny=()=>{throw Error('DEVICE_WINDOWS_PRIVATE_STORE_DENIED');};
12
+ const verifiedUpdate=Symbol('windows-private-preverified-update');
13
+ const sidPattern=/^S-1-\d+(?:-\d+){1,15}$/;
14
+ function nativeTool(name){
15
+ const root=process.env.SystemRoot||'C:\\Windows';
16
+ canonicalWindowsLocalFile(root+'\\System32');
17
+ return win32.join(root,'System32',name);
18
+ }
19
+ function runWin(name,args,{run=spawnSync,maxBuffer=8192}={}){
20
+ const res=run(nativeTool(name),args,{shell:false,windowsHide:true,
21
+ encoding:'utf8',timeout:20000,maxBuffer,stdio:'pipe'});
22
+ if(res.error||res.signal||res.status!==0)deny();
23
+ return String(res.stdout||'');
24
+ }
25
+ function currentSid({run=spawnSync}={}){
26
+ const stdout=runWin('whoami.exe',['/user','/fo','csv','/nh'],{run});
27
+ const sid=stdout.match(/S-1-\d+(?:-\d+){1,15}/)?.[0];
28
+ if(!sidPattern.test(sid||''))deny();
29
+ return sid;
30
+ }
31
+ function checkStore(store,{home=homedir()}={}){
32
+ if(process.platform!=='win32')deny();
33
+ canonicalWindowsLocalFile(home);
34
+ isWindowsChildPath(store,home);
35
+ if(!store.toLowerCase().endsWith('\\dev-credentials'))deny();
36
+ const parent=win32.dirname(store);
37
+ canonicalWindowsLocalFile(parent);
38
+ isWindowsChildPath(parent,home);
39
+ for(const item of [home,parent]){
40
+ const st=lstatSync(item);
41
+ if(!st.isDirectory()||st.isSymbolicLink()||
42
+ realpathSync(item).toLowerCase()!==item.toLowerCase())deny();
43
+ }
44
+ return home;
45
+ }
46
+ export function parseWindowsLogonSids(text){
47
+ if(typeof text!=='string'||text.length>8192)deny();
48
+ const numeric=text.match(/S-1-5-5-\d+-\d+/g)||[];
49
+ // icacls sometimes resolves S-1-5-5-X-Y as LogonSessionId_X_Y.
50
+ const named=[...text.matchAll(/LogonSessionId_(\d+)_(\d+)/gi)]
51
+ .map(match=>'S-1-5-5-'+match[1]+'-'+match[2]);
52
+ return [...new Set([...numeric,...named])];
53
+ }
54
+ function sealAcl(path,{directory=false,run=spawnSync}={}){
55
+ const sid=currentSid({run});
56
+ const suffix=directory?':(OI)(CI)F':':F';
57
+ runWin('icacls.exe',[path,'/inheritance:r','/grant:r','*'+sid+suffix,
58
+ '/grant:r','*S-1-5-18'+suffix],{run});
59
+ // Task Scheduler interactive tokens can leave an explicit per-logon SID on
60
+ // freshly written files. /grant:r replaces only grants for named SIDs; it
61
+ // does not remove this extra entry, which the independent ACL verifier denies.
62
+ // Remove only session SIDs, never broaden the user/SYSTEM allowlist.
63
+ const aclText=runWin('icacls.exe',[path],{run});
64
+ // icacls may resolve the same SID to NT AUTHORITY\\LogonSessionId_N_N.
65
+ // Match both localized display forms without granting any new identity.
66
+ const logonSids=parseWindowsLogonSids(aclText);
67
+ for(const logonSid of logonSids){
68
+ runWin('icacls.exe',[path,'/remove:g','*'+logonSid],{run});
69
+ }
70
+ // Windows service tokens may create new files owned by Administrators even
71
+ // when the creator is LocalSystem. Ensure the owner matches the running SID
72
+ // before the independent NTFS owner/ACL verification.
73
+ if(sid==='S-1-5-18')runWin('icacls.exe',[path,'/setowner','*S-1-5-18'],{run});
74
+ }
75
+ export function ensureWindowsPrivateStore(store,{home=homedir(),run=spawnSync}={}){
76
+ if(process.platform!=='win32')deny();
77
+ try{
78
+ canonicalWindowsLocalFile(home);
79
+ isWindowsChildPath(store,home);
80
+ const base=win32.dirname(store);
81
+ canonicalWindowsLocalFile(base);
82
+ isWindowsChildPath(base,home);
83
+ if(!store.toLowerCase().endsWith('\\dev-credentials'))deny();
84
+ const existed=existsSync(store);
85
+ if(!existed){
86
+ if(!existsSync(base))mkdirSync(base,{recursive:true});
87
+ const parent=lstatSync(base);
88
+ if(!parent.isDirectory()||parent.isSymbolicLink()||
89
+ realpathSync(base).toLowerCase()!==base.toLowerCase())deny();
90
+ mkdirSync(store);
91
+ sealAcl(store,{directory:true,run});
92
+ }
93
+ checkStore(store,{home});
94
+ inspectWindowsPrivateDirectoryAcl({directory:store,home});
95
+ return Object.freeze({ready:true,created:!existed,aclVerified:true});
96
+ }catch{deny();}
97
+ }
98
+ function verifyFile(file,{home=homedir()}={}){
99
+ const store=win32.dirname(file);
100
+ checkStore(store,{home});
101
+ // The native file snapshot also checks its protected parent directory.
102
+ // Avoid a duplicate PowerShell invocation in every credential operation.
103
+ inspectWindowsCredentialAcl({file,home});
104
+ }
105
+ // Seal a newly created exclusive lock using the same owner/SYSTEM ACL proof
106
+ // as credentials. Used by #327 S2 for Windows logoff/reboot recovery.
107
+ export function sealWindowsPrivateFile(file,{home=homedir()}={}){
108
+ try{
109
+ const store=win32.dirname(file);
110
+ checkStore(store,{home});
111
+ const stat=lstatSync(file);
112
+ if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1)deny();
113
+ sealAcl(file);
114
+ verifyFile(file,{home});
115
+ return true;
116
+ }catch{deny();}
117
+ }
118
+ export function readWindowsPrivate(file,{home=homedir()}={}){
119
+ try{
120
+ verifyFile(file,{home});
121
+ return readFileSync(file,'utf8');
122
+ }catch{deny();}
123
+ }
124
+ // A one-use update capability keeps the old credential ACL verification and
125
+ // the new credential ACL verification, without re-launching PowerShell twice
126
+ // for an unchanged old file. It never skips the OS owner/DACL checks.
127
+ export function readWindowsPrivateForUpdate(file,{home=homedir()}={}){
128
+ try{
129
+ verifyFile(file,{home});
130
+ const initial=readFileSync(file,'utf8');
131
+ const stat=lstatSync(file);
132
+ if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1)deny();
133
+ let consumed=false;
134
+ return Object.freeze({content:initial,replace(value){
135
+ if(consumed)deny();
136
+ consumed=true;
137
+ try{
138
+ const current=lstatSync(file);
139
+ if(!current.isFile()||current.isSymbolicLink()||current.nlink!==1||
140
+ current.size!==stat.size||current.mtimeMs!==stat.mtimeMs||
141
+ current.ctimeMs!==stat.ctimeMs||readFileSync(file,'utf8')!==initial)deny();
142
+ return atomicWindowsPrivate(file,value,{replace:true,home,
143
+ [verifiedUpdate]:true});
144
+ }catch{deny();}
145
+ }});
146
+ }catch{deny();}
147
+ }
148
+ export function atomicWindowsPrivate(file,value,{replace=false,home=homedir(),run=spawnSync,...proof}={}){
149
+ let temp;
150
+ try{
151
+ if(typeof value!=='string'||Buffer.byteLength(value)>8192||Buffer.byteLength(value)<1)deny();
152
+ const store=win32.dirname(file);
153
+ canonicalWindowsLocalFile(file);
154
+ isWindowsChildPath(file,store);
155
+ // For replacement, existing file verification already checks the parent
156
+ // directory and file ACLs. New files still require a protected store.
157
+ if(replace){
158
+ if(proof[verifiedUpdate]!==true)verifyFile(file,{home});
159
+ else checkStore(store,{home});
160
+ }else {ensureWindowsPrivateStore(store,{home,run});if(existsSync(file))deny();}
161
+ temp=file+'.tmp-'+randomBytes(12).toString('hex');
162
+ writeFileSync(temp,value,{flag:'wx'});
163
+ // The protected parent directory and successful SID-specific icacls seal
164
+ // protect the temporary file. After atomic rename, verify the final file
165
+ // and parent with a fresh independent native ACL snapshot.
166
+ sealAcl(temp,{run});
167
+ if(!replace&&existsSync(file))deny();
168
+ renameSync(temp,file);
169
+ // Windows file replacement can preserve the destination security descriptor.
170
+ // Seal the final file as well, then independently verify its owner/DACL.
171
+ sealAcl(file,{run});
172
+ verifyFile(file,{home});
173
+ return Object.freeze({written:true,aclVerified:true});
174
+ }catch{deny();
175
+ }finally{if(temp&&existsSync(temp))rmSync(temp,{force:true});}
176
+ }
@@ -0,0 +1,34 @@
1
+ // #310 Windows native per-user agent lifecycle. Explicit opt-in only.
2
+ // No admin service, shell invocation, token copy, or implicit enrolment.
3
+ import {spawnSync} from 'node:child_process';
4
+ import {win32} from 'node:path';
5
+ import {canonicalWindowsLocalFile} from './native-path-contract.mjs';
6
+
7
+ const deny=()=>{throw Error('DEVICE_WINDOWS_LIFECYCLE_DENIED');};
8
+ const TASK='RemoteShell Device Agent (User)';
9
+ const safePath=value=>{try{canonicalWindowsLocalFile(value);return true;}catch{return false;}};
10
+ const quote=value=>'"'+value.replaceAll('"','""')+'"';
11
+ export function windowsUserPlan({action,nodeBin,agentScript,os='win32'}={}){
12
+ if(os!=='win32'||!['install','start','stop','status','uninstall'].includes(action))deny();
13
+ if(action==='install'&&(!safePath(nodeBin)||!safePath(agentScript)))deny();
14
+ // Task Scheduler only supports a single command string in /TR. Paths are
15
+ // validated and quoted, with no cmd.exe or PowerShell in the execution path.
16
+ const base=['/TN',TASK];
17
+ if(action==='install')return Object.freeze({program:'schtasks.exe',
18
+ args:['/Create','/SC','ONLOGON','/RL','LIMITED',...base,
19
+ '/TR',quote(win32.normalize(nodeBin))+' '+quote(win32.normalize(agentScript))+' dev-heartbeat'],
20
+ task:TASK,autostart:true,credentialsPreserved:true,approvalRequired:true});
21
+ if(action==='start')return Object.freeze({program:'schtasks.exe',args:['/Run',...base],task:TASK,credentialsPreserved:true});
22
+ if(action==='stop')return Object.freeze({program:'schtasks.exe',args:['/End',...base],task:TASK,credentialsPreserved:true});
23
+ if(action==='status')return Object.freeze({program:'schtasks.exe',args:['/Query',...base,'/FO','LIST'],task:TASK,credentialsPreserved:true});
24
+ return Object.freeze({program:'schtasks.exe',args:['/Delete',...base,'/F'],task:TASK,credentialsPreserved:true});
25
+ }
26
+ export function runWindowsUserPlan(options,{run=spawnSync,confirmed=false}={}){
27
+ if(!confirmed)deny();
28
+ const plan=windowsUserPlan(options);
29
+ const result=run(plan.program,plan.args,{shell:false,windowsHide:true,encoding:'utf8',
30
+ timeout:10000,maxBuffer:16384,stdio:'pipe'});
31
+ if(result?.error||result?.signal||result?.status!==0)deny();
32
+ return Object.freeze({action:options.action,task:plan.task,commandSucceeded:true,
33
+ connected:false,dcReady:false,credentialsPreserved:true});
34
+ }