@xkwdstore/agent 2.1.5 → 2.1.6

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.
@@ -1,385 +1,385 @@
1
- # XKWDStore Agent - Machine-Wide Silent Startup (version from -AgentVersion)
2
- #
3
- # Installs / removes the machine-wide BROKER + per-session interactive WORKER
4
- # startup. This script MUST run elevated (it creates a Windows service and writes
5
- # %ProgramData%). It is idempotent and preserves device identity + profiles.
6
- #
7
- # DESIGN
8
- # Broker : a Windows Service (elevated, silent, no console, no taskbar window)
9
- # running as a dedicated service identity (default: LocalSystem, or a
10
- # configured virtual service account). It owns machine identity, the
11
- # server WebSocket, leases, and the machine-state ACLs.
12
- # Worker : spawned PER INTERACTIVE SESSION by the broker (CreateProcessAsUser
13
- # into the active session) OR, when per-session spawning is not
14
- # available, by a per-user logon Scheduled Task that ONLY launches the
15
- # worker with a broker-issued one-time channel token. The worker needs
16
- # no credential and cannot enroll.
17
- #
18
- # WHY A SERVICE (not just a task)
19
- # - starts at boot, independent of any Windows login
20
- # - silent (Session 0, no interactive desktop, no console window)
21
- # - restart-on-crash handled by the SCM with backoff
22
- # - one machine broker, gated further by a Global\ named mutex
23
- #
24
- # LIMITATION (documented): a Session 0 service cannot itself show a browser. The
25
- # browser MUST run in an interactive session, so the broker hands the browser work
26
- # to a worker in the active session. This script installs both halves.
27
- #
28
- # Options:
29
- # -AgentVersion <ver> pinned agent version (default 2.1.5)
30
- # -Server <url> server origin (default https://x.kwdstore.com)
31
- # -ServiceAccount <s> service identity (default LocalSystem)
32
- # -Uninstall remove service + startup (keeps ProgramData unless -PurgeData)
33
- # -PurgeData with -Uninstall, also delete machine state (EXPLICIT)
34
- # -NoStart install but do not start
35
- # -NoLaunch (test) validate + write files, never start a process
36
-
37
- param(
38
- [string]$AgentVersion = '2.1.5',
39
- [string]$Server = 'https://x.kwdstore.com',
40
- [string]$ServiceAccount = 'LocalSystem',
41
- [string]$AgentRoot,
42
- [switch]$Uninstall,
43
- [switch]$PurgeData,
44
- [switch]$NoStart,
45
- [switch]$NoLaunch
46
- )
47
-
48
- $ErrorActionPreference = 'Stop'
49
- $ServiceName = 'XKWDStoreAgentBroker'
50
- $ServiceDisplay = 'XKWDStore Agent Broker (machine-wide)'
51
- $MachineRoot = if ($AgentRoot) { $AgentRoot } else { Join-Path $env:ProgramData 'XKWDStore\Agent' }
52
-
53
- function Write-Step([string]$msg) { Write-Host " $msg" -ForegroundColor Cyan }
54
- function Write-Ok([string]$msg) { Write-Host " OK $msg" -ForegroundColor Green }
55
- function Write-Warn2([string]$msg) { Write-Host " ! $msg" -ForegroundColor Yellow }
56
-
57
- function Assert-Elevated {
58
- $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
59
- $p = New-Object System.Security.Principal.WindowsPrincipal($id)
60
- if (-not $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) {
61
- Write-Host 'This script must run elevated (Administrator).' -ForegroundColor Red
62
- exit 5
63
- }
64
- }
65
-
66
- function Get-NodePath {
67
- $cmd = Get-Command node -ErrorAction SilentlyContinue
68
- if (-not $cmd) { throw 'Node.js 22+ is required on PATH.' }
69
- return $cmd.Source
70
- }
71
-
72
- # -- install -----------------------------------------------------------------
73
- if (-not $Uninstall) {
74
- Write-Host ''
75
- Write-Host " XKWDStore Agent $AgentVersion - machine-wide silent startup" -ForegroundColor Cyan
76
- Write-Host ' ==================================================' -ForegroundColor Cyan
77
- Assert-Elevated
78
- $node = Get-NodePath
79
- Write-Step "node: $node"
80
-
81
- # 1. layout + restrictive ACLs (owner + Administrators + SYSTEM only)
82
- foreach ($sub in @('', 'config', 'identity', 'credentials', 'logs', 'runtime', 'state', 'launcher', 'state\profiles', 'state\servers')) {
83
- $d = if ($sub) { Join-Path $MachineRoot $sub } else { $MachineRoot }
84
- if (-not (Test-Path -LiteralPath $d)) { New-Item -ItemType Directory -Force -Path $d | Out-Null }
85
- }
86
- Write-Ok "machine root: $MachineRoot"
87
-
88
- # 1a. install the agent program files (so the service does not depend on the repo)
89
- $AgentInstallDir = if ($AgentRoot) { Join-Path $AgentRoot 'program' } else { Join-Path ${env:ProgramFiles} 'XKWDStore\Agent' }
90
- $srcDir = Join-Path (Split-Path $PSScriptRoot -Parent) 'src'
91
- if (Test-Path -LiteralPath $srcDir) {
92
- if (-not (Test-Path -LiteralPath $AgentInstallDir)) { New-Item -ItemType Directory -Force -Path $AgentInstallDir | Out-Null }
93
- Copy-Item -Path (Join-Path $srcDir '*') -Destination $AgentInstallDir -Recurse -Force
94
- foreach ($f in @('package.json', 'package-lock.json', 'node_modules')) {
95
- $sf = Join-Path (Split-Path $PSScriptRoot -Parent) $f
96
- if (Test-Path -LiteralPath $sf) {
97
- if ((Get-Item $sf).PSIsContainer) {
98
- Copy-Item -Path $sf -Destination (Join-Path $AgentInstallDir $f) -Recurse -Force -ErrorAction SilentlyContinue
99
- } else {
100
- Copy-Item -Path $sf -Destination (Join-Path $AgentInstallDir $f) -Force -ErrorAction SilentlyContinue
101
- }
102
- }
103
- }
104
- Write-Ok "agent files installed: $AgentInstallDir"
105
- } else {
106
- Write-Warn2 "agent src not found next to the installer; using the repo path in the service wrapper"
107
- }
108
-
109
- # 1a-bis. Provision the RUNTIME DEPENDENCIES into the install dir.
110
- # The block above copies a `node_modules` only if one sits next to the
111
- # installer. A normal `npm install @xkwdstore/agent` hoists the agent's
112
- # dependencies to the CALLER's node_modules, so the package directory ships
113
- # none. Copying only what happens to be there therefore produced an install
114
- # with no dependencies at all, and the broker died on its first bare
115
- # `require('playwright-core')` - a MODULE_NOT_FOUND crash-loop masked by the
116
- # service restarting it. The installer must guarantee the dependency tree
117
- # exists, not hope it was shipped alongside.
118
- $agentPkgJson = Join-Path $AgentInstallDir 'package.json'
119
- if (Test-Path -LiteralPath $agentPkgJson) {
120
- $depProbe = Join-Path $AgentInstallDir 'node_modules\playwright-core'
121
- if (-not (Test-Path -LiteralPath $depProbe)) {
122
- $agentLockJson = Join-Path $AgentInstallDir 'package-lock.json'
123
- Write-Step 'provisioning agent runtime dependencies (npm)'
124
- Push-Location $AgentInstallDir
125
- try {
126
- if (Test-Path -LiteralPath $agentLockJson) {
127
- & npm ci --omit=dev --no-audit --no-fund *> $null
128
- } else {
129
- & npm install --omit=dev --no-audit --no-fund *> $null
130
- }
131
- } finally { Pop-Location }
132
- if (-not (Test-Path -LiteralPath $depProbe)) {
133
- Write-Host ' X agent runtime dependencies could not be provisioned.' -ForegroundColor Red
134
- Write-Host ' The agent needs npm + network access on this machine.' -ForegroundColor Red
135
- exit 1
136
- }
137
- Write-Ok 'agent runtime dependencies provisioned'
138
- } else {
139
- Write-Ok 'agent runtime dependencies already present'
140
- }
141
- }
142
-
143
- # 1b. place the worker-entry launcher where the logon task expects it AND the
144
- # installer-managed scripts next to the installed program files.
145
- $workerEntrySrc = Join-Path $PSScriptRoot 'worker-entry.js'
146
- $workerEntryDst = Join-Path $AgentInstallDir 'scripts\worker-entry.js'
147
- if (Test-Path -LiteralPath $workerEntrySrc) {
148
- New-Item -ItemType Directory -Force -Path (Split-Path $workerEntryDst -Parent) | Out-Null
149
- Copy-Item -Path $workerEntrySrc -Destination $workerEntryDst -Force
150
- }
151
-
152
- $aclApply = @"
153
- `$ErrorActionPreference='Stop'
154
- `$root = '$($MachineRoot.Replace("'","''"))'
155
- `$owner = ([System.Security.Principal.WindowsIdentity]::GetCurrent()).User.Value
156
- `$sids = @(`$owner, 'S-1-5-18','S-1-5-32-544')
157
- `$dirs = @(`$root, (Join-Path `$root 'config'), (Join-Path `$root 'identity'), (Join-Path `$root 'credentials'), (Join-Path `$root 'logs'), (Join-Path `$root 'runtime'), (Join-Path `$root 'state'), (Join-Path `$root 'launcher'), (Join-Path `$root 'state\profiles'), (Join-Path `$root 'state\servers'))
158
- foreach (`$dir in `$dirs) {
159
- if (-not (Test-Path -LiteralPath `$dir)) { continue }
160
- `$acl = New-Object System.Security.AccessControl.DirectorySecurity
161
- `$acl.SetAccessRuleProtection(`$true, `$false)
162
- foreach (`$sid in `$sids) {
163
- `$rule = New-Object System.Security.AccessControl.FileSystemAccessRule((New-Object System.Security.Principal.SecurityIdentifier(`$sid)), 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
164
- `$acl.AddAccessRule(`$rule)
165
- }
166
- (Get-Item -LiteralPath `$dir).SetAccessControl(`$acl)
167
- }
168
- "@
169
- $aclFile = Join-Path $env:TEMP ("xkwd-acl-" + [guid]::NewGuid().ToString('N') + '.ps1')
170
- Set-Content -Path $aclFile -Value $aclApply -Encoding UTF8
171
- & powershell -NoProfile -ExecutionPolicy Bypass -File $aclFile
172
- Remove-Item $aclFile -Force -ErrorAction SilentlyContinue
173
- Write-Ok 'ACLs applied (owner + Administrators + SYSTEM; no broad principals)'
174
-
175
- # 1c. Re-protect any adopted (v1/CurrentUser) machine credential under
176
- # LocalMachine scope so the SERVICE broker (LocalSystem) can decrypt it.
177
- # Preserves the SAME key material -> same deviceId + pairing. Run as the
178
- # elevated OWNER so the CurrentUser blob is decryptable here.
179
- $rescope = @"
180
- `$ErrorActionPreference='Continue'
181
- `$env:XKWDSTORE_MACHINE_ROOT = '$($MachineRoot.Replace("'","''"))'
182
- `$env:XKWDSTORE_DPAPI_SCOPE = 'LocalMachine'
183
- Push-Location '$((Join-Path $AgentInstallDir '').Replace("'","''"))'
184
- try {
185
- `$dk = node -e "const dk=require('./deviceKeyStore'); const r=dk.rescopeWindowsKey({serverOrigin:'$($Server)'}); console.log(JSON.stringify(r));"
186
- Write-Output ('RESCOPE ' + (`$dk -join ' '))
187
- } finally { Pop-Location }
188
- "@
189
- $rescopeFile = Join-Path $env:TEMP ("xkwd-rescope-" + [guid]::NewGuid().ToString('N') + '.ps1')
190
- Set-Content -Path $rescopeFile -Value $rescope -Encoding UTF8
191
- & powershell -NoProfile -ExecutionPolicy Bypass -File $rescopeFile
192
- Remove-Item $rescopeFile -Force -ErrorAction SilentlyContinue
193
- Write-Ok 'machine credential scope reconciled to LocalMachine (if it was CurrentUser)'
194
-
195
- # 1d. legacy per-user startup: DETECT + BACK UP (fail-safe step 1-2).
196
- # A 2.0.x install may have left a per-user `start-xkwdstore-agent.bat`
197
- # (auto-start) that must not run once the machine service is authoritative.
198
- # We only BACK UP here; the backup preserves exact bytes + hash so rollback
199
- # is always possible. Disable happens LATER, only after the broker is
200
- # verified Running (fail-safe step 3 -> 4).
201
- $legacyMod = Join-Path $AgentInstallDir 'legacyStartup.js'
202
- $legacyBackupDir = Join-Path $MachineRoot 'state\legacy-startup-backup'
203
- if (Test-Path -LiteralPath $legacyMod) {
204
- try {
205
- $lb = (& node $legacyMod backup --users-root "$env:SystemDrive\Users" --backup-dir $legacyBackupDir 2>&1 | Out-String)
206
- $lbObj = $lb | ConvertFrom-Json
207
- Write-Ok ("legacy per-user startup: backed up " + $lbObj.count + " launcher(s) (rollback preserved)")
208
- } catch { Write-Warn2 "legacy startup backup step failed (non-fatal): $($_.Exception.Message)" }
209
- }
210
-
211
- # 2. service host (REAL Windows service: reports SERVICE_RUNNING to the SCM).
212
- # A running service LOCKS its own EXE, so stop it before recompiling.
213
- if (Get-Service -Name $ServiceName -ErrorAction SilentlyContinue) {
214
- Write-Step "stopping existing $ServiceName before host recompile"
215
- try { Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue } catch { }
216
- $dl = (Get-Date).AddSeconds(20)
217
- while ((Get-Service -Name $ServiceName -ErrorAction SilentlyContinue).Status -ne 'Stopped' -and (Get-Date) -lt $dl) { Start-Sleep -Milliseconds 500 }
218
- }
219
- # A compiled EXE is required: `powershell.exe -File` and `cmd /c` both fail
220
- # as SCM binaries (they exit before StartServiceCtrlDispatcher / 30s timeout).
221
- # The installer compiles broker-service-host.cs with the IN-BOX .NET
222
- # Framework compiler (no external dependency).
223
- $hostCs = Join-Path $PSScriptRoot 'broker-service-host.cs'
224
- $hostExe = Join-Path $MachineRoot 'launcher\XKWDStoreBrokerService.exe'
225
- if (-not (Test-Path -LiteralPath $hostCs)) {
226
- Write-Host " X broker-service-host.cs not found next to the installer: $hostCs" -ForegroundColor Red
227
- exit 1
228
- }
229
- $csc = Join-Path $env:SystemRoot 'Microsoft.NET\Framework64\v4.0.30319\csc.exe'
230
- if (-not (Test-Path -LiteralPath $csc)) { $csc = Join-Path $env:SystemRoot 'Microsoft.NET\Framework\v4.0.30319\csc.exe' }
231
- if (-not (Test-Path -LiteralPath $csc)) {
232
- Write-Host ' X in-box .NET Framework compiler (csc.exe) not found' -ForegroundColor Red
233
- exit 1
234
- }
235
- New-Item -ItemType Directory -Force -Path (Split-Path $hostExe -Parent) | Out-Null
236
- $cscArgs = @('/nologo', '/target:exe', "/out:$hostExe", '/reference:System.ServiceProcess.dll', $hostCs)
237
- $cscOut = (& $csc $cscArgs 2>&1)
238
- if (-not (Test-Path -LiteralPath $hostExe) -or ($cscOut -match 'error CS')) {
239
- Write-Host ' X service host compilation failed:' -ForegroundColor Red
240
- Write-Host (" " + ($cscOut -join "`n ")) -ForegroundColor Red
241
- exit 1
242
- }
243
- Write-Ok "service host compiled: $hostExe"
244
-
245
- # 2b. compile the interactive-session launcher so the Session-0 broker can
246
- # create the Browser Worker in the active interactive user session.
247
- $launcherCs = Join-Path $PSScriptRoot 'session-launcher.cs'
248
- $launcherExe = Join-Path $MachineRoot 'launcher\XKWDStoreSessionLauncher.exe'
249
- if (Test-Path -LiteralPath $launcherCs) {
250
- $lOut = (& $csc @('/nologo', '/target:exe', "/out:$launcherExe", $launcherCs) 2>&1)
251
- if (-not (Test-Path -LiteralPath $launcherExe) -or ($lOut -match 'error CS')) {
252
- Write-Host ' X session launcher compilation failed:' -ForegroundColor Red
253
- Write-Host (" " + ($lOut -join "`n ")) -ForegroundColor Red
254
- exit 1
255
- }
256
- Write-Ok "session launcher compiled: $launcherExe"
257
- } else {
258
- Write-Warn2 "session-launcher.cs not found next to the installer; interactive worker launch may fail"
259
- }
260
-
261
- $cliJs = Join-Path $AgentInstallDir 'cli.js'
262
- if (-not (Test-Path -LiteralPath $cliJs)) {
263
- $cliJs = Join-Path (Split-Path $PSScriptRoot -Parent) 'src\cli.js'
264
- Write-Warn2 "service host falling back to the repo CLI: $cliJs"
265
- }
266
- $agentNode = $node
267
- $svcBin = '"' + $hostExe + '" -Node "' + $agentNode + '" -Cli "' + $cliJs + '" -Root "' + $MachineRoot + '" -Server "' + $Server + '"'
268
-
269
- # 3. (re)create the service so no stale configuration survives. An in-place
270
- # `sc config` can leave remnants; delete + wait + create is deterministic.
271
- $svc = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
272
- if ($svc) {
273
- Write-Step "removing existing service $ServiceName (clean recreate)"
274
- try { Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue } catch { }
275
- (sc.exe delete $ServiceName) | Out-Null
276
- $deadline = (Get-Date).AddSeconds(20)
277
- while ((Get-Service -Name $ServiceName -ErrorAction SilentlyContinue) -and (Get-Date) -lt $deadline) { Start-Sleep -Milliseconds 500 }
278
- if (Get-Service -Name $ServiceName -ErrorAction SilentlyContinue) { Write-Warn2 'existing service did not disappear within 20s' }
279
- }
280
- Write-Step "creating service $ServiceName (account=$ServiceAccount)"
281
- if ($ServiceAccount -eq 'LocalSystem') {
282
- New-Service -Name $ServiceName -BinaryPathName $svcBin -DisplayName $ServiceDisplay -StartupType Automatic | Out-Null
283
- } else {
284
- New-Service -Name $ServiceName -BinaryPathName $svcBin -DisplayName $ServiceDisplay -StartupType Automatic -Credential $ServiceAccount | Out-Null
285
- }
286
- # restart-on-crash with backoff + no interactive desktop
287
- sc.exe failure $ServiceName reset= 86400 actions= restart/5000/restart/15000/restart/60000 | Out-Null
288
- sc.exe description $ServiceName "Machine-wide XKWDStore broker: identity, server connection, leases; spawns interactive browser workers." | Out-Null
289
- Write-Ok 'service configured (auto-start, restart-on-crash/backoff)'
290
-
291
- # 3a. verify the SCM binary path no longer references the old cmd wrapper.
292
- $finalPath = ((sc.exe qc $ServiceName 2>&1) | Where-Object { $_ -match 'BINARY_PATH_NAME' })
293
- if ($finalPath -match 'cmd\.exe /c') {
294
- Write-Host ' X service binary path still references the old cmd wrapper.' -ForegroundColor Red
295
- exit 1
296
- } else {
297
- Write-Ok "service binary path verified (no cmd wrapper): $($finalPath -replace '\s+',' ')"
298
- }
299
- # 3b. remove a stale diagnostic wrapper if it exists (never used by the SCM now).
300
- $staleCmd = Join-Path $MachineRoot 'launcher\broker-service.cmd'
301
- if (Test-Path -LiteralPath $staleCmd) { Remove-Item $staleCmd -Force -ErrorAction SilentlyContinue }
302
-
303
- # 4. per-session worker fallback (logon task) - only used if session spawning is unavailable
304
- $taskName = 'XKWDStoreAgentWorker'
305
- try {
306
- $action = New-ScheduledTaskAction -Execute $node -Argument "`"$workerEntryDst`""
307
- $trigger = New-ScheduledTaskTrigger -AtLogOn
308
- $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -MultipleInstances IgnoreNew
309
- Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Settings $settings -Description 'Per-interactive-session XKWDStore browser worker (broker-token gated).' -Force | Out-Null
310
- Write-Ok "worker logon task registered: $taskName"
311
- } catch {
312
- Write-Warn2 "could not register the worker logon task (broker session-spawn will be used): $($_.Exception.Message)"
313
- }
314
-
315
- if (-not $NoStart -and -not $NoLaunch) {
316
- Start-Service -Name $ServiceName
317
- # Verify the broker is actually Running BEFORE retiring the legacy startup.
318
- $deadline = (Get-Date).AddSeconds(30)
319
- $running = $false
320
- while ((Get-Date) -lt $deadline) {
321
- $svcNow = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
322
- if ($svcNow -and $svcNow.Status -eq 'Running') { $running = $true; break }
323
- Start-Sleep -Milliseconds 500
324
- }
325
- if (-not $running) {
326
- Write-Host ' X broker service did not reach Running; NOT retiring legacy startup (rollback preserved)' -ForegroundColor Red
327
- exit 1
328
- }
329
- Write-Ok "service started and verified Running: $ServiceName"
330
-
331
- # 4d. NOW retire the legacy per-user startup (fail-safe step 4-5): disable the
332
- # backed-up launchers, then stop only PROVEN legacy Agent processes.
333
- if (Test-Path -LiteralPath $legacyMod) {
334
- try {
335
- $ld = (& node $legacyMod disable --users-root "$env:SystemDrive\Users" --backup-dir $legacyBackupDir 2>&1 | Out-String)
336
- Write-Ok "legacy per-user startup retired (Startup-folder entries removed; backups retained)"
337
- } catch { Write-Warn2 "legacy startup retire step failed (non-fatal): $($_.Exception.Message)" }
338
-
339
- # Stop only an EXACT legacy Agent process (npm package invocation or the
340
- # legacy launcher BAT), never a generic node.exe.
341
- try {
342
- $legacyProcs = Get-CimInstance Win32_Process | Where-Object {
343
- ($_.CommandLine -match '@xkwdstore[\\/]agent(@\d|\\|\s|")') -or ($_.CommandLine -match 'start-xkwdstore-agent\.bat')
344
- } | Where-Object { $_.CommandLine -notmatch 'XKWDStore\\Agent\\cli\.js' }
345
- foreach ($lp in $legacyProcs) {
346
- Write-Warn2 ("stopping proven legacy Agent process pid=" + $lp.ProcessId)
347
- try { Stop-Process -Id $lp.ProcessId -Force -ErrorAction SilentlyContinue } catch {}
348
- }
349
- } catch {}
350
- }
351
- } else {
352
- Write-Warn2 'service not started (-NoStart/-NoLaunch); legacy startup NOT retired (rollback preserved)'
353
- }
354
-
355
- Write-Host ''
356
- Write-Host " Machine-wide agent installed. Device identity: $MachineRoot\state\servers\..." -ForegroundColor Cyan
357
- Write-Host ' No console window, no taskbar agent. Browser workers attach to the active desktop only.' -ForegroundColor DarkGray
358
- Write-Host ''
359
- exit 0
360
- }
361
-
362
- # -- uninstall ---------------------------------------------------------------
363
- Write-Host ''
364
- Write-Host " XKWDStore Agent $AgentVersion - uninstall" -ForegroundColor Cyan
365
- Assert-Elevated
366
- $svc = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
367
- if ($svc) {
368
- try { Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue } catch { }
369
- sc.exe delete $ServiceName | Out-Null
370
- Write-Ok "service removed: $ServiceName"
371
- } else {
372
- Write-Warn2 'service not present'
373
- }
374
- try { Unregister-ScheduledTask -TaskName 'XKWDStoreAgentWorker' -Confirm:$false -ErrorAction SilentlyContinue | Out-Null; Write-Ok 'worker logon task removed' } catch { }
375
-
376
- # Profile data is PRESERVED by default. Only -PurgeData removes it, explicitly.
377
- if ($PurgeData) {
378
- Write-Warn2 "PURGE: deleting machine state (identity + profiles) at $MachineRoot"
379
- Remove-Item -LiteralPath $MachineRoot -Recurse -Force -ErrorAction SilentlyContinue
380
- Write-Ok 'machine state deleted'
381
- } else {
382
- Write-Ok "profile + identity PRESERVED at $MachineRoot (use -PurgeData to delete)"
383
- }
384
- Write-Host ''
385
- exit 0
1
+ # XKWDStore Agent - Machine-Wide Silent Startup (version from -AgentVersion)
2
+ #
3
+ # Installs / removes the machine-wide BROKER + per-session interactive WORKER
4
+ # startup. This script MUST run elevated (it creates a Windows service and writes
5
+ # %ProgramData%). It is idempotent and preserves device identity + profiles.
6
+ #
7
+ # DESIGN
8
+ # Broker : a Windows Service (elevated, silent, no console, no taskbar window)
9
+ # running as a dedicated service identity (default: LocalSystem, or a
10
+ # configured virtual service account). It owns machine identity, the
11
+ # server WebSocket, leases, and the machine-state ACLs.
12
+ # Worker : spawned PER INTERACTIVE SESSION by the broker (CreateProcessAsUser
13
+ # into the active session) OR, when per-session spawning is not
14
+ # available, by a per-user logon Scheduled Task that ONLY launches the
15
+ # worker with a broker-issued one-time channel token. The worker needs
16
+ # no credential and cannot enroll.
17
+ #
18
+ # WHY A SERVICE (not just a task)
19
+ # - starts at boot, independent of any Windows login
20
+ # - silent (Session 0, no interactive desktop, no console window)
21
+ # - restart-on-crash handled by the SCM with backoff
22
+ # - one machine broker, gated further by a Global\ named mutex
23
+ #
24
+ # LIMITATION (documented): a Session 0 service cannot itself show a browser. The
25
+ # browser MUST run in an interactive session, so the broker hands the browser work
26
+ # to a worker in the active session. This script installs both halves.
27
+ #
28
+ # Options:
29
+ # -AgentVersion <ver> pinned agent version (default 2.1.6)
30
+ # -Server <url> server origin (default https://x.kwdstore.com)
31
+ # -ServiceAccount <s> service identity (default LocalSystem)
32
+ # -Uninstall remove service + startup (keeps ProgramData unless -PurgeData)
33
+ # -PurgeData with -Uninstall, also delete machine state (EXPLICIT)
34
+ # -NoStart install but do not start
35
+ # -NoLaunch (test) validate + write files, never start a process
36
+
37
+ param(
38
+ [string]$AgentVersion = '2.1.6',
39
+ [string]$Server = 'https://x.kwdstore.com',
40
+ [string]$ServiceAccount = 'LocalSystem',
41
+ [string]$AgentRoot,
42
+ [switch]$Uninstall,
43
+ [switch]$PurgeData,
44
+ [switch]$NoStart,
45
+ [switch]$NoLaunch
46
+ )
47
+
48
+ $ErrorActionPreference = 'Stop'
49
+ $ServiceName = 'XKWDStoreAgentBroker'
50
+ $ServiceDisplay = 'XKWDStore Agent Broker (machine-wide)'
51
+ $MachineRoot = if ($AgentRoot) { $AgentRoot } else { Join-Path $env:ProgramData 'XKWDStore\Agent' }
52
+
53
+ function Write-Step([string]$msg) { Write-Host " $msg" -ForegroundColor Cyan }
54
+ function Write-Ok([string]$msg) { Write-Host " OK $msg" -ForegroundColor Green }
55
+ function Write-Warn2([string]$msg) { Write-Host " ! $msg" -ForegroundColor Yellow }
56
+
57
+ function Assert-Elevated {
58
+ $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
59
+ $p = New-Object System.Security.Principal.WindowsPrincipal($id)
60
+ if (-not $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) {
61
+ Write-Host 'This script must run elevated (Administrator).' -ForegroundColor Red
62
+ exit 5
63
+ }
64
+ }
65
+
66
+ function Get-NodePath {
67
+ $cmd = Get-Command node -ErrorAction SilentlyContinue
68
+ if (-not $cmd) { throw 'Node.js 22+ is required on PATH.' }
69
+ return $cmd.Source
70
+ }
71
+
72
+ # -- install -----------------------------------------------------------------
73
+ if (-not $Uninstall) {
74
+ Write-Host ''
75
+ Write-Host " XKWDStore Agent $AgentVersion - machine-wide silent startup" -ForegroundColor Cyan
76
+ Write-Host ' ==================================================' -ForegroundColor Cyan
77
+ Assert-Elevated
78
+ $node = Get-NodePath
79
+ Write-Step "node: $node"
80
+
81
+ # 1. layout + restrictive ACLs (owner + Administrators + SYSTEM only)
82
+ foreach ($sub in @('', 'config', 'identity', 'credentials', 'logs', 'runtime', 'state', 'launcher', 'state\profiles', 'state\servers')) {
83
+ $d = if ($sub) { Join-Path $MachineRoot $sub } else { $MachineRoot }
84
+ if (-not (Test-Path -LiteralPath $d)) { New-Item -ItemType Directory -Force -Path $d | Out-Null }
85
+ }
86
+ Write-Ok "machine root: $MachineRoot"
87
+
88
+ # 1a. install the agent program files (so the service does not depend on the repo)
89
+ $AgentInstallDir = if ($AgentRoot) { Join-Path $AgentRoot 'program' } else { Join-Path ${env:ProgramFiles} 'XKWDStore\Agent' }
90
+ $srcDir = Join-Path (Split-Path $PSScriptRoot -Parent) 'src'
91
+ if (Test-Path -LiteralPath $srcDir) {
92
+ if (-not (Test-Path -LiteralPath $AgentInstallDir)) { New-Item -ItemType Directory -Force -Path $AgentInstallDir | Out-Null }
93
+ Copy-Item -Path (Join-Path $srcDir '*') -Destination $AgentInstallDir -Recurse -Force
94
+ foreach ($f in @('package.json', 'package-lock.json', 'node_modules')) {
95
+ $sf = Join-Path (Split-Path $PSScriptRoot -Parent) $f
96
+ if (Test-Path -LiteralPath $sf) {
97
+ if ((Get-Item $sf).PSIsContainer) {
98
+ Copy-Item -Path $sf -Destination (Join-Path $AgentInstallDir $f) -Recurse -Force -ErrorAction SilentlyContinue
99
+ } else {
100
+ Copy-Item -Path $sf -Destination (Join-Path $AgentInstallDir $f) -Force -ErrorAction SilentlyContinue
101
+ }
102
+ }
103
+ }
104
+ Write-Ok "agent files installed: $AgentInstallDir"
105
+ } else {
106
+ Write-Warn2 "agent src not found next to the installer; using the repo path in the service wrapper"
107
+ }
108
+
109
+ # 1a-bis. Provision the RUNTIME DEPENDENCIES into the install dir.
110
+ # The block above copies a `node_modules` only if one sits next to the
111
+ # installer. A normal `npm install @xkwdstore/agent` hoists the agent's
112
+ # dependencies to the CALLER's node_modules, so the package directory ships
113
+ # none. Copying only what happens to be there therefore produced an install
114
+ # with no dependencies at all, and the broker died on its first bare
115
+ # `require('playwright-core')` - a MODULE_NOT_FOUND crash-loop masked by the
116
+ # service restarting it. The installer must guarantee the dependency tree
117
+ # exists, not hope it was shipped alongside.
118
+ $agentPkgJson = Join-Path $AgentInstallDir 'package.json'
119
+ if (Test-Path -LiteralPath $agentPkgJson) {
120
+ $depProbe = Join-Path $AgentInstallDir 'node_modules\playwright-core'
121
+ if (-not (Test-Path -LiteralPath $depProbe)) {
122
+ $agentLockJson = Join-Path $AgentInstallDir 'package-lock.json'
123
+ Write-Step 'provisioning agent runtime dependencies (npm)'
124
+ Push-Location $AgentInstallDir
125
+ try {
126
+ if (Test-Path -LiteralPath $agentLockJson) {
127
+ & npm ci --omit=dev --no-audit --no-fund *> $null
128
+ } else {
129
+ & npm install --omit=dev --no-audit --no-fund *> $null
130
+ }
131
+ } finally { Pop-Location }
132
+ if (-not (Test-Path -LiteralPath $depProbe)) {
133
+ Write-Host ' X agent runtime dependencies could not be provisioned.' -ForegroundColor Red
134
+ Write-Host ' The agent needs npm + network access on this machine.' -ForegroundColor Red
135
+ exit 1
136
+ }
137
+ Write-Ok 'agent runtime dependencies provisioned'
138
+ } else {
139
+ Write-Ok 'agent runtime dependencies already present'
140
+ }
141
+ }
142
+
143
+ # 1b. place the worker-entry launcher where the logon task expects it AND the
144
+ # installer-managed scripts next to the installed program files.
145
+ $workerEntrySrc = Join-Path $PSScriptRoot 'worker-entry.js'
146
+ $workerEntryDst = Join-Path $AgentInstallDir 'scripts\worker-entry.js'
147
+ if (Test-Path -LiteralPath $workerEntrySrc) {
148
+ New-Item -ItemType Directory -Force -Path (Split-Path $workerEntryDst -Parent) | Out-Null
149
+ Copy-Item -Path $workerEntrySrc -Destination $workerEntryDst -Force
150
+ }
151
+
152
+ $aclApply = @"
153
+ `$ErrorActionPreference='Stop'
154
+ `$root = '$($MachineRoot.Replace("'","''"))'
155
+ `$owner = ([System.Security.Principal.WindowsIdentity]::GetCurrent()).User.Value
156
+ `$sids = @(`$owner, 'S-1-5-18','S-1-5-32-544')
157
+ `$dirs = @(`$root, (Join-Path `$root 'config'), (Join-Path `$root 'identity'), (Join-Path `$root 'credentials'), (Join-Path `$root 'logs'), (Join-Path `$root 'runtime'), (Join-Path `$root 'state'), (Join-Path `$root 'launcher'), (Join-Path `$root 'state\profiles'), (Join-Path `$root 'state\servers'))
158
+ foreach (`$dir in `$dirs) {
159
+ if (-not (Test-Path -LiteralPath `$dir)) { continue }
160
+ `$acl = New-Object System.Security.AccessControl.DirectorySecurity
161
+ `$acl.SetAccessRuleProtection(`$true, `$false)
162
+ foreach (`$sid in `$sids) {
163
+ `$rule = New-Object System.Security.AccessControl.FileSystemAccessRule((New-Object System.Security.Principal.SecurityIdentifier(`$sid)), 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
164
+ `$acl.AddAccessRule(`$rule)
165
+ }
166
+ (Get-Item -LiteralPath `$dir).SetAccessControl(`$acl)
167
+ }
168
+ "@
169
+ $aclFile = Join-Path $env:TEMP ("xkwd-acl-" + [guid]::NewGuid().ToString('N') + '.ps1')
170
+ Set-Content -Path $aclFile -Value $aclApply -Encoding UTF8
171
+ & powershell -NoProfile -ExecutionPolicy Bypass -File $aclFile
172
+ Remove-Item $aclFile -Force -ErrorAction SilentlyContinue
173
+ Write-Ok 'ACLs applied (owner + Administrators + SYSTEM; no broad principals)'
174
+
175
+ # 1c. Re-protect any adopted (v1/CurrentUser) machine credential under
176
+ # LocalMachine scope so the SERVICE broker (LocalSystem) can decrypt it.
177
+ # Preserves the SAME key material -> same deviceId + pairing. Run as the
178
+ # elevated OWNER so the CurrentUser blob is decryptable here.
179
+ $rescope = @"
180
+ `$ErrorActionPreference='Continue'
181
+ `$env:XKWDSTORE_MACHINE_ROOT = '$($MachineRoot.Replace("'","''"))'
182
+ `$env:XKWDSTORE_DPAPI_SCOPE = 'LocalMachine'
183
+ Push-Location '$((Join-Path $AgentInstallDir '').Replace("'","''"))'
184
+ try {
185
+ `$dk = node -e "const dk=require('./deviceKeyStore'); const r=dk.rescopeWindowsKey({serverOrigin:'$($Server)'}); console.log(JSON.stringify(r));"
186
+ Write-Output ('RESCOPE ' + (`$dk -join ' '))
187
+ } finally { Pop-Location }
188
+ "@
189
+ $rescopeFile = Join-Path $env:TEMP ("xkwd-rescope-" + [guid]::NewGuid().ToString('N') + '.ps1')
190
+ Set-Content -Path $rescopeFile -Value $rescope -Encoding UTF8
191
+ & powershell -NoProfile -ExecutionPolicy Bypass -File $rescopeFile
192
+ Remove-Item $rescopeFile -Force -ErrorAction SilentlyContinue
193
+ Write-Ok 'machine credential scope reconciled to LocalMachine (if it was CurrentUser)'
194
+
195
+ # 1d. legacy per-user startup: DETECT + BACK UP (fail-safe step 1-2).
196
+ # A 2.0.x install may have left a per-user `start-xkwdstore-agent.bat`
197
+ # (auto-start) that must not run once the machine service is authoritative.
198
+ # We only BACK UP here; the backup preserves exact bytes + hash so rollback
199
+ # is always possible. Disable happens LATER, only after the broker is
200
+ # verified Running (fail-safe step 3 -> 4).
201
+ $legacyMod = Join-Path $AgentInstallDir 'legacyStartup.js'
202
+ $legacyBackupDir = Join-Path $MachineRoot 'state\legacy-startup-backup'
203
+ if (Test-Path -LiteralPath $legacyMod) {
204
+ try {
205
+ $lb = (& node $legacyMod backup --users-root "$env:SystemDrive\Users" --backup-dir $legacyBackupDir 2>&1 | Out-String)
206
+ $lbObj = $lb | ConvertFrom-Json
207
+ Write-Ok ("legacy per-user startup: backed up " + $lbObj.count + " launcher(s) (rollback preserved)")
208
+ } catch { Write-Warn2 "legacy startup backup step failed (non-fatal): $($_.Exception.Message)" }
209
+ }
210
+
211
+ # 2. service host (REAL Windows service: reports SERVICE_RUNNING to the SCM).
212
+ # A running service LOCKS its own EXE, so stop it before recompiling.
213
+ if (Get-Service -Name $ServiceName -ErrorAction SilentlyContinue) {
214
+ Write-Step "stopping existing $ServiceName before host recompile"
215
+ try { Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue } catch { }
216
+ $dl = (Get-Date).AddSeconds(20)
217
+ while ((Get-Service -Name $ServiceName -ErrorAction SilentlyContinue).Status -ne 'Stopped' -and (Get-Date) -lt $dl) { Start-Sleep -Milliseconds 500 }
218
+ }
219
+ # A compiled EXE is required: `powershell.exe -File` and `cmd /c` both fail
220
+ # as SCM binaries (they exit before StartServiceCtrlDispatcher / 30s timeout).
221
+ # The installer compiles broker-service-host.cs with the IN-BOX .NET
222
+ # Framework compiler (no external dependency).
223
+ $hostCs = Join-Path $PSScriptRoot 'broker-service-host.cs'
224
+ $hostExe = Join-Path $MachineRoot 'launcher\XKWDStoreBrokerService.exe'
225
+ if (-not (Test-Path -LiteralPath $hostCs)) {
226
+ Write-Host " X broker-service-host.cs not found next to the installer: $hostCs" -ForegroundColor Red
227
+ exit 1
228
+ }
229
+ $csc = Join-Path $env:SystemRoot 'Microsoft.NET\Framework64\v4.0.30319\csc.exe'
230
+ if (-not (Test-Path -LiteralPath $csc)) { $csc = Join-Path $env:SystemRoot 'Microsoft.NET\Framework\v4.0.30319\csc.exe' }
231
+ if (-not (Test-Path -LiteralPath $csc)) {
232
+ Write-Host ' X in-box .NET Framework compiler (csc.exe) not found' -ForegroundColor Red
233
+ exit 1
234
+ }
235
+ New-Item -ItemType Directory -Force -Path (Split-Path $hostExe -Parent) | Out-Null
236
+ $cscArgs = @('/nologo', '/target:exe', "/out:$hostExe", '/reference:System.ServiceProcess.dll', $hostCs)
237
+ $cscOut = (& $csc $cscArgs 2>&1)
238
+ if (-not (Test-Path -LiteralPath $hostExe) -or ($cscOut -match 'error CS')) {
239
+ Write-Host ' X service host compilation failed:' -ForegroundColor Red
240
+ Write-Host (" " + ($cscOut -join "`n ")) -ForegroundColor Red
241
+ exit 1
242
+ }
243
+ Write-Ok "service host compiled: $hostExe"
244
+
245
+ # 2b. compile the interactive-session launcher so the Session-0 broker can
246
+ # create the Browser Worker in the active interactive user session.
247
+ $launcherCs = Join-Path $PSScriptRoot 'session-launcher.cs'
248
+ $launcherExe = Join-Path $MachineRoot 'launcher\XKWDStoreSessionLauncher.exe'
249
+ if (Test-Path -LiteralPath $launcherCs) {
250
+ $lOut = (& $csc @('/nologo', '/target:exe', "/out:$launcherExe", $launcherCs) 2>&1)
251
+ if (-not (Test-Path -LiteralPath $launcherExe) -or ($lOut -match 'error CS')) {
252
+ Write-Host ' X session launcher compilation failed:' -ForegroundColor Red
253
+ Write-Host (" " + ($lOut -join "`n ")) -ForegroundColor Red
254
+ exit 1
255
+ }
256
+ Write-Ok "session launcher compiled: $launcherExe"
257
+ } else {
258
+ Write-Warn2 "session-launcher.cs not found next to the installer; interactive worker launch may fail"
259
+ }
260
+
261
+ $cliJs = Join-Path $AgentInstallDir 'cli.js'
262
+ if (-not (Test-Path -LiteralPath $cliJs)) {
263
+ $cliJs = Join-Path (Split-Path $PSScriptRoot -Parent) 'src\cli.js'
264
+ Write-Warn2 "service host falling back to the repo CLI: $cliJs"
265
+ }
266
+ $agentNode = $node
267
+ $svcBin = '"' + $hostExe + '" -Node "' + $agentNode + '" -Cli "' + $cliJs + '" -Root "' + $MachineRoot + '" -Server "' + $Server + '"'
268
+
269
+ # 3. (re)create the service so no stale configuration survives. An in-place
270
+ # `sc config` can leave remnants; delete + wait + create is deterministic.
271
+ $svc = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
272
+ if ($svc) {
273
+ Write-Step "removing existing service $ServiceName (clean recreate)"
274
+ try { Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue } catch { }
275
+ (sc.exe delete $ServiceName) | Out-Null
276
+ $deadline = (Get-Date).AddSeconds(20)
277
+ while ((Get-Service -Name $ServiceName -ErrorAction SilentlyContinue) -and (Get-Date) -lt $deadline) { Start-Sleep -Milliseconds 500 }
278
+ if (Get-Service -Name $ServiceName -ErrorAction SilentlyContinue) { Write-Warn2 'existing service did not disappear within 20s' }
279
+ }
280
+ Write-Step "creating service $ServiceName (account=$ServiceAccount)"
281
+ if ($ServiceAccount -eq 'LocalSystem') {
282
+ New-Service -Name $ServiceName -BinaryPathName $svcBin -DisplayName $ServiceDisplay -StartupType Automatic | Out-Null
283
+ } else {
284
+ New-Service -Name $ServiceName -BinaryPathName $svcBin -DisplayName $ServiceDisplay -StartupType Automatic -Credential $ServiceAccount | Out-Null
285
+ }
286
+ # restart-on-crash with backoff + no interactive desktop
287
+ sc.exe failure $ServiceName reset= 86400 actions= restart/5000/restart/15000/restart/60000 | Out-Null
288
+ sc.exe description $ServiceName "Machine-wide XKWDStore broker: identity, server connection, leases; spawns interactive browser workers." | Out-Null
289
+ Write-Ok 'service configured (auto-start, restart-on-crash/backoff)'
290
+
291
+ # 3a. verify the SCM binary path no longer references the old cmd wrapper.
292
+ $finalPath = ((sc.exe qc $ServiceName 2>&1) | Where-Object { $_ -match 'BINARY_PATH_NAME' })
293
+ if ($finalPath -match 'cmd\.exe /c') {
294
+ Write-Host ' X service binary path still references the old cmd wrapper.' -ForegroundColor Red
295
+ exit 1
296
+ } else {
297
+ Write-Ok "service binary path verified (no cmd wrapper): $($finalPath -replace '\s+',' ')"
298
+ }
299
+ # 3b. remove a stale diagnostic wrapper if it exists (never used by the SCM now).
300
+ $staleCmd = Join-Path $MachineRoot 'launcher\broker-service.cmd'
301
+ if (Test-Path -LiteralPath $staleCmd) { Remove-Item $staleCmd -Force -ErrorAction SilentlyContinue }
302
+
303
+ # 4. per-session worker fallback (logon task) - only used if session spawning is unavailable
304
+ $taskName = 'XKWDStoreAgentWorker'
305
+ try {
306
+ $action = New-ScheduledTaskAction -Execute $node -Argument "`"$workerEntryDst`""
307
+ $trigger = New-ScheduledTaskTrigger -AtLogOn
308
+ $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -MultipleInstances IgnoreNew
309
+ Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Settings $settings -Description 'Per-interactive-session XKWDStore browser worker (broker-token gated).' -Force | Out-Null
310
+ Write-Ok "worker logon task registered: $taskName"
311
+ } catch {
312
+ Write-Warn2 "could not register the worker logon task (broker session-spawn will be used): $($_.Exception.Message)"
313
+ }
314
+
315
+ if (-not $NoStart -and -not $NoLaunch) {
316
+ Start-Service -Name $ServiceName
317
+ # Verify the broker is actually Running BEFORE retiring the legacy startup.
318
+ $deadline = (Get-Date).AddSeconds(30)
319
+ $running = $false
320
+ while ((Get-Date) -lt $deadline) {
321
+ $svcNow = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
322
+ if ($svcNow -and $svcNow.Status -eq 'Running') { $running = $true; break }
323
+ Start-Sleep -Milliseconds 500
324
+ }
325
+ if (-not $running) {
326
+ Write-Host ' X broker service did not reach Running; NOT retiring legacy startup (rollback preserved)' -ForegroundColor Red
327
+ exit 1
328
+ }
329
+ Write-Ok "service started and verified Running: $ServiceName"
330
+
331
+ # 4d. NOW retire the legacy per-user startup (fail-safe step 4-5): disable the
332
+ # backed-up launchers, then stop only PROVEN legacy Agent processes.
333
+ if (Test-Path -LiteralPath $legacyMod) {
334
+ try {
335
+ $ld = (& node $legacyMod disable --users-root "$env:SystemDrive\Users" --backup-dir $legacyBackupDir 2>&1 | Out-String)
336
+ Write-Ok "legacy per-user startup retired (Startup-folder entries removed; backups retained)"
337
+ } catch { Write-Warn2 "legacy startup retire step failed (non-fatal): $($_.Exception.Message)" }
338
+
339
+ # Stop only an EXACT legacy Agent process (npm package invocation or the
340
+ # legacy launcher BAT), never a generic node.exe.
341
+ try {
342
+ $legacyProcs = Get-CimInstance Win32_Process | Where-Object {
343
+ ($_.CommandLine -match '@xkwdstore[\\/]agent(@\d|\\|\s|")') -or ($_.CommandLine -match 'start-xkwdstore-agent\.bat')
344
+ } | Where-Object { $_.CommandLine -notmatch 'XKWDStore\\Agent\\cli\.js' }
345
+ foreach ($lp in $legacyProcs) {
346
+ Write-Warn2 ("stopping proven legacy Agent process pid=" + $lp.ProcessId)
347
+ try { Stop-Process -Id $lp.ProcessId -Force -ErrorAction SilentlyContinue } catch {}
348
+ }
349
+ } catch {}
350
+ }
351
+ } else {
352
+ Write-Warn2 'service not started (-NoStart/-NoLaunch); legacy startup NOT retired (rollback preserved)'
353
+ }
354
+
355
+ Write-Host ''
356
+ Write-Host " Machine-wide agent installed. Device identity: $MachineRoot\state\servers\..." -ForegroundColor Cyan
357
+ Write-Host ' No console window, no taskbar agent. Browser workers attach to the active desktop only.' -ForegroundColor DarkGray
358
+ Write-Host ''
359
+ exit 0
360
+ }
361
+
362
+ # -- uninstall ---------------------------------------------------------------
363
+ Write-Host ''
364
+ Write-Host " XKWDStore Agent $AgentVersion - uninstall" -ForegroundColor Cyan
365
+ Assert-Elevated
366
+ $svc = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
367
+ if ($svc) {
368
+ try { Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue } catch { }
369
+ sc.exe delete $ServiceName | Out-Null
370
+ Write-Ok "service removed: $ServiceName"
371
+ } else {
372
+ Write-Warn2 'service not present'
373
+ }
374
+ try { Unregister-ScheduledTask -TaskName 'XKWDStoreAgentWorker' -Confirm:$false -ErrorAction SilentlyContinue | Out-Null; Write-Ok 'worker logon task removed' } catch { }
375
+
376
+ # Profile data is PRESERVED by default. Only -PurgeData removes it, explicitly.
377
+ if ($PurgeData) {
378
+ Write-Warn2 "PURGE: deleting machine state (identity + profiles) at $MachineRoot"
379
+ Remove-Item -LiteralPath $MachineRoot -Recurse -Force -ErrorAction SilentlyContinue
380
+ Write-Ok 'machine state deleted'
381
+ } else {
382
+ Write-Ok "profile + identity PRESERVED at $MachineRoot (use -PurgeData to delete)"
383
+ }
384
+ Write-Host ''
385
+ exit 0