@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,292 @@
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 $script:agentVersion -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
+ # Backward-compatible with older DEV-only Windows bundles; each new bundle pins its public beta explicitly.
95
+ $script:agentVersion=if($manifest.agentVersion){[string]$manifest.agentVersion}else{'0.1.0'}
96
+ Demand ($script:agentVersion -match '^0\.1\.0(-beta\.[1-9][0-9]*)?$') 'AGENT_VERSION_DENIED'
97
+ $paths=@{
98
+ node=(Join-Path $source 'runtime\node.exe');
99
+ npm=(Join-Path $source 'runtime\node_modules\npm\bin\npm-cli.js');
100
+ archive=(Join-Path $source 'agent.tgz')
101
+ }
102
+ foreach($key in @('node','npm','archive')){
103
+ Demand (Test-Path -LiteralPath $paths[$key] -PathType Leaf) ('MISSING_'+$key)
104
+ Demand ((Digest $paths[$key]) -eq $manifest.sha256.$key) ('HASH_MISMATCH_'+$key)
105
+ }
106
+ $who=[Security.Principal.WindowsIdentity]::GetCurrent().Name
107
+ $principal=New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
108
+ Demand (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) 'DO_NOT_RUN_AS_ADMIN'
109
+ Demand ([Environment]::Is64BitOperatingSystem) 'WINDOWS_X64_REQUIRED'
110
+ $homePath=[Environment]::GetFolderPath('UserProfile')
111
+ $localPath=[Environment]::GetFolderPath('LocalApplicationData')
112
+ Demand ($homePath -and $localPath -and (Test-Path -LiteralPath $localPath)) 'WINDOWS_PROFILE_MISSING'
113
+ Demand ($localPath -ieq (Join-Path $homePath 'AppData\Local')) 'FOREIGN_PROFILE_DENIED'
114
+ $agentInstall=Join-Path $localPath 'RemoteShell\DeviceAgent\install'
115
+ $oldCredentials=Join-Path $localPath 'RemoteShell\DeviceAgent\dev-credentials'
116
+ $resume=(Test-Path -LiteralPath $agentInstall -PathType Container)
117
+ if($resume){
118
+ Demand (-not $SkipPair) 'EXISTING_AGENT_PRESERVED'
119
+ # A failed/expired pairing is not a reason to reinstall or overwrite keys.
120
+ # Resume only a fully staged, currently unregistered installation.
121
+ $privateRuntime=Join-Path $localPath 'RemoteShell\EasyInstall\runtime-v22'
122
+ $node=Join-Path $privateRuntime 'node.exe'
123
+ $cli=Join-Path $agentInstall 'node_modules\@remoteshell\device\bin\device.mjs'
124
+ Demand (StageComplete $agentInstall) 'EXISTING_AGENT_INCOMPLETE_REVIEW_REQUIRED'
125
+ Demand (Test-Path -LiteralPath $node -PathType Leaf) 'EXISTING_PRIVATE_RUNTIME_MISSING'
126
+ Demand ((Digest $node) -eq $manifest.sha256.node) 'EXISTING_PRIVATE_RUNTIME_HASH_DENIED'
127
+ Demand (-not (IsRegistered $node $cli)) 'EXISTING_AGENT_ALREADY_REGISTERED'
128
+ $live=@(Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object {
129
+ $_.ExecutablePath -ieq $node -and $_.CommandLine -like ('*'+$cli+'*')
130
+ })
131
+ Demand ($live.Count -eq 0) 'EXISTING_AGENT_PROCESS_REVIEW_REQUIRED'
132
+ }else{
133
+ # A new install must not consume leftovers from a prior registration.
134
+ Demand (-not (Test-Path -LiteralPath $oldCredentials)) 'PREVIOUS_DEVICE_REGISTRATION_MUST_BE_REMOVED'
135
+ }
136
+ $version=& $paths.node '--version'
137
+ Demand ($LASTEXITCODE -eq 0 -and $version -match '^v22\.') 'BUNDLED_NODE_VERSION_DENIED'
138
+ if($CheckOnly){
139
+ Write-Host ('EASY_INSTALL_CHECK_PASS '+$version+' '+$who)
140
+ exit 0
141
+ }
142
+ $reportDir=Join-Path $localPath 'RemoteShell\EasyInstall\logs'
143
+ if(-not(Test-Path -LiteralPath $reportDir)){New-Item -ItemType Directory -Path $reportDir -Force|Out-Null}
144
+ $log=Join-Path $reportDir 'result.txt'
145
+ # Preserve prior status/error codes only; pair.out can carry private enrollment
146
+ # material and must never be backed up into a new distributable or shared path.
147
+ $priorLog=Join-Path $reportDir 'result.txt'
148
+ if(Test-Path -LiteralPath $priorLog -PathType Leaf){
149
+ $history=Join-Path $reportDir 'history'
150
+ if(-not(Test-Path -LiteralPath $history)){New-Item -ItemType Directory -Path $history -Force|Out-Null}
151
+ $stamp=Get-Date -Format 'yyyyMMdd-HHmmss-fff'
152
+ Copy-Item -LiteralPath $priorLog -Destination (Join-Path $history ('result-'+$stamp+'.txt')) -ErrorAction Stop
153
+ $priorError=Join-Path $reportDir 'pair.err'
154
+ if(Test-Path -LiteralPath $priorError -PathType Leaf){
155
+ # Raw stderr may be untrusted; preserve only known uppercase error codes.
156
+ Get-Content -LiteralPath $priorError | Where-Object {$_ -match '^DEVICE_[A-Z0-9_]+$'} |
157
+ Set-Content -LiteralPath (Join-Path $history ('pair-error-'+$stamp+'.txt')) -Encoding UTF8
158
+ }
159
+ }
160
+ Set-Content -LiteralPath $log -Value ('RemoteShell EasyInstall DEV '+(Get-Date -Format o)+' user='+$who) -Encoding UTF8
161
+ if($resume){
162
+ $phase='RESUME_PAIR'
163
+ Add-Content -LiteralPath $log -Value 'INSTALL_RESUME=PAIR_ONLY; PACKAGE_PRESERVED=true' -Encoding UTF8
164
+ Write-Host '[PASS] previously installed Agent verified; resuming Google approval only'
165
+ }else{
166
+ $phase='COPY_RUNTIME'
167
+ $privateRuntime=Join-Path $localPath 'RemoteShell\EasyInstall\runtime-v22'
168
+ if(-not(Test-Path -LiteralPath $privateRuntime)){
169
+ New-Item -ItemType Directory -Path $privateRuntime -Force|Out-Null
170
+ Copy-Item -LiteralPath (Join-Path $source 'runtime\node.exe') -Destination (Join-Path $privateRuntime 'node.exe')
171
+ New-Item -ItemType Directory -Path (Join-Path $privateRuntime 'node_modules') -Force|Out-Null
172
+ Copy-Item -LiteralPath (Join-Path $source 'runtime\node_modules\npm') -Destination (Join-Path $privateRuntime 'node_modules\npm') -Recurse
173
+ }
174
+ $node=Join-Path $privateRuntime 'node.exe'
175
+ $npm=Join-Path $privateRuntime 'node_modules\npm\bin\npm-cli.js'
176
+ Demand ((Digest $node) -eq $manifest.sha256.node -and (Digest $npm) -eq $manifest.sha256.npm) 'PRIVATE_RUNTIME_HASH_DENIED'
177
+ $env:PATH=$privateRuntime+';'+$env:PATH
178
+ $phase='STAGE'
179
+ $stage=Join-Path $localPath 'RemoteShell\EasyInstall\stage'
180
+ if(Test-Path -LiteralPath $stage){
181
+ Demand (StageComplete $stage) 'PREVIOUS_STAGE_INCOMPLETE_REVIEW_FIRST'
182
+ Write-Host '[PASS] stage-agent (verified existing dependencies)'
183
+ }else{
184
+ New-Item -ItemType Directory -Path $stage -Force|Out-Null
185
+ 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')
186
+ Demand (StageComplete $stage) 'DEVICE_DEPENDENCY_VALIDATION_FAILED'
187
+ }
188
+ $cli=Join-Path $stage 'node_modules\@remoteshell\device\bin\device.mjs'
189
+ Demand (Test-Path -LiteralPath $cli -PathType Leaf) 'DEVICE_CLI_MISSING'
190
+ $phase='PREFLIGHT'
191
+ Step 'preflight' $node @($cli,'install-preflight') 20
192
+ $phase='INSTALL'
193
+ Step 'install' $node @($cli,'install') 240
194
+ Step 'status' $node @($cli,'status') 20
195
+ Add-Content -LiteralPath $log -Value 'AGENT_INSTALLED=true; REGISTERED=false; CONNECTED=false' -Encoding UTF8
196
+ Write-Host 'RemoteShell Agent package installed; Google owner approval is separate.'
197
+ Demand (-not (IsRegistered $node $cli)) 'UNEXPECTED_OLD_DEVICE_REGISTRATION_DENIED'
198
+ if($SkipPair){
199
+ Add-Content -LiteralPath $log -Value 'PAIR=SKIPPED_UNREGISTERED; USER_WORKER=NOT_STARTED' -Encoding UTF8
200
+ exit 0
201
+ }
202
+ }
203
+ $phase='PAIR'
204
+ $url='https://ailab-remoteshell.duckdns.org/dev/'
205
+ $out=Join-Path $reportDir 'pair.out';$err=Join-Path $reportDir 'pair.err'
206
+ $pair=Start-Process -FilePath $node -ArgumentList ('"'+$cli+'" windows-pair '+$url) -PassThru -RedirectStandardOutput $out -RedirectStandardError $err
207
+ $opened=$false;$approved=$false;$pairId='none';$pairStart=Get-Date;$pairDeadline=$pairStart.AddMinutes(5)
208
+ Add-Content -LiteralPath $log -Value ('PAIR_REQUEST_STARTED='+$pairStart.ToString('o')+'; PHASE=WAIT_OWNER_BROWSER') -Encoding UTF8
209
+ try{
210
+ $deadline=(Get-Date).AddMinutes(6)
211
+ while((Get-Date) -lt $deadline){
212
+ if(Test-Path -LiteralPath $out){
213
+ foreach($line in @(Get-Content -LiteralPath $out -ErrorAction SilentlyContinue)){
214
+ try{$obj=$line | ConvertFrom-Json}catch{continue}
215
+ if(-not $opened -and $obj.next -eq 'approve-device-in-browser' -and $obj.ownerApprovalRequired -and $obj.approval_url){
216
+ $link=[uri]$obj.approval_url
217
+ Demand ($link.Scheme -eq 'https' -and $link.Host -eq 'ailab-remoteshell.duckdns.org' -and $link.AbsolutePath.StartsWith('/dev/')) 'PAIR_APPROVAL_URL_DENIED'
218
+ $pairId=($link.AbsolutePath -split '/')[-1]
219
+ Demand ($pairId -match '^[0-9a-fA-F-]{36}$') 'PAIR_REQUEST_ID_INVALID'
220
+ Add-Content -LiteralPath $log -Value ('PAIR_BROWSER_URL_CREATED='+$pairStart.ToString('o')+'; PAIR_ID='+$pairId+'; APPROVAL_DEADLINE='+$pairDeadline.ToString('o')) -Encoding UTF8
221
+ Write-Host 'Google approval: check account and approve the device in the browser.'
222
+ Start-Process $link.AbsoluteUri
223
+ Add-Content -LiteralPath $log -Value ('PAIR_BROWSER_OPEN_ATTEMPT='+((Get-Date).ToString('o'))+'; PAIR_ID='+$pairId) -Encoding UTF8
224
+ $opened=$true
225
+ }
226
+ if($obj.registered -eq $true -and $obj.connected -eq $true){
227
+ $approved=$true
228
+ Add-Content -LiteralPath $log -Value ('PAIR_AGENT_CONNECTED='+((Get-Date).ToString('o'))+'; PAIR_ID='+$pairId) -Encoding UTF8
229
+ }
230
+ }
231
+ }
232
+ $pair.Refresh()
233
+ if($pair.HasExited){break}
234
+ Start-Sleep -Milliseconds 700
235
+ }
236
+ $pair.Refresh()
237
+ if(-not $approved){
238
+ $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'}
239
+ $exitStatus=if($pair.HasExited){[string]$pair.ExitCode}else{'RUNNING'}
240
+ Add-Content -LiteralPath $log -Value ('PAIR_DIAGNOSTIC='+$reason+'; PAIR_ID='+$pairId+'; PROCESS_EXIT='+$exitStatus+'; AT='+((Get-Date).ToString('o'))) -Encoding UTF8
241
+ throw $reason
242
+ }
243
+ Demand ($pair.HasExited -and ($null -eq $pair.ExitCode -or $pair.ExitCode -eq 0)) 'PAIR_PROCESS_EXIT_NONZERO'
244
+ Add-Content -LiteralPath $log -Value 'PAIR=PASS; GOOGLE_OWNER_APPROVAL=true' -Encoding UTF8
245
+ Write-Host '[PASS] Google owner approval and first heartbeat'
246
+ }finally{if(-not $pair.HasExited){try{$pair.Kill()}catch{}}}
247
+ $phase='START_AGENT'
248
+ Demand (IsRegistered $node $cli) 'OWNER_PAIRING_REGISTRATION_NOT_PERSISTED'
249
+ if($Background){
250
+ # Opt-in only: current user HKCU Run/VBS, no admin/system service.
251
+ StartRegisteredUserAgent $node $cli $log
252
+ Add-Content -LiteralPath $log -Value 'RUN_MODE=BACKGROUND; USER_AUTOSTART=ENABLED' -Encoding UTF8
253
+ }else{
254
+ # Default foreground: no autostart entry, no hidden launcher.
255
+ $runKey='HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'
256
+ Demand (-not (Get-ItemProperty -LiteralPath $runKey -Name 'RemoteShell-DEV-User-Agent' -ErrorAction SilentlyContinue)) 'EXISTING_USER_AUTOSTART_REVIEW_REQUIRED'
257
+ Demand (-not (Test-Path -LiteralPath (Join-Path $localPath 'RemoteShell\EasyInstall\agent-autostart.vbs'))) 'EXISTING_LAUNCHER_REVIEW_REQUIRED'
258
+ Add-Content -LiteralPath $log -Value 'RUN_MODE=FOREGROUND; USER_AUTOSTART=DISABLED' -Encoding UTF8
259
+ }
260
+ $phase='COMPLETE'
261
+ # Device enrollment is NOT AI connection authorization. An authenticated owner
262
+ # must create and approve a connection covering this exact new device before
263
+ # ChatGPT can obtain the live DC catalog. No automatic connection grant.
264
+ $connectionsUrl='https://ailab-remoteshell.duckdns.org/dev/connections'
265
+ Write-Host ('NEXT: Sign in with the same Google RS identity at '+$connectionsUrl)
266
+ Write-Host 'NEXT: Select this newly registered device, create and approve an AI connection; then refresh ChatGPT tools.'
267
+ Add-Content -LiteralPath $log -Value ('NEXT=VERIFY_OWNER_AI_CONNECTION; URL='+$connectionsUrl) -Encoding UTF8
268
+ Add-Content -LiteralPath $log -Value 'RESULT=INSTALL_AND_PAIR_PASS; AI_CONNECTION_AND_DC_READ_AND_USAGE_NOT_TESTED' -Encoding UTF8
269
+ if(-not $Background){
270
+ $phase='FOREGROUND'
271
+ Write-Host 'Foreground Agent started. Keep this window open; Ctrl+C stops the session.'
272
+ & $node $cli dev-heartbeat
273
+ Demand ($LASTEXITCODE -eq 0) 'FOREGROUND_AGENT_EXIT_NONZERO'
274
+ }
275
+ }catch{
276
+ Write-Host ('[STOP] '+$phase+': '+$_.Exception.Message)
277
+ if($reportDir -and (Test-Path -LiteralPath $reportDir)){
278
+ Add-Content -LiteralPath (Join-Path $reportDir 'result.txt') -Value ('RESULT=FAIL; PHASE='+$phase+'; ERROR='+$_.Exception.Message+'; AT='+((Get-Date).ToString('o'))) -Encoding UTF8
279
+ if($phase -eq 'PAIR'){
280
+ $stderrFile=Join-Path $reportDir 'pair.err'
281
+ if(Test-Path -LiteralPath $stderrFile){
282
+ $known=@(Get-Content -LiteralPath $stderrFile | Where-Object {$_ -match '^DEVICE_[A-Z0-9_]+$'} | Select-Object -First 3)
283
+ foreach($errorCode in $known){Add-Content -LiteralPath (Join-Path $reportDir 'result.txt') -Value ('PAIR_AGENT_ERROR_CODE='+$errorCode) -Encoding UTF8}
284
+ }
285
+ }
286
+ }
287
+ exit 1
288
+ }finally{
289
+ if(-not $CheckOnly -and $reportDir -and (Test-Path -LiteralPath $reportDir -PathType Container)){
290
+ Write-Host ('Result: '+(Join-Path $reportDir 'result.txt'))
291
+ }
292
+ }
@@ -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,128 @@
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 -match '^0\.1\.0(-beta\.[1-9][0-9]*)?$') 'FOREIGN_INSTALL_DENIED'
68
+ $pkg=Join-Path $install 'node_modules\@remoteshell\device\package.json'
69
+ Demand (Test-Path -LiteralPath $pkg -PathType Leaf) 'FOREIGN_INSTALL_DENIED'
70
+ $metadata=Get-Content -LiteralPath $pkg -Raw | ConvertFrom-Json
71
+ Demand ($metadata.name -eq '@remoteshell/device' -and $metadata.version -eq $r.version) 'FOREIGN_INSTALL_DENIED'
72
+ }
73
+ if(Test-Path $credentials){
74
+ $files=@(Get-ChildItem -LiteralPath $credentials -Force)
75
+ foreach($f in $files){
76
+ Demand (-not $f.PSIsContainer -and -not ($f.Attributes -band [IO.FileAttributes]::ReparsePoint)) 'FOREIGN_CREDENTIAL_ENTRY'
77
+ 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'
78
+ }
79
+ }
80
+ if($CheckOnly){
81
+ Write-Host ('EASY_UNINSTALL_CHECK_PASS user='+$identity.Name+
82
+ ' workers='+$workers.Count+' installed='+(Test-Path $install)+
83
+ ' credentials='+(Test-Path $credentials))
84
+ exit 0
85
+ }
86
+ if(-not (Test-Path -LiteralPath $reportDir)){New-Item -Path $reportDir -ItemType Directory -Force|Out-Null}
87
+ Set-Content -LiteralPath $report -Value ('RemoteShell easy uninstall '+(Get-Date -Format o)+' user='+$identity.Name) -Encoding UTF8
88
+ $phase='STOP'
89
+ $order=@($workers|Sort-Object @{Expression={if($_.CommandLine -like '*desktop-commander*'){0}elseif($_.CommandLine -like '*main.mjs*'){1}else{2}}})
90
+ foreach($w in $order){Stop-Process -Id $w.ProcessId -Force -ErrorAction Stop}
91
+ Report ('AGENT_PROCESSES_STOPPED='+$order.Count)
92
+ $phase='AUTOSTART'
93
+ if($task){Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction Stop}
94
+ if($run){Remove-ItemProperty -LiteralPath $runKey -Name $runName -ErrorAction Stop}
95
+ # Foreground-only installation intentionally has no autostart registration.
96
+ # Treat absence as a valid clean uninstall, not a failed removal.
97
+ if($task -or $run){Report 'USER_AUTOSTART_REMOVED=PASS'}
98
+ else{Report 'USER_AUTOSTART_NOT_INSTALLED=PASS'}
99
+ $phase='PACKAGE'
100
+ if(Test-Path $install){
101
+ # Delete only a receipt-verified private Agent installation; CLI is not
102
+ # trusted as sole cleanup path because uninstall must work with no runtime.
103
+ Remove-Item -LiteralPath $install -Recurse -Force -ErrorAction Stop
104
+ }
105
+ Report 'AGENT_PACKAGE_REMOVED=PASS'
106
+ $phase='CREDENTIALS'
107
+ if(Test-Path $credentials){Remove-Item -LiteralPath $credentials -Recurse -Force -ErrorAction Stop}
108
+ Report 'LOCAL_DEVICE_CREDENTIALS_REMOVED=PASS'
109
+ $phase='STAGE'
110
+ if(Test-Path $stage){Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction Stop}
111
+ Report 'PRIVATE_STAGE_REMOVED=PASS'
112
+ $phase='LAUNCHER'
113
+ if(Test-Path -LiteralPath $launcher){Remove-Item -LiteralPath $launcher -Force -ErrorAction Stop}
114
+ $phase='RUNTIME'
115
+ if(Test-Path $privateRuntime){Remove-Item -LiteralPath $privateRuntime -Recurse -Force -ErrorAction Stop}
116
+ Report 'PRIVATE_RUNTIME_REMOVED=PASS'
117
+ $phase='VERIFY'
118
+ Demand (-not(Test-Path $install) -and -not(Test-Path $credentials) -and -not(Test-Path $stage) -and -not(Test-Path $privateRuntime)) 'RESIDUAL_FILES_FOUND'
119
+ $remaining=@(Get-CimInstance Win32_Process -Filter "Name='node.exe'"|Where-Object {($_.CommandLine -like ('*'+$install+'*') -or $_.CommandLine -like ('*'+$stageCli+'*'))})
120
+ Demand ($remaining.Count -eq 0) 'RESIDUAL_WORKER_FOUND'
121
+ Report 'RESULT=LOCAL_UNINSTALL_PASS; SERVER_DEVICE_REGISTRATION_NOT_CHANGED'
122
+ Write-Host 'Server device registration may remain offline. Remove it separately under RemoteShell > My Devices if desired.'
123
+ }catch {
124
+ $message='RESULT=FAIL; PHASE='+$phase+'; ERROR='+$_.Exception.Message
125
+ Write-Host $message
126
+ if(Test-Path -LiteralPath $reportDir){Add-Content -LiteralPath $report -Value $message -Encoding UTF8}
127
+ exit 1
128
+ }
@@ -0,0 +1,50 @@
1
+ // #327 Windows owner/DACL query without starting nested PowerShell.
2
+ // Uses built-in cscript/WMI under the caller's OS token; read-only, fail closed.
3
+ import {spawnSync} from 'node:child_process';
4
+ import {win32} from 'node:path';
5
+ import {fileURLToPath} from 'node:url';
6
+ const DENY=()=>{throw Error('DEVICE_WINDOWS_ACL_DENIED');};
7
+ const SID=/^S-1-\d+(?:-\d+){1,15}$/;
8
+ export function parseWmiAclRows(output,user,{directory=false}={}){
9
+ if(typeof output!=='string'||output.length>8192||!SID.test(user||''))DENY();
10
+ const expected=directory?['file']:['parent','file'];
11
+ const lines=output.trim().split(/\r?\n/),result={};
12
+ let index=0;
13
+ for(const name of expected){
14
+ if(lines[index++]!==`begin=${name}`)DENY();
15
+ const ownerLine=lines[index++];
16
+ if(!ownerLine?.startsWith('owner='))DENY();
17
+ const owner=ownerLine.slice(6);
18
+ if(!SID.test(owner))DENY();
19
+ const protectedLine=lines[index++];
20
+ if(protectedLine!=='protected=true'&&protectedLine!=='protected=false')DENY();
21
+ const rules=[];
22
+ while(index<lines.length&&lines[index].startsWith('ace=')){
23
+ const match=/^ace=(S-1-\d+(?:-\d+){1,15}),(true|false),([01]),(\d{1,12})$/.exec(lines[index++]);
24
+ if(!match)DENY();
25
+ const rights=Number(match[4]);
26
+ if(!Number.isSafeInteger(rights))DENY();
27
+ rules.push({sid:match[1],inherited:match[2]==='true',
28
+ access:match[3]==='0'?'Allow':'Deny',rights});
29
+ if(rules.length>32)DENY();
30
+ }
31
+ if(lines[index++]!==`end=${name}`||rules.length===0)DENY();
32
+ result[name]={user,owner,protected:protectedLine==='protected=true',rules};
33
+ }
34
+ if(index!==lines.length)DENY();
35
+ return result;
36
+ }
37
+ export function inspectWmiAcl(target,{directory=false,run=spawnSync}={}){
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();
44
+ const user=String(who.stdout||'').match(/S-1-\d+(?:-\d+){1,15}/)?.[0];
45
+ if(!SID.test(user||''))DENY();
46
+ 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});
50
+ }
@@ -0,0 +1,43 @@
1
+ // Windows JScript Host WMI ACL snapshot. Read-only; no ACL repair.
2
+ // Executes under the current Windows user token via cscript.exe.
3
+ try {
4
+ var target = String(WScript.Arguments.Item(0));
5
+ var directory = String(WScript.Arguments.Item(1)) === '1';
6
+ if (target.length > 1024 || !/^[A-Za-z]:\\/.test(target) ||
7
+ /['"\r\n]/.test(target) || (WScript.Arguments.Length !== 2))
8
+ throw new Error('PATH_DENIED');
9
+ var svc = new ActiveXObject('WbemScripting.SWbemLocator').ConnectServer('.', 'root\\cimv2');
10
+ var fso = new ActiveXObject('Scripting.FileSystemObject');
11
+ function inspect(path, label) {
12
+ var q = "SELECT * FROM Win32_LogicalFileSecuritySetting WHERE Path='" +
13
+ path.replace(/\\/g, '\\\\') + "'";
14
+ var found = new Enumerator(svc.ExecQuery(q)), count = 0, record = null;
15
+ for (; !found.atEnd(); found.moveNext()) { record = found.item(); count++; }
16
+ if (count !== 1) throw new Error('MATCH_DENIED');
17
+ var result = record.ExecMethod_('GetSecurityDescriptor');
18
+ if (result.Properties_.Item('ReturnValue').Value !== 0)
19
+ throw new Error('ACCESS_DENIED');
20
+ var descriptor = result.Properties_.Item('Descriptor').Value;
21
+ var owner = descriptor.Properties_.Item('Owner').Value.Properties_.Item('SIDString').Value;
22
+ var flags = descriptor.Properties_.Item('ControlFlags').Value;
23
+ var list = descriptor.Properties_.Item('DACL').Value.toArray();
24
+ if (list.length < 1 || list.length > 32) throw new Error('ACE_COUNT_DENIED');
25
+ WScript.Echo('begin=' + label);
26
+ WScript.Echo('owner=' + owner);
27
+ WScript.Echo('protected=' + ((flags & 4096) !== 0));
28
+ for (var i = 0; i < list.length; i++) {
29
+ var ace = list[i];
30
+ var sid = ace.Properties_.Item('Trustee').Value.Properties_.Item('SIDString').Value;
31
+ WScript.Echo('ace=' + sid + ',' +
32
+ ((ace.Properties_.Item('AceFlags').Value & 16) !== 0) + ',' +
33
+ ace.Properties_.Item('AceType').Value + ',' +
34
+ ace.Properties_.Item('AccessMask').Value);
35
+ }
36
+ WScript.Echo('end=' + label);
37
+ }
38
+ if (!directory) inspect(fso.GetParentFolderName(target), 'parent');
39
+ inspect(target, 'file');
40
+ } catch (error) {
41
+ WScript.Echo('DEVICE_WINDOWS_ACL_DENIED');
42
+ WScript.Quit(1);
43
+ }