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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/LICENSE +26 -0
  2. package/NOTICE +20 -0
  3. package/bin/dev-agent-client.mjs +228 -0
  4. package/bin/dev-agent-runner.mjs +60 -0
  5. package/bin/dev-api-client.mjs +31 -0
  6. package/bin/dev-auto-worker.mjs +25 -0
  7. package/bin/dev-browser-open.mjs +12 -0
  8. package/bin/dev-dogfood-read.mjs +3 -0
  9. package/bin/dev-heartbeat-service.mjs +77 -0
  10. package/bin/dev-pairing-client.mjs +63 -0
  11. package/bin/dev-secrets.mjs +33 -0
  12. package/bin/dev-setup-recovery.mjs +34 -0
  13. package/bin/dev-signer-pin.mjs +22 -0
  14. package/bin/device.mjs +363 -0
  15. package/bin/enrollment-client.mjs +105 -0
  16. package/bin/install-acquire.mjs +89 -0
  17. package/bin/install-integrity.mjs +74 -0
  18. package/bin/install-plan.mjs +43 -0
  19. package/bin/lifecycle.mjs +172 -0
  20. package/bin/native-path-contract.mjs +23 -0
  21. package/bin/remoteshell-device-install.cmd +17 -0
  22. package/bin/remoteshell-device-install.ps1 +17 -0
  23. package/bin/remoteshell-device-install.sh +15 -0
  24. package/bin/remoteshell-device-preflight.cmd +10 -0
  25. package/bin/remoteshell-device-preflight.ps1 +10 -0
  26. package/bin/remoteshell-easy-diagnose.ps1 +32 -0
  27. package/bin/remoteshell-easy-install.ps1 +289 -0
  28. package/bin/remoteshell-easy-install.sh +71 -0
  29. package/bin/remoteshell-easy-uninstall.ps1 +124 -0
  30. package/bin/windows-credential-boundary.mjs +106 -0
  31. package/bin/windows-install-layout.mjs +28 -0
  32. package/bin/windows-native-installer.mjs +88 -0
  33. package/bin/windows-private-store.mjs +163 -0
  34. package/bin/windows-user-lifecycle.mjs +34 -0
  35. package/npm-shrinkwrap.json +8591 -0
  36. package/package.json +27 -4
  37. package/shared/lib/bounded-search-contract.mjs +5 -0
  38. package/shared/lib/bounded-search-policy.mjs +24 -0
  39. package/shared/lib/config.mjs +14 -0
  40. package/shared/lib/contracts.mjs +26 -0
  41. package/shared/lib/dc-generic-policy.mjs +102 -0
  42. package/shared/lib/dc-relay-contract.mjs +42 -0
  43. package/shared/lib/dc-tool-catalog.mjs +67 -0
  44. package/shared/lib/dev-dc-relay-contract.mjs +20 -0
  45. package/shared/lib/dev-paged-output.mjs +32 -0
  46. package/shared/lib/dev-root-exclusions.mjs +56 -0
  47. package/shared/lib/errors.mjs +9 -0
  48. package/shared/lib/events.mjs +5 -0
  49. package/shared/lib/execution-policy.mjs +41 -0
  50. package/shared/lib/isolated-read-boundary.mjs +50 -0
  51. package/shared/lib/isolated-read-policy.mjs +29 -0
  52. package/shared/lib/lifecycle-events.mjs +13 -0
  53. package/shared/lib/runtime-timing.mjs +9 -0
  54. package/shared/lib/synthetic-auxiliary-policy.mjs +21 -0
  55. package/shared/lib/synthetic-write-policy.mjs +52 -0
  56. package/shared/lib/tool-registry.mjs +58 -0
  57. package/src/config/l2-dev-oci-credential.mjs +39 -0
  58. package/src/config/p2-private-credential.mjs +15 -0
  59. package/src/connection/dev-dogfood-processes.mjs +25 -0
  60. package/src/connection/dev-dogfood-read.mjs +64 -0
  61. package/src/connection/dev-dogfood-task.mjs +113 -0
  62. package/src/connection/dev-dogfood-write.mjs +62 -0
  63. package/src/connection/dev-file-task.mjs +119 -0
  64. package/src/connection/dev-r4-file-task.mjs +56 -0
  65. package/src/connection/dev-read-tools.mjs +134 -0
  66. package/src/connection/dev-root-scopes.mjs +82 -0
  67. package/src/core/c1-dc-transport.mjs +26 -0
  68. package/src/core/c1-startup.mjs +22 -0
  69. package/src/core/c1-supervisor.mjs +111 -0
  70. package/src/core/c1-worker.mjs +88 -0
  71. package/src/core/fixture.txt +2 -0
  72. package/src/dc/dc-access-readiness.mjs +31 -0
  73. package/src/dc/dev-dc-relay.mjs +47 -0
  74. package/src/device-agent/main.mjs +1 -0
  75. package/src/gateway-keepalive.mjs +73 -0
  76. package/src/main.mjs +434 -0
  77. package/src/policy/bounded-search-adapter.mjs +115 -0
  78. package/src/policy/isolated-read-adapter.mjs +50 -0
  79. package/src/policy/isolated-read-mount.mjs +27 -0
  80. package/src/policy/synthetic-auxiliary-adapter.mjs +75 -0
  81. package/src/policy/synthetic-file-adapter.mjs +26 -0
  82. package/src/policy/synthetic-file-transaction.mjs +87 -0
  83. package/src/policy/synthetic-write-adapter.mjs +151 -0
  84. package/src/policy/synthetic-write-mount.mjs +23 -0
  85. package/src/policy/verified-bounded-search.mjs +12 -0
  86. package/src/policy/verified-isolated-read.mjs +15 -0
  87. package/src/policy/verified-synthetic-write.mjs +14 -0
  88. package/README.md +0 -3
@@ -0,0 +1,289 @@
1
+ # RemoteShell #310 Windows no-prerequisite DEV installer.
2
+ # Requires only built-in Windows PowerShell 5.1. Includes isolated Node runtime.
3
+ param([switch]$CheckOnly,[switch]$SkipPair,[switch]$Background)
4
+ $ErrorActionPreference='Stop'
5
+ $ProgressPreference='SilentlyContinue'
6
+ $source=Split-Path -Parent $MyInvocation.MyCommand.Path
7
+ $manifestFile=Join-Path $source 'manifest.json'
8
+ $phase='VERIFY'
9
+ $reportDir=$null
10
+ function Demand($ok,[string]$reason){if(-not $ok){throw $reason}}
11
+ function Digest($file){return (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant()}
12
+ function Step($label,$exe,[string[]]$parameters,[int]$limit=240){
13
+ $out=Join-Path $reportDir ($label+'.out')
14
+ $err=Join-Path $reportDir ($label+'.err')
15
+ $argsText=($parameters | ForEach-Object {if($_ -match '\s') {'"'+($_ -replace '"','')+'"'} else {$_}}) -join ' '
16
+ # In Windows PowerShell 5.1 -PassThru without -Wait can yield null ExitCode.
17
+ $child=Start-Process -FilePath $exe -ArgumentList $argsText -Wait -PassThru -RedirectStandardOutput $out -RedirectStandardError $err
18
+ Demand ($null -ne $child.ExitCode -and $child.ExitCode -eq 0) ($label+'_FAILED_EXIT_'+$child.ExitCode)
19
+ Write-Host ('[PASS] '+$label)
20
+ }
21
+ function StageComplete([string]$root){
22
+ try {
23
+ $agentFile=Join-Path $root 'node_modules\@remoteshell\device\package.json'
24
+ $dcFile=Join-Path $root 'node_modules\@wonderwhy-er\desktop-commander\package.json'
25
+ $sdkFile=Join-Path $root 'node_modules\@modelcontextprotocol\sdk\package.json'
26
+ $cliFile=Join-Path $root 'node_modules\@remoteshell\device\bin\device.mjs'
27
+ foreach($file in @($agentFile,$dcFile,$sdkFile,$cliFile)){
28
+ if(-not (Test-Path -LiteralPath $file -PathType Leaf)){return $false}
29
+ }
30
+ $a=Get-Content -LiteralPath $agentFile -Raw | ConvertFrom-Json
31
+ $d=Get-Content -LiteralPath $dcFile -Raw | ConvertFrom-Json
32
+ $k=Get-Content -LiteralPath $sdkFile -Raw | ConvertFrom-Json
33
+ return ($a.name -eq '@remoteshell/device' -and $a.version -eq '0.1.0' -and
34
+ $d.version -eq '0.3.1' -and $k.version -eq '1.32.1')
35
+ }catch{return $false}
36
+ }
37
+
38
+
39
+ function StartRegisteredUserAgent([string]$node,[string]$cli,[string]$log){
40
+ # The login-started Node console must not appear to the Windows user.
41
+ # wscript.exe launches the private Agent with window style 0 (hidden).
42
+ # The stable installed CLI is used, never the temporary staging CLI.
43
+ $phase='USER_WORKER'
44
+ $localPath=[Environment]::GetFolderPath('LocalApplicationData')
45
+ $root=Join-Path $localPath 'RemoteShell'
46
+ $installedCli=Join-Path $root 'DeviceAgent\install\node_modules\@remoteshell\device\bin\device.mjs'
47
+ $launcher=Join-Path $root 'EasyInstall\agent-autostart.vbs'
48
+ $wscript=Join-Path $env:WINDIR 'System32\wscript.exe'
49
+ Demand (Test-Path -LiteralPath $node -PathType Leaf) 'PRIVATE_NODE_MISSING'
50
+ Demand (Test-Path -LiteralPath $installedCli -PathType Leaf) 'INSTALLED_AGENT_CLI_MISSING'
51
+ Demand (Test-Path -LiteralPath $wscript -PathType Leaf) 'WINDOWS_SCRIPT_HOST_MISSING'
52
+ $vb=@(
53
+ 'Set fso = CreateObject("Scripting.FileSystemObject")',
54
+ 'Set sh = CreateObject("WScript.Shell")',
55
+ 'base = fso.GetParentFolderName(WScript.ScriptFullName)',
56
+ 'root = fso.GetParentFolderName(base)',
57
+ 'node = base & "\runtime-v22\node.exe"',
58
+ 'cli = root & "\DeviceAgent\install\node_modules\@remoteshell\device\bin\device.mjs"',
59
+ 'sh.Run Chr(34) & node & Chr(34) & " " & Chr(34) & cli & Chr(34) & " dev-heartbeat", 0, False'
60
+ )
61
+ Demand (-not (Test-Path -LiteralPath $launcher)) 'EXISTING_LAUNCHER_REVIEW_REQUIRED'
62
+ Set-Content -LiteralPath $launcher -Value $vb -Encoding Unicode -ErrorAction Stop
63
+ $runKey='HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'
64
+ $runName='RemoteShell-DEV-User-Agent'
65
+ $runValue=('"'+$wscript+'" "'+$launcher+'"')
66
+ $prior=Get-ItemProperty -LiteralPath $runKey -Name $runName -ErrorAction SilentlyContinue
67
+ Demand (-not $prior) 'EXISTING_USER_AUTOSTART_REVIEW_REQUIRED'
68
+ New-ItemProperty -LiteralPath $runKey -Name $runName -Value $runValue -PropertyType String -ErrorAction Stop | Out-Null
69
+ Add-Content -LiteralPath $log -Value 'USER_AUTOSTART=HKCU_RUN_HIDDEN_WSCRIPT' -Encoding UTF8
70
+ $existing=@(Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object {
71
+ $_.ExecutablePath -ieq $node -and $_.CommandLine -like ('*'+$installedCli+'*dev-heartbeat*')
72
+ })
73
+ Demand ($existing.Count -eq 0) 'DUPLICATE_USER_AGENT_DENIED'
74
+ $child=Start-Process -FilePath $wscript -ArgumentList ('"'+$launcher+'"') -PassThru -WindowStyle Hidden
75
+ Demand ($null -ne $child -and $child.Id -gt 0) 'USER_WORKER_START_FAILED'
76
+ Start-Sleep -Seconds 5
77
+ $live=@(Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object {
78
+ $_.ExecutablePath -ieq $node -and $_.CommandLine -like ('*'+$installedCli+'*dev-heartbeat*')
79
+ })
80
+ Demand ($live.Count -eq 1) 'USER_WORKER_NOT_RUNNING'
81
+ Add-Content -LiteralPath $log -Value 'USER_WORKER_PROCESS=PASS; GATEWAY_ONLINE_NOT_YET_VERIFIED' -Encoding UTF8
82
+ }
83
+ function IsRegistered([string]$node,[string]$cli){
84
+ $state=& $node $cli status 2>$null
85
+ Demand ($LASTEXITCODE -eq 0) 'REGISTERED_STATUS_FAILED'
86
+ $parsed=($state -join '') | ConvertFrom-Json
87
+ return ($parsed.installed -eq $true -and $parsed.registered -eq $true)
88
+ }
89
+
90
+ try{
91
+ Demand (Test-Path -LiteralPath $manifestFile -PathType Leaf) 'MANIFEST_MISSING'
92
+ $manifest=Get-Content -LiteralPath $manifestFile -Raw | ConvertFrom-Json
93
+ Demand ($manifest.schema -eq 1 -and $manifest.platform -eq 'win32' -and $manifest.arch -eq 'x64' -and $manifest.devOnly -eq $true) 'MANIFEST_INVALID'
94
+ $paths=@{
95
+ node=(Join-Path $source 'runtime\node.exe');
96
+ npm=(Join-Path $source 'runtime\node_modules\npm\bin\npm-cli.js');
97
+ archive=(Join-Path $source 'agent.tgz')
98
+ }
99
+ foreach($key in @('node','npm','archive')){
100
+ Demand (Test-Path -LiteralPath $paths[$key] -PathType Leaf) ('MISSING_'+$key)
101
+ Demand ((Digest $paths[$key]) -eq $manifest.sha256.$key) ('HASH_MISMATCH_'+$key)
102
+ }
103
+ $who=[Security.Principal.WindowsIdentity]::GetCurrent().Name
104
+ $principal=New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
105
+ Demand (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) 'DO_NOT_RUN_AS_ADMIN'
106
+ Demand ([Environment]::Is64BitOperatingSystem) 'WINDOWS_X64_REQUIRED'
107
+ $homePath=[Environment]::GetFolderPath('UserProfile')
108
+ $localPath=[Environment]::GetFolderPath('LocalApplicationData')
109
+ Demand ($homePath -and $localPath -and (Test-Path -LiteralPath $localPath)) 'WINDOWS_PROFILE_MISSING'
110
+ Demand ($localPath -ieq (Join-Path $homePath 'AppData\Local')) 'FOREIGN_PROFILE_DENIED'
111
+ $agentInstall=Join-Path $localPath 'RemoteShell\DeviceAgent\install'
112
+ $oldCredentials=Join-Path $localPath 'RemoteShell\DeviceAgent\dev-credentials'
113
+ $resume=(Test-Path -LiteralPath $agentInstall -PathType Container)
114
+ if($resume){
115
+ Demand (-not $SkipPair) 'EXISTING_AGENT_PRESERVED'
116
+ # A failed/expired pairing is not a reason to reinstall or overwrite keys.
117
+ # Resume only a fully staged, currently unregistered installation.
118
+ $privateRuntime=Join-Path $localPath 'RemoteShell\EasyInstall\runtime-v22'
119
+ $node=Join-Path $privateRuntime 'node.exe'
120
+ $cli=Join-Path $agentInstall 'node_modules\@remoteshell\device\bin\device.mjs'
121
+ Demand (StageComplete $agentInstall) 'EXISTING_AGENT_INCOMPLETE_REVIEW_REQUIRED'
122
+ Demand (Test-Path -LiteralPath $node -PathType Leaf) 'EXISTING_PRIVATE_RUNTIME_MISSING'
123
+ Demand ((Digest $node) -eq $manifest.sha256.node) 'EXISTING_PRIVATE_RUNTIME_HASH_DENIED'
124
+ Demand (-not (IsRegistered $node $cli)) 'EXISTING_AGENT_ALREADY_REGISTERED'
125
+ $live=@(Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object {
126
+ $_.ExecutablePath -ieq $node -and $_.CommandLine -like ('*'+$cli+'*')
127
+ })
128
+ Demand ($live.Count -eq 0) 'EXISTING_AGENT_PROCESS_REVIEW_REQUIRED'
129
+ }else{
130
+ # A new install must not consume leftovers from a prior registration.
131
+ Demand (-not (Test-Path -LiteralPath $oldCredentials)) 'PREVIOUS_DEVICE_REGISTRATION_MUST_BE_REMOVED'
132
+ }
133
+ $version=& $paths.node '--version'
134
+ Demand ($LASTEXITCODE -eq 0 -and $version -match '^v22\.') 'BUNDLED_NODE_VERSION_DENIED'
135
+ if($CheckOnly){
136
+ Write-Host ('EASY_INSTALL_CHECK_PASS '+$version+' '+$who)
137
+ exit 0
138
+ }
139
+ $reportDir=Join-Path $localPath 'RemoteShell\EasyInstall\logs'
140
+ if(-not(Test-Path -LiteralPath $reportDir)){New-Item -ItemType Directory -Path $reportDir -Force|Out-Null}
141
+ $log=Join-Path $reportDir 'result.txt'
142
+ # Preserve prior status/error codes only; pair.out can carry private enrollment
143
+ # material and must never be backed up into a new distributable or shared path.
144
+ $priorLog=Join-Path $reportDir 'result.txt'
145
+ if(Test-Path -LiteralPath $priorLog -PathType Leaf){
146
+ $history=Join-Path $reportDir 'history'
147
+ if(-not(Test-Path -LiteralPath $history)){New-Item -ItemType Directory -Path $history -Force|Out-Null}
148
+ $stamp=Get-Date -Format 'yyyyMMdd-HHmmss-fff'
149
+ Copy-Item -LiteralPath $priorLog -Destination (Join-Path $history ('result-'+$stamp+'.txt')) -ErrorAction Stop
150
+ $priorError=Join-Path $reportDir 'pair.err'
151
+ if(Test-Path -LiteralPath $priorError -PathType Leaf){
152
+ # Raw stderr may be untrusted; preserve only known uppercase error codes.
153
+ Get-Content -LiteralPath $priorError | Where-Object {$_ -match '^DEVICE_[A-Z0-9_]+$'} |
154
+ Set-Content -LiteralPath (Join-Path $history ('pair-error-'+$stamp+'.txt')) -Encoding UTF8
155
+ }
156
+ }
157
+ Set-Content -LiteralPath $log -Value ('RemoteShell EasyInstall DEV '+(Get-Date -Format o)+' user='+$who) -Encoding UTF8
158
+ if($resume){
159
+ $phase='RESUME_PAIR'
160
+ Add-Content -LiteralPath $log -Value 'INSTALL_RESUME=PAIR_ONLY; PACKAGE_PRESERVED=true' -Encoding UTF8
161
+ Write-Host '[PASS] previously installed Agent verified; resuming Google approval only'
162
+ }else{
163
+ $phase='COPY_RUNTIME'
164
+ $privateRuntime=Join-Path $localPath 'RemoteShell\EasyInstall\runtime-v22'
165
+ if(-not(Test-Path -LiteralPath $privateRuntime)){
166
+ New-Item -ItemType Directory -Path $privateRuntime -Force|Out-Null
167
+ Copy-Item -LiteralPath (Join-Path $source 'runtime\node.exe') -Destination (Join-Path $privateRuntime 'node.exe')
168
+ New-Item -ItemType Directory -Path (Join-Path $privateRuntime 'node_modules') -Force|Out-Null
169
+ Copy-Item -LiteralPath (Join-Path $source 'runtime\node_modules\npm') -Destination (Join-Path $privateRuntime 'node_modules\npm') -Recurse
170
+ }
171
+ $node=Join-Path $privateRuntime 'node.exe'
172
+ $npm=Join-Path $privateRuntime 'node_modules\npm\bin\npm-cli.js'
173
+ Demand ((Digest $node) -eq $manifest.sha256.node -and (Digest $npm) -eq $manifest.sha256.npm) 'PRIVATE_RUNTIME_HASH_DENIED'
174
+ $env:PATH=$privateRuntime+';'+$env:PATH
175
+ $phase='STAGE'
176
+ $stage=Join-Path $localPath 'RemoteShell\EasyInstall\stage'
177
+ if(Test-Path -LiteralPath $stage){
178
+ Demand (StageComplete $stage) 'PREVIOUS_STAGE_INCOMPLETE_REVIEW_FIRST'
179
+ Write-Host '[PASS] stage-agent (verified existing dependencies)'
180
+ }else{
181
+ New-Item -ItemType Directory -Path $stage -Force|Out-Null
182
+ Step 'stage-agent' $node @($npm,'install','--prefix',$stage,'--ignore-scripts','--no-audit','--no-fund','--no-package-lock','--no-save',$paths.archive,'--fetch-retries=1','--fetch-timeout=90000')
183
+ Demand (StageComplete $stage) 'DEVICE_DEPENDENCY_VALIDATION_FAILED'
184
+ }
185
+ $cli=Join-Path $stage 'node_modules\@remoteshell\device\bin\device.mjs'
186
+ Demand (Test-Path -LiteralPath $cli -PathType Leaf) 'DEVICE_CLI_MISSING'
187
+ $phase='PREFLIGHT'
188
+ Step 'preflight' $node @($cli,'install-preflight') 20
189
+ $phase='INSTALL'
190
+ Step 'install' $node @($cli,'install') 240
191
+ Step 'status' $node @($cli,'status') 20
192
+ Add-Content -LiteralPath $log -Value 'AGENT_INSTALLED=true; REGISTERED=false; CONNECTED=false' -Encoding UTF8
193
+ Write-Host 'RemoteShell Agent package installed; Google owner approval is separate.'
194
+ Demand (-not (IsRegistered $node $cli)) 'UNEXPECTED_OLD_DEVICE_REGISTRATION_DENIED'
195
+ if($SkipPair){
196
+ Add-Content -LiteralPath $log -Value 'PAIR=SKIPPED_UNREGISTERED; USER_WORKER=NOT_STARTED' -Encoding UTF8
197
+ exit 0
198
+ }
199
+ }
200
+ $phase='PAIR'
201
+ $url='https://ailab-remoteshell.duckdns.org/dev/'
202
+ $out=Join-Path $reportDir 'pair.out';$err=Join-Path $reportDir 'pair.err'
203
+ $pair=Start-Process -FilePath $node -ArgumentList ('"'+$cli+'" windows-pair '+$url) -PassThru -RedirectStandardOutput $out -RedirectStandardError $err
204
+ $opened=$false;$approved=$false;$pairId='none';$pairStart=Get-Date;$pairDeadline=$pairStart.AddMinutes(5)
205
+ Add-Content -LiteralPath $log -Value ('PAIR_REQUEST_STARTED='+$pairStart.ToString('o')+'; PHASE=WAIT_OWNER_BROWSER') -Encoding UTF8
206
+ try{
207
+ $deadline=(Get-Date).AddMinutes(6)
208
+ while((Get-Date) -lt $deadline){
209
+ if(Test-Path -LiteralPath $out){
210
+ foreach($line in @(Get-Content -LiteralPath $out -ErrorAction SilentlyContinue)){
211
+ try{$obj=$line | ConvertFrom-Json}catch{continue}
212
+ if(-not $opened -and $obj.next -eq 'approve-device-in-browser' -and $obj.ownerApprovalRequired -and $obj.approval_url){
213
+ $link=[uri]$obj.approval_url
214
+ Demand ($link.Scheme -eq 'https' -and $link.Host -eq 'ailab-remoteshell.duckdns.org' -and $link.AbsolutePath.StartsWith('/dev/')) 'PAIR_APPROVAL_URL_DENIED'
215
+ $pairId=($link.AbsolutePath -split '/')[-1]
216
+ Demand ($pairId -match '^[0-9a-fA-F-]{36}$') 'PAIR_REQUEST_ID_INVALID'
217
+ Add-Content -LiteralPath $log -Value ('PAIR_BROWSER_URL_CREATED='+$pairStart.ToString('o')+'; PAIR_ID='+$pairId+'; APPROVAL_DEADLINE='+$pairDeadline.ToString('o')) -Encoding UTF8
218
+ Write-Host 'Google approval: check account and approve the device in the browser.'
219
+ Start-Process $link.AbsoluteUri
220
+ Add-Content -LiteralPath $log -Value ('PAIR_BROWSER_OPEN_ATTEMPT='+((Get-Date).ToString('o'))+'; PAIR_ID='+$pairId) -Encoding UTF8
221
+ $opened=$true
222
+ }
223
+ if($obj.registered -eq $true -and $obj.connected -eq $true){
224
+ $approved=$true
225
+ Add-Content -LiteralPath $log -Value ('PAIR_AGENT_CONNECTED='+((Get-Date).ToString('o'))+'; PAIR_ID='+$pairId) -Encoding UTF8
226
+ }
227
+ }
228
+ }
229
+ $pair.Refresh()
230
+ if($pair.HasExited){break}
231
+ Start-Sleep -Milliseconds 700
232
+ }
233
+ $pair.Refresh()
234
+ if(-not $approved){
235
+ $reason=if(-not $opened){'PAIR_BROWSER_NOT_OPENED'}elseif((Get-Date) -ge $pairDeadline){'PAIR_APPROVAL_WINDOW_EXPIRED_OR_NO_SERVER_CONFIRMATION'}else{'PAIR_AGENT_TERMINATED_OR_SERVER_REJECTED'}
236
+ $exitStatus=if($pair.HasExited){[string]$pair.ExitCode}else{'RUNNING'}
237
+ Add-Content -LiteralPath $log -Value ('PAIR_DIAGNOSTIC='+$reason+'; PAIR_ID='+$pairId+'; PROCESS_EXIT='+$exitStatus+'; AT='+((Get-Date).ToString('o'))) -Encoding UTF8
238
+ throw $reason
239
+ }
240
+ Demand ($pair.HasExited -and ($null -eq $pair.ExitCode -or $pair.ExitCode -eq 0)) 'PAIR_PROCESS_EXIT_NONZERO'
241
+ Add-Content -LiteralPath $log -Value 'PAIR=PASS; GOOGLE_OWNER_APPROVAL=true' -Encoding UTF8
242
+ Write-Host '[PASS] Google owner approval and first heartbeat'
243
+ }finally{if(-not $pair.HasExited){try{$pair.Kill()}catch{}}}
244
+ $phase='START_AGENT'
245
+ Demand (IsRegistered $node $cli) 'OWNER_PAIRING_REGISTRATION_NOT_PERSISTED'
246
+ if($Background){
247
+ # Opt-in only: current user HKCU Run/VBS, no admin/system service.
248
+ StartRegisteredUserAgent $node $cli $log
249
+ Add-Content -LiteralPath $log -Value 'RUN_MODE=BACKGROUND; USER_AUTOSTART=ENABLED' -Encoding UTF8
250
+ }else{
251
+ # Default foreground: no autostart entry, no hidden launcher.
252
+ $runKey='HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'
253
+ Demand (-not (Get-ItemProperty -LiteralPath $runKey -Name 'RemoteShell-DEV-User-Agent' -ErrorAction SilentlyContinue)) 'EXISTING_USER_AUTOSTART_REVIEW_REQUIRED'
254
+ Demand (-not (Test-Path -LiteralPath (Join-Path $localPath 'RemoteShell\EasyInstall\agent-autostart.vbs'))) 'EXISTING_LAUNCHER_REVIEW_REQUIRED'
255
+ Add-Content -LiteralPath $log -Value 'RUN_MODE=FOREGROUND; USER_AUTOSTART=DISABLED' -Encoding UTF8
256
+ }
257
+ $phase='COMPLETE'
258
+ # Device enrollment is NOT AI connection authorization. An authenticated owner
259
+ # must create and approve a connection covering this exact new device before
260
+ # ChatGPT can obtain the live DC catalog. No automatic connection grant.
261
+ $connectionsUrl='https://ailab-remoteshell.duckdns.org/dev/connections'
262
+ Write-Host ('NEXT: Sign in with the same Google RS identity at '+$connectionsUrl)
263
+ Write-Host 'NEXT: Select this newly registered device, create and approve an AI connection; then refresh ChatGPT tools.'
264
+ Add-Content -LiteralPath $log -Value ('NEXT=VERIFY_OWNER_AI_CONNECTION; URL='+$connectionsUrl) -Encoding UTF8
265
+ Add-Content -LiteralPath $log -Value 'RESULT=INSTALL_AND_PAIR_PASS; AI_CONNECTION_AND_DC_READ_AND_USAGE_NOT_TESTED' -Encoding UTF8
266
+ if(-not $Background){
267
+ $phase='FOREGROUND'
268
+ Write-Host 'Foreground Agent started. Keep this window open; Ctrl+C stops the session.'
269
+ & $node $cli dev-heartbeat
270
+ Demand ($LASTEXITCODE -eq 0) 'FOREGROUND_AGENT_EXIT_NONZERO'
271
+ }
272
+ }catch{
273
+ Write-Host ('[STOP] '+$phase+': '+$_.Exception.Message)
274
+ if($reportDir -and (Test-Path -LiteralPath $reportDir)){
275
+ Add-Content -LiteralPath (Join-Path $reportDir 'result.txt') -Value ('RESULT=FAIL; PHASE='+$phase+'; ERROR='+$_.Exception.Message+'; AT='+((Get-Date).ToString('o'))) -Encoding UTF8
276
+ if($phase -eq 'PAIR'){
277
+ $stderrFile=Join-Path $reportDir 'pair.err'
278
+ if(Test-Path -LiteralPath $stderrFile){
279
+ $known=@(Get-Content -LiteralPath $stderrFile | Where-Object {$_ -match '^DEVICE_[A-Z0-9_]+$'} | Select-Object -First 3)
280
+ foreach($errorCode in $known){Add-Content -LiteralPath (Join-Path $reportDir 'result.txt') -Value ('PAIR_AGENT_ERROR_CODE='+$errorCode) -Encoding UTF8}
281
+ }
282
+ }
283
+ }
284
+ exit 1
285
+ }finally{
286
+ if(-not $CheckOnly -and $reportDir -and (Test-Path -LiteralPath $reportDir -PathType Container)){
287
+ Write-Host ('Result: '+(Join-Path $reportDir 'result.txt'))
288
+ }
289
+ }
@@ -0,0 +1,71 @@
1
+ #!/bin/sh
2
+ # RS #310 private Ubuntu easy installer; Node not required before execution.
3
+ set -eu
4
+ umask 077
5
+ mode=install
6
+ run_mode=manual
7
+ confirm_linger=no
8
+ # Default stays manual; login/boot autostart are explicit user decisions.
9
+ case "$*" in
10
+ "") ;;
11
+ "--check-only") mode=check ;;
12
+ "--install-only") mode=install-only ;;
13
+ "--pair") mode=pair ;;
14
+ "--login") run_mode=login ;;
15
+ "--pair --login") mode=pair;run_mode=login ;;
16
+ "--boot --confirm-linger") run_mode=boot;confirm_linger=yes ;;
17
+ "--pair --boot --confirm-linger") mode=pair;run_mode=boot;confirm_linger=yes ;;
18
+ *) echo ARGS_DENIED >&2;exit 2 ;;
19
+ esac
20
+ base=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
21
+ [ "$(id -u)" -ne 0 ] || { echo DO_NOT_RUN_AS_ROOT >&2;exit 1;}
22
+ [ "$(uname -s)" = Linux ] && [ "$(uname -m)" = x86_64 ] || { echo LINUX_X64_REQUIRED >&2;exit 1;}
23
+ case "$(cat /proc/version 2>/dev/null || true)" in *icrosoft*|*WSL*)echo WSL_BETA_EXCLUDED >&2;exit 1;;esac
24
+ [ -f "$base/manifest.sha256" ] && [ -f "$base/runtime/node" ] && [ -f "$base/agent.tgz" ] || { echo KIT_FILES_MISSING >&2;exit 1;}
25
+ (cd "$base" && sha256sum -c manifest.sha256 >/dev/null) || { echo KIT_HASH_DENIED >&2;exit 1;}
26
+ case "$("$base/runtime/node" --version)" in v22.*):;;*)echo NODE22_REQUIRED >&2;exit 1;;esac
27
+ "$base/runtime/node" "$base/runtime/node_modules/npm/bin/npm-cli.js" --version >/dev/null 2>&1 || { echo NPM_BUNDLE_INVALID >&2;exit 1;}
28
+ [ -n "$HOME" ] && [ -d "$HOME" ] && [ "$HOME" != "/" ] || { echo HOME_DENIED >&2;exit 1;}
29
+ if [ "$mode" = check ];then echo EASY_INSTALL_LINUX_CHECK_PASS;exit 0;fi
30
+ private="$HOME/.local/share/remoteshell-easy"
31
+ runtime="$private/runtime-v22"
32
+ stage="$private/stage"
33
+ mkdir -p "$private"
34
+ if [ ! -d "$runtime" ];then cp -R "$base/runtime" "$runtime";fi
35
+ [ -x "$runtime/node" ] && [ -f "$runtime/node_modules/npm/bin/npm-cli.js" ] || { echo RUNTIME_INVALID >&2;exit 1;}
36
+ export PATH="$runtime:$PATH"
37
+ if [ "$mode" = pair ];then
38
+ cli="$HOME/.local/share/remoteshell-device/install/node_modules/@remoteshell/device/bin/device.mjs"
39
+ [ -f "$cli" ] || { echo AGENT_NOT_INSTALLED >&2;exit 1;}
40
+ if [ "$confirm_linger" = yes ];then
41
+ "$runtime/node" "$cli" setup https://ailab-remoteshell.duckdns.org/dev/ "$run_mode" --confirm-linger
42
+ else
43
+ "$runtime/node" "$cli" setup https://ailab-remoteshell.duckdns.org/dev/ "$run_mode"
44
+ fi
45
+ exit $?
46
+ fi
47
+ [ ! -e "$HOME/.local/share/remoteshell-device/install" ] || { echo EXISTING_AGENT_PRESERVED >&2;exit 1;}
48
+ [ ! -e "$stage" ] || { echo PREVIOUS_STAGE_EXISTS >&2;exit 1;}
49
+ mkdir -m 700 "$stage"
50
+ "$runtime/node" "$runtime/node_modules/npm/bin/npm-cli.js" install --prefix "$stage" --ignore-scripts --no-audit --no-fund --no-package-lock --no-save "$base/agent.tgz" || { echo STAGE_DEPENDENCY_FAILED >&2;exit 1;}
51
+ cli="$stage/node_modules/@remoteshell/device/bin/device.mjs"
52
+ [ -f "$cli" ] || { echo STAGE_AGENT_MISSING >&2;exit 1;}
53
+ "$runtime/node" "$cli" install-preflight
54
+ "$runtime/node" "$cli" install || { echo AGENT_INSTALL_FAILED >&2;exit 1;}
55
+ # The install receipt is in the user's permanent layout; the npm staging
56
+ # tree is disposable. Otherwise uninstall -> reinstall is blocked by stage.
57
+ installed_cli="$HOME/.local/share/remoteshell-device/install/node_modules/@remoteshell/device/bin/device.mjs"
58
+ [ -f "$installed_cli" ] || { echo INSTALLED_AGENT_MISSING >&2;exit 1;}
59
+ [ -d "$stage" ] && [ ! -L "$stage" ] || { echo STAGE_INVALID >&2;exit 1;}
60
+ rm -rf -- "$stage"
61
+ cli="$installed_cli"
62
+ echo EASY_INSTALL_LINUX_PASS_NOT_YET_PAIRED
63
+ if [ "$mode" = install ];then
64
+ if [ "$confirm_linger" = yes ];then
65
+ "$runtime/node" "$cli" setup https://ailab-remoteshell.duckdns.org/dev/ "$run_mode" --confirm-linger
66
+ else
67
+ "$runtime/node" "$cli" setup https://ailab-remoteshell.duckdns.org/dev/ "$run_mode"
68
+ fi
69
+ else
70
+ echo 'Pair later: sh install.sh --pair'
71
+ fi
@@ -0,0 +1,124 @@
1
+ # RemoteShell Windows x64 user-local EasyInstall uninstall.
2
+ # Independent of network, Google identity, RS server/device revoke and other OS accounts.
3
+ param([switch]$CheckOnly)
4
+ $ErrorActionPreference='Stop'
5
+ $phase='PRECHECK'
6
+ function Demand([bool]$ok,[string]$reason){if(-not $ok){throw $reason}}
7
+ function SafeDir([string]$path){
8
+ if(Test-Path -LiteralPath $path){
9
+ $f=Get-Item -LiteralPath $path -Force
10
+ Demand ($f.PSIsContainer -and -not ($f.Attributes -band [IO.FileAttributes]::ReparsePoint)) 'UNSAFE_DIRECTORY_DENIED'
11
+ }
12
+ }
13
+ $homePath=[Environment]::GetFolderPath('UserProfile')
14
+ $localPath=[Environment]::GetFolderPath('LocalApplicationData')
15
+ $root=Join-Path $localPath 'RemoteShell'
16
+ $agent=Join-Path $root 'DeviceAgent'
17
+ $install=Join-Path $agent 'install'
18
+ $credentials=Join-Path $agent 'dev-credentials'
19
+ $easy=Join-Path $root 'EasyInstall'
20
+ $privateRuntime=Join-Path $easy 'runtime-v22'
21
+ $stage=Join-Path $easy 'stage'
22
+ $node=Join-Path $privateRuntime 'node.exe'
23
+ $cli=Join-Path $install 'node_modules\@remoteshell\device\bin\device.mjs'
24
+ $stageCli=Join-Path $stage 'node_modules\@remoteshell\device\bin\device.mjs'
25
+ $launcher=Join-Path $easy 'agent-autostart.vbs'
26
+ $wscript=Join-Path $env:WINDIR 'System32\wscript.exe'
27
+ $runKey='HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'
28
+ $runName='RemoteShell-DEV-User-Agent'
29
+ $taskName='RemoteShell Device Agent (User)'
30
+ $reportDir=Join-Path $root 'UninstallLogs'
31
+ $report=Join-Path $reportDir 'easy-uninstall-result.txt'
32
+ function Report([string]$value){
33
+ Write-Host $value
34
+ Add-Content -LiteralPath $report -Value $value -Encoding UTF8
35
+ }
36
+ try {
37
+ $identity=[Security.Principal.WindowsIdentity]::GetCurrent()
38
+ $principal=New-Object Security.Principal.WindowsPrincipal($identity)
39
+ Demand ([Environment]::Is64BitOperatingSystem) 'WINDOWS_X64_REQUIRED'
40
+ Demand (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) 'DO_NOT_RUN_AS_ADMIN'
41
+ Demand ($homePath -and $localPath -and $localPath -ieq (Join-Path $homePath 'AppData\Local')) 'FOREIGN_PROFILE_DENIED'
42
+ foreach($d in @($homePath,(Join-Path $homePath 'AppData'),$localPath,$root,$agent,$install,$credentials,$easy,$privateRuntime,$stage)){SafeDir $d}
43
+ # Do not delete any other product directory, even under the same owner.
44
+ $run=Get-ItemProperty -LiteralPath $runKey -Name $runName -ErrorAction SilentlyContinue
45
+ $expected=('"'+$node+'" "'+$cli+'" dev-heartbeat')
46
+ $legacyStage=('"'+$node+'" "'+$stageCli+'" dev-heartbeat')
47
+ $hiddenStartup=('"'+$wscript+'" "'+$launcher+'"')
48
+ if($run){Demand ($run.$runName -ceq $expected -or $run.$runName -ceq $legacyStage -or $run.$runName -ceq $hiddenStartup) 'FOREIGN_AUTOSTART_DENIED'}
49
+ $task=Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
50
+ if($task){
51
+ $action=@($task.Actions)
52
+ Demand ($action.Count -eq 1) 'FOREIGN_TASK_DENIED'
53
+ Demand ($action[0].Execute -ieq $node -and $action[0].Arguments -like ('*'+$cli+'*dev-heartbeat*')) 'FOREIGN_TASK_DENIED'
54
+ Demand ($task.Principal.UserId -ieq $identity.Name -or $task.Principal.UserId -eq $identity.User.Value) 'FOREIGN_TASK_PRINCIPAL_DENIED'
55
+ }
56
+ $workers=@(Get-CimInstance Win32_Process -Filter "Name='node.exe'"|Where-Object {
57
+ $_.ExecutablePath -ieq $node -and ($_.CommandLine -like ('*'+$install+'*') -or $_.CommandLine -like ('*'+$stageCli+'*'))
58
+ })
59
+ foreach($w in $workers){
60
+ $owner=Invoke-CimMethod -InputObject $w -MethodName GetOwner
61
+ Demand ($owner.User -ieq $identity.Name.Split('\')[-1]) 'FOREIGN_PROCESS_DENIED'
62
+ }
63
+ if(Test-Path $install){
64
+ $receipt=Join-Path $install 'receipt.json'
65
+ Demand (Test-Path -LiteralPath $receipt -PathType Leaf) 'RECEIPT_MISSING'
66
+ $r=Get-Content -LiteralPath $receipt -Raw|ConvertFrom-Json
67
+ Demand ($r.schema -eq 1 -and $r.distribution -eq 'synthetic-private' -and $r.version -eq '0.1.0') 'FOREIGN_INSTALL_DENIED'
68
+ }
69
+ if(Test-Path $credentials){
70
+ $files=@(Get-ChildItem -LiteralPath $credentials -Force)
71
+ foreach($f in $files){
72
+ Demand (-not $f.PSIsContainer -and -not ($f.Attributes -band [IO.FileAttributes]::ReparsePoint)) 'FOREIGN_CREDENTIAL_ENTRY'
73
+ Demand ($f.Name -eq 'device.json' -or $f.Name -eq 'device-key.pem' -or $f.Name -match '^device\.json\.tmp-[a-z0-9]{8,64}$') 'FOREIGN_CREDENTIAL_FILE'
74
+ }
75
+ }
76
+ if($CheckOnly){
77
+ Write-Host ('EASY_UNINSTALL_CHECK_PASS user='+$identity.Name+
78
+ ' workers='+$workers.Count+' installed='+(Test-Path $install)+
79
+ ' credentials='+(Test-Path $credentials))
80
+ exit 0
81
+ }
82
+ if(-not (Test-Path -LiteralPath $reportDir)){New-Item -Path $reportDir -ItemType Directory -Force|Out-Null}
83
+ Set-Content -LiteralPath $report -Value ('RemoteShell easy uninstall '+(Get-Date -Format o)+' user='+$identity.Name) -Encoding UTF8
84
+ $phase='STOP'
85
+ $order=@($workers|Sort-Object @{Expression={if($_.CommandLine -like '*desktop-commander*'){0}elseif($_.CommandLine -like '*main.mjs*'){1}else{2}}})
86
+ foreach($w in $order){Stop-Process -Id $w.ProcessId -Force -ErrorAction Stop}
87
+ Report ('AGENT_PROCESSES_STOPPED='+$order.Count)
88
+ $phase='AUTOSTART'
89
+ if($task){Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction Stop}
90
+ if($run){Remove-ItemProperty -LiteralPath $runKey -Name $runName -ErrorAction Stop}
91
+ # Foreground-only installation intentionally has no autostart registration.
92
+ # Treat absence as a valid clean uninstall, not a failed removal.
93
+ if($task -or $run){Report 'USER_AUTOSTART_REMOVED=PASS'}
94
+ else{Report 'USER_AUTOSTART_NOT_INSTALLED=PASS'}
95
+ $phase='PACKAGE'
96
+ if(Test-Path $install){
97
+ # Delete only a receipt-verified private Agent installation; CLI is not
98
+ # trusted as sole cleanup path because uninstall must work with no runtime.
99
+ Remove-Item -LiteralPath $install -Recurse -Force -ErrorAction Stop
100
+ }
101
+ Report 'AGENT_PACKAGE_REMOVED=PASS'
102
+ $phase='CREDENTIALS'
103
+ if(Test-Path $credentials){Remove-Item -LiteralPath $credentials -Recurse -Force -ErrorAction Stop}
104
+ Report 'LOCAL_DEVICE_CREDENTIALS_REMOVED=PASS'
105
+ $phase='STAGE'
106
+ if(Test-Path $stage){Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction Stop}
107
+ Report 'PRIVATE_STAGE_REMOVED=PASS'
108
+ $phase='LAUNCHER'
109
+ if(Test-Path -LiteralPath $launcher){Remove-Item -LiteralPath $launcher -Force -ErrorAction Stop}
110
+ $phase='RUNTIME'
111
+ if(Test-Path $privateRuntime){Remove-Item -LiteralPath $privateRuntime -Recurse -Force -ErrorAction Stop}
112
+ Report 'PRIVATE_RUNTIME_REMOVED=PASS'
113
+ $phase='VERIFY'
114
+ Demand (-not(Test-Path $install) -and -not(Test-Path $credentials) -and -not(Test-Path $stage) -and -not(Test-Path $privateRuntime)) 'RESIDUAL_FILES_FOUND'
115
+ $remaining=@(Get-CimInstance Win32_Process -Filter "Name='node.exe'"|Where-Object {($_.CommandLine -like ('*'+$install+'*') -or $_.CommandLine -like ('*'+$stageCli+'*'))})
116
+ Demand ($remaining.Count -eq 0) 'RESIDUAL_WORKER_FOUND'
117
+ Report 'RESULT=LOCAL_UNINSTALL_PASS; SERVER_DEVICE_REGISTRATION_NOT_CHANGED'
118
+ Write-Host 'Server device registration may remain offline. Remove it separately under RemoteShell > My Devices if desired.'
119
+ }catch {
120
+ $message='RESULT=FAIL; PHASE='+$phase+'; ERROR='+$_.Exception.Message
121
+ Write-Host $message
122
+ if(Test-Path -LiteralPath $reportDir){Add-Content -LiteralPath $report -Value $message -Encoding UTF8}
123
+ exit 1
124
+ }
@@ -0,0 +1,106 @@
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
+ const DENY=()=>{throw Error('DEVICE_WINDOWS_ACL_DENIED');};
9
+ const SID=/^S-1-\d+(?:-\d+){1,15}$/;
10
+ const SYSTEM='S-1-5-18';
11
+ const ADMINISTRATORS='S-1-5-32-544';
12
+ // PowerShell Get-Acl must run under the actual Windows user profile. A
13
+ // SystemRoot-only environment makes initialization intermittently time out
14
+ // on Windows Task Scheduler. Pass only OS/user environment essentials, not
15
+ // PATH, PSModulePath, executable names or arbitrary parent environment.
16
+ function aclChildEnv(systemRoot,target,directory){
17
+ const e={SystemRoot:systemRoot,WINDIR:systemRoot,
18
+ RS310_ACL_TARGET:target,RS310_ACL_DIR:directory?'1':'0'};
19
+ for(const key of ['USERPROFILE','APPDATA','LOCALAPPDATA','TEMP','TMP','HOMEDRIVE','HOMEPATH','ProgramData']){
20
+ const v=process.env[key];
21
+ if(typeof v==='string'&&v.length>0&&v.length<4096)e[key]=v;
22
+ }
23
+ return e;
24
+ }
25
+ const SCRIPT=[
26
+ '$ErrorActionPreference = "Stop"',
27
+ '$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()',
28
+ 'function Read-PrivateAcl([string]$target) {',
29
+ ' $acl = Get-Acl -LiteralPath $target',
30
+ ' $owner = $acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value',
31
+ ' $rules = @($acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier]) | ForEach-Object {',
32
+ ' @{ sid = $_.IdentityReference.Value; inherited = $_.IsInherited; access = $_.AccessControlType.ToString(); rights = [int64]$_.FileSystemRights }',
33
+ ' })',
34
+ ' return @{ user = $identity.User.Value; owner = $owner; protected = $acl.AreAccessRulesProtected; rules = $rules }',
35
+ '}',
36
+ '$file = $env:RS310_ACL_TARGET',
37
+ '$parent = if ($env:RS310_ACL_DIR -eq "1") { $file } else { Split-Path -Parent $file }',
38
+ '@{ file = (Read-PrivateAcl $file); parent = (Read-PrivateAcl $parent) } | ConvertTo-Json -Compress -Depth 6'
39
+ ].join('; ');
40
+ export function validateWindowsAclSnapshot(snapshot){
41
+ const {user,owner,protected:aclProtected,rules}=snapshot||{};
42
+ if(!SID.test(user||'')||owner!==user||aclProtected!==true||!Array.isArray(rules)||rules.length<1)DENY();
43
+ let ownerAllowed=false;
44
+ for(const rule of rules){
45
+ if(!SID.test(rule?.sid||'')||rule.inherited!==false||rule.access!=='Allow'||
46
+ !Number.isSafeInteger(rule.rights)||rule.rights<0)DENY();
47
+ if(![user,SYSTEM,ADMINISTRATORS].includes(rule.sid))DENY();
48
+ if(rule.sid===user)ownerAllowed=true;
49
+ }
50
+ if(!ownerAllowed)DENY();
51
+ return Object.freeze({ownerVerified:true,restrictedAcl:true,credentialReadiness:'acl-only'});
52
+ }
53
+ export function inspectWindowsCredentialAcl({
54
+ file,home,os=process.platform,lstat=lstatSync,realpath=realpathSync,
55
+ run=spawnSync
56
+ }={}){
57
+ if(os!=='win32')DENY();
58
+ try{
59
+ canonicalWindowsLocalFile(home);
60
+ isWindowsChildPath(file,home);
61
+ const parent=win32.dirname(file);
62
+ canonicalWindowsLocalFile(parent);
63
+ const root=lstat(home),dir=lstat(parent),stat=lstat(file);
64
+ if(!root.isDirectory()||root.isSymbolicLink()||
65
+ !dir.isDirectory()||dir.isSymbolicLink()||
66
+ !stat.isFile()||stat.isSymbolicLink()||
67
+ stat.nlink!==1||stat.size<1||stat.size>8192)DENY();
68
+ if(win32.normalize(realpath(file)).toLowerCase()!==file.toLowerCase()||
69
+ win32.normalize(realpath(parent)).toLowerCase()!==parent.toLowerCase())DENY();
70
+ const systemRoot=process.env.SystemRoot||'C:\\Windows';
71
+ canonicalWindowsLocalFile(systemRoot+'\\System32');
72
+ const powerShell=win32.join(systemRoot,'System32','WindowsPowerShell','v1.0','powershell.exe');
73
+ const child=run(powerShell,['-NoProfile','-NonInteractive','-EncodedCommand',
74
+ Buffer.from(SCRIPT,'utf16le').toString('base64')],{
75
+ shell:false,windowsHide:true,encoding:'utf8',timeout:20000,maxBuffer:16384,
76
+ env:aclChildEnv(systemRoot,file,false),
77
+ stdio:'pipe'
78
+ });
79
+ if(child.error||child.signal||child.status!==0||typeof child.stdout!=='string'||child.stdout.length>8192)DENY();
80
+ const snapshot=JSON.parse(child.stdout);
81
+ validateWindowsAclSnapshot(snapshot?.parent);
82
+ return validateWindowsAclSnapshot(snapshot?.file);
83
+ }catch{DENY();}
84
+ }
85
+
86
+ // Verify one directory's own protected ACL without creating any files.
87
+ export function inspectWindowsPrivateDirectoryAcl({directory,home,os=process.platform,
88
+ lstat=lstatSync,realpath=realpathSync,run=spawnSync}={}){
89
+ if(os!=='win32')DENY();
90
+ try{
91
+ canonicalWindowsLocalFile(home);
92
+ isWindowsChildPath(directory,home);
93
+ const st=lstat(directory);
94
+ if(!st.isDirectory()||st.isSymbolicLink()||
95
+ win32.normalize(realpath(directory)).toLowerCase()!==directory.toLowerCase())DENY();
96
+ const systemRoot=process.env.SystemRoot||'C:\\Windows';
97
+ const ps=win32.join(systemRoot,'System32','WindowsPowerShell','v1.0','powershell.exe');
98
+ const child=run(ps,['-NoProfile','-NonInteractive','-EncodedCommand',
99
+ Buffer.from(SCRIPT,'utf16le').toString('base64')],{
100
+ shell:false,windowsHide:true,encoding:'utf8',timeout:20000,maxBuffer:16384,
101
+ env:aclChildEnv(systemRoot,directory,true),stdio:'pipe'
102
+ });
103
+ if(child.error||child.signal||child.status!==0||typeof child.stdout!=='string'||child.stdout.length>8192)DENY();
104
+ return validateWindowsAclSnapshot(JSON.parse(child.stdout)?.file);
105
+ }catch{DENY();}
106
+ }
@@ -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
+ }