@xkwdstore/agent 2.0.7 → 2.1.1

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.
@@ -0,0 +1,208 @@
1
+ // XKWDStore Agent 2.1.0 — compiled Windows Service host (broker).
2
+ //
3
+ // WHY COMPILED: a Windows service binary must call StartServiceCtrlDispatcher and
4
+ // report SERVICE_RUNNING. `powershell.exe -File <script>` proved unreliable as an
5
+ // SCM binary (it exits before running). This EXE is compiled by the installer with
6
+ // the IN-BOX .NET Framework compiler (csc.exe, no external dependency) and is the
7
+ // SCM-facing process. It:
8
+ //
9
+ // 1. launches `node <cli.js> service ...` as a CHILD in Session 0 with a fixed
10
+ // working directory, no window, and file-redirected stdio;
11
+ // 2. reports SERVICE_RUNNING immediately;
12
+ // 3. kills the child on stop/shutdown;
13
+ // 4. restarts the child if it exits unexpectedly (bounded backoff) so a broker
14
+ // crash recovers without relying solely on the SCM;
15
+ // 5. logs SAFE lifecycle info only (no credentials, no key material).
16
+ //
17
+ // The broker owns the machine identity/WebSocket/leases and never launches
18
+ // Chromium; browser work is delegated to an interactive-session worker.
19
+
20
+ using System;
21
+ using System.Diagnostics;
22
+ using System.IO;
23
+ using System.ServiceProcess;
24
+ using System.Threading;
25
+
26
+ public sealed class XkwdBrokerService : ServiceBase
27
+ {
28
+ private readonly string _node;
29
+ private readonly string _argLine;
30
+ private readonly string _workDir;
31
+ private readonly string _logFile;
32
+ private readonly string _outFile;
33
+ private readonly string _errFile;
34
+
35
+ private Process _child;
36
+ private Thread _watch;
37
+ private volatile bool _stopping;
38
+ private static readonly object _logLock = new object();
39
+
40
+ public XkwdBrokerService(string node, string argLine, string workDir, string logFile, string outFile, string errFile)
41
+ {
42
+ this.ServiceName = "XKWDStoreAgentBroker";
43
+ this.CanStop = true;
44
+ this.CanShutdown = true;
45
+ this.CanPauseAndContinue = false;
46
+ _node = node; _argLine = argLine; _workDir = workDir;
47
+ _logFile = logFile; _outFile = outFile; _errFile = errFile;
48
+ }
49
+
50
+ private static void Log(string file, string message)
51
+ {
52
+ try
53
+ {
54
+ lock (_logLock)
55
+ {
56
+ File.AppendAllText(file, string.Format("[{0}] {1}{2}", DateTime.UtcNow.ToString("o"), message, Environment.NewLine));
57
+ }
58
+ }
59
+ catch { }
60
+ }
61
+
62
+ private void Log(string message) { Log(_logFile, message); }
63
+
64
+ private void StartChild()
65
+ {
66
+ var psi = new ProcessStartInfo(_node, _argLine);
67
+ psi.UseShellExecute = false;
68
+ psi.CreateNoWindow = true;
69
+ psi.WorkingDirectory = _workDir;
70
+ psi.RedirectStandardOutput = true;
71
+ psi.RedirectStandardError = true;
72
+ var p = new Process();
73
+ p.StartInfo = psi;
74
+ p.OutputDataReceived += (s, e) => { if (e.Data != null) Log(_outFile, e.Data); };
75
+ p.ErrorDataReceived += (s, e) => { if (e.Data != null) Log(_errFile, e.Data); };
76
+ p.Start();
77
+ p.BeginOutputReadLine();
78
+ p.BeginErrorReadLine();
79
+ _child = p;
80
+ Log("broker child started pid=" + p.Id);
81
+ }
82
+
83
+ protected override void OnStart(string[] args)
84
+ {
85
+ Log("service OnStart node=" + _node + " workdir=" + _workDir);
86
+ try { StartChild(); }
87
+ catch (Exception ex) { Log("broker child start FAILED: " + ex.Message); }
88
+ // Watchdog: if the broker dies unexpectedly (not during stop), restart it
89
+ // with a bounded backoff so a crash does not require a manual restart.
90
+ _watch = new Thread(() =>
91
+ {
92
+ int attempts = 0;
93
+ int[] delays = new int[] { 5000, 15000, 60000 };
94
+ while (!_stopping)
95
+ {
96
+ Thread.Sleep(2000);
97
+ if (_stopping) break;
98
+ Process c = _child;
99
+ if (c == null) continue;
100
+ try
101
+ {
102
+ if (!c.HasExited)
103
+ {
104
+ if (attempts != 0) attempts = 0; // healthy
105
+ continue;
106
+ }
107
+ }
108
+ catch { continue; }
109
+ if (_stopping) break;
110
+ int d = delays[Math.Min(attempts, delays.Length - 1)];
111
+ attempts++;
112
+ Log("broker child exited code=" + (SafeExit(c)) + "; restart in " + d + "ms (attempt " + attempts + ")");
113
+ Thread.Sleep(d);
114
+ if (_stopping) break;
115
+ try { StartChild(); } catch (Exception ex) { Log("broker restart failed: " + ex.Message); }
116
+ }
117
+ });
118
+ _watch.IsBackground = true;
119
+ _watch.Start();
120
+ }
121
+
122
+ private static string SafeExit(Process p)
123
+ {
124
+ try { return p.ExitCode.ToString(); } catch { return "unknown"; }
125
+ }
126
+
127
+ protected override void OnStop()
128
+ {
129
+ _stopping = true;
130
+ Log("service OnStop");
131
+ StopChild();
132
+ }
133
+
134
+ protected override void OnShutdown()
135
+ {
136
+ _stopping = true;
137
+ Log("service OnShutdown");
138
+ StopChild();
139
+ }
140
+
141
+ private void StopChild()
142
+ {
143
+ try
144
+ {
145
+ Process c = _child;
146
+ if (c != null && !c.HasExited)
147
+ {
148
+ c.Kill();
149
+ c.WaitForExit(15000);
150
+ Log("broker child stopped");
151
+ }
152
+ }
153
+ catch (Exception ex) { Log("StopChild error: " + ex.Message); }
154
+ }
155
+
156
+ public static void Main()
157
+ {
158
+ try
159
+ {
160
+ string node = null, cli = null, root = null, server = "https://x.kwdstore.com";
161
+ // Args are supplied by the SCM binPath as: -Node <n> -Cli <c> -Root <r> -Server <s>
162
+ var a = Environment.GetCommandLineArgs();
163
+ for (int i = 1; i < a.Length - 1; i++)
164
+ {
165
+ switch (a[i])
166
+ {
167
+ case "-Node": node = a[++i]; break;
168
+ case "-Cli": cli = a[++i]; break;
169
+ case "-Root": root = a[++i]; break;
170
+ case "-Server": server = a[++i]; break;
171
+ }
172
+ }
173
+ if (node == null || cli == null || root == null)
174
+ {
175
+ // Not enough info to run as a service.
176
+ return;
177
+ }
178
+ string workDir = Path.GetDirectoryName(cli);
179
+ string logDir = Path.Combine(root, "logs");
180
+ Directory.CreateDirectory(logDir);
181
+ string logFile = Path.Combine(logDir, "service-host.log");
182
+ string outFile = Path.Combine(logDir, "broker.out.log");
183
+ string errFile = Path.Combine(logDir, "broker.err.log");
184
+
185
+ Environment.SetEnvironmentVariable("XKWDSTORE_MACHINE_ROOT", root);
186
+ Environment.SetEnvironmentVariable("XKWDSTORE_DPAPI_SCOPE", "LocalMachine");
187
+
188
+ string argLine = "\"" + cli + "\" service --server \"" + server + "\"";
189
+ ServiceBase.Run(new XkwdBrokerService(node, argLine, workDir, logFile, outFile, errFile));
190
+ }
191
+ catch (Exception ex)
192
+ {
193
+ try
194
+ {
195
+ string root = null;
196
+ var a = Environment.GetCommandLineArgs();
197
+ for (int i = 1; i < a.Length - 1; i++) if (a[i] == "-Root") root = a[++i];
198
+ if (root != null)
199
+ {
200
+ string logDir = Path.Combine(root, "logs");
201
+ Directory.CreateDirectory(logDir);
202
+ Log(Path.Combine(logDir, "service-host.log"), "FATAL Main: " + ex.ToString());
203
+ }
204
+ }
205
+ catch { }
206
+ }
207
+ }
208
+ }
@@ -0,0 +1,351 @@
1
+ # XKWDStore Agent 2.1.0 — Machine-Wide Silent Startup
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.0)
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.1',
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 2.1.0 — 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
+ # 1b. place the worker-entry launcher where the logon task expects it AND the
110
+ # installer-managed scripts next to the installed program files.
111
+ $workerEntrySrc = Join-Path $PSScriptRoot 'worker-entry.js'
112
+ $workerEntryDst = Join-Path $AgentInstallDir 'scripts\worker-entry.js'
113
+ if (Test-Path -LiteralPath $workerEntrySrc) {
114
+ New-Item -ItemType Directory -Force -Path (Split-Path $workerEntryDst -Parent) | Out-Null
115
+ Copy-Item -Path $workerEntrySrc -Destination $workerEntryDst -Force
116
+ }
117
+
118
+ $aclApply = @"
119
+ `$ErrorActionPreference='Stop'
120
+ `$root = '$($MachineRoot.Replace("'","''"))'
121
+ `$owner = ([System.Security.Principal.WindowsIdentity]::GetCurrent()).User.Value
122
+ `$sids = @(`$owner, 'S-1-5-18','S-1-5-32-544')
123
+ `$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'))
124
+ foreach (`$dir in `$dirs) {
125
+ if (-not (Test-Path -LiteralPath `$dir)) { continue }
126
+ `$acl = New-Object System.Security.AccessControl.DirectorySecurity
127
+ `$acl.SetAccessRuleProtection(`$true, `$false)
128
+ foreach (`$sid in `$sids) {
129
+ `$rule = New-Object System.Security.AccessControl.FileSystemAccessRule((New-Object System.Security.Principal.SecurityIdentifier(`$sid)), 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')
130
+ `$acl.AddAccessRule(`$rule)
131
+ }
132
+ (Get-Item -LiteralPath `$dir).SetAccessControl(`$acl)
133
+ }
134
+ "@
135
+ $aclFile = Join-Path $env:TEMP ("xkwd-acl-" + [guid]::NewGuid().ToString('N') + '.ps1')
136
+ Set-Content -Path $aclFile -Value $aclApply -Encoding UTF8
137
+ & powershell -NoProfile -ExecutionPolicy Bypass -File $aclFile
138
+ Remove-Item $aclFile -Force -ErrorAction SilentlyContinue
139
+ Write-Ok 'ACLs applied (owner + Administrators + SYSTEM; no broad principals)'
140
+
141
+ # 1c. Re-protect any adopted (v1/CurrentUser) machine credential under
142
+ # LocalMachine scope so the SERVICE broker (LocalSystem) can decrypt it.
143
+ # Preserves the SAME key material -> same deviceId + pairing. Run as the
144
+ # elevated OWNER so the CurrentUser blob is decryptable here.
145
+ $rescope = @"
146
+ `$ErrorActionPreference='Continue'
147
+ `$env:XKWDSTORE_MACHINE_ROOT = '$($MachineRoot.Replace("'","''"))'
148
+ `$env:XKWDSTORE_DPAPI_SCOPE = 'LocalMachine'
149
+ Push-Location '$((Join-Path $AgentInstallDir '').Replace("'","''"))'
150
+ try {
151
+ `$dk = node -e "const dk=require('./deviceKeyStore'); const r=dk.rescopeWindowsKey({serverOrigin:'$($Server)'}); console.log(JSON.stringify(r));"
152
+ Write-Output ('RESCOPE ' + (`$dk -join ' '))
153
+ } finally { Pop-Location }
154
+ "@
155
+ $rescopeFile = Join-Path $env:TEMP ("xkwd-rescope-" + [guid]::NewGuid().ToString('N') + '.ps1')
156
+ Set-Content -Path $rescopeFile -Value $rescope -Encoding UTF8
157
+ & powershell -NoProfile -ExecutionPolicy Bypass -File $rescopeFile
158
+ Remove-Item $rescopeFile -Force -ErrorAction SilentlyContinue
159
+ Write-Ok 'machine credential scope reconciled to LocalMachine (if it was CurrentUser)'
160
+
161
+ # 1d. legacy per-user startup: DETECT + BACK UP (fail-safe step 1-2).
162
+ # A 2.0.x install may have left a per-user `start-xkwdstore-agent.bat`
163
+ # (auto-start) that must not run once the machine service is authoritative.
164
+ # We only BACK UP here; the backup preserves exact bytes + hash so rollback
165
+ # is always possible. Disable happens LATER, only after the broker is
166
+ # verified Running (fail-safe step 3 -> 4).
167
+ $legacyMod = Join-Path $AgentInstallDir 'legacyStartup.js'
168
+ $legacyBackupDir = Join-Path $MachineRoot 'state\legacy-startup-backup'
169
+ if (Test-Path -LiteralPath $legacyMod) {
170
+ try {
171
+ $lb = (& node $legacyMod backup --users-root "$env:SystemDrive\Users" --backup-dir $legacyBackupDir 2>&1 | Out-String)
172
+ $lbObj = $lb | ConvertFrom-Json
173
+ Write-Ok ("legacy per-user startup: backed up " + $lbObj.count + " launcher(s) (rollback preserved)")
174
+ } catch { Write-Warn2 "legacy startup backup step failed (non-fatal): $($_.Exception.Message)" }
175
+ }
176
+
177
+ # 2. service host (REAL Windows service: reports SERVICE_RUNNING to the SCM).
178
+ # A running service LOCKS its own EXE, so stop it before recompiling.
179
+ if (Get-Service -Name $ServiceName -ErrorAction SilentlyContinue) {
180
+ Write-Step "stopping existing $ServiceName before host recompile"
181
+ try { Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue } catch { }
182
+ $dl = (Get-Date).AddSeconds(20)
183
+ while ((Get-Service -Name $ServiceName -ErrorAction SilentlyContinue).Status -ne 'Stopped' -and (Get-Date) -lt $dl) { Start-Sleep -Milliseconds 500 }
184
+ }
185
+ # A compiled EXE is required: `powershell.exe -File` and `cmd /c` both fail
186
+ # as SCM binaries (they exit before StartServiceCtrlDispatcher / 30s timeout).
187
+ # The installer compiles broker-service-host.cs with the IN-BOX .NET
188
+ # Framework compiler (no external dependency).
189
+ $hostCs = Join-Path $PSScriptRoot 'broker-service-host.cs'
190
+ $hostExe = Join-Path $MachineRoot 'launcher\XKWDStoreBrokerService.exe'
191
+ if (-not (Test-Path -LiteralPath $hostCs)) {
192
+ Write-Host " X broker-service-host.cs not found next to the installer: $hostCs" -ForegroundColor Red
193
+ exit 1
194
+ }
195
+ $csc = Join-Path $env:SystemRoot 'Microsoft.NET\Framework64\v4.0.30319\csc.exe'
196
+ if (-not (Test-Path -LiteralPath $csc)) { $csc = Join-Path $env:SystemRoot 'Microsoft.NET\Framework\v4.0.30319\csc.exe' }
197
+ if (-not (Test-Path -LiteralPath $csc)) {
198
+ Write-Host ' X in-box .NET Framework compiler (csc.exe) not found' -ForegroundColor Red
199
+ exit 1
200
+ }
201
+ New-Item -ItemType Directory -Force -Path (Split-Path $hostExe -Parent) | Out-Null
202
+ $cscArgs = @('/nologo', '/target:exe', "/out:$hostExe", '/reference:System.ServiceProcess.dll', $hostCs)
203
+ $cscOut = (& $csc $cscArgs 2>&1)
204
+ if (-not (Test-Path -LiteralPath $hostExe) -or ($cscOut -match 'error CS')) {
205
+ Write-Host ' X service host compilation failed:' -ForegroundColor Red
206
+ Write-Host (" " + ($cscOut -join "`n ")) -ForegroundColor Red
207
+ exit 1
208
+ }
209
+ Write-Ok "service host compiled: $hostExe"
210
+
211
+ # 2b. compile the interactive-session launcher so the Session-0 broker can
212
+ # create the Browser Worker in the active interactive user session.
213
+ $launcherCs = Join-Path $PSScriptRoot 'session-launcher.cs'
214
+ $launcherExe = Join-Path $MachineRoot 'launcher\XKWDStoreSessionLauncher.exe'
215
+ if (Test-Path -LiteralPath $launcherCs) {
216
+ $lOut = (& $csc @('/nologo', '/target:exe', "/out:$launcherExe", $launcherCs) 2>&1)
217
+ if (-not (Test-Path -LiteralPath $launcherExe) -or ($lOut -match 'error CS')) {
218
+ Write-Host ' X session launcher compilation failed:' -ForegroundColor Red
219
+ Write-Host (" " + ($lOut -join "`n ")) -ForegroundColor Red
220
+ exit 1
221
+ }
222
+ Write-Ok "session launcher compiled: $launcherExe"
223
+ } else {
224
+ Write-Warn2 "session-launcher.cs not found next to the installer; interactive worker launch may fail"
225
+ }
226
+
227
+ $cliJs = Join-Path $AgentInstallDir 'cli.js'
228
+ if (-not (Test-Path -LiteralPath $cliJs)) {
229
+ $cliJs = Join-Path (Split-Path $PSScriptRoot -Parent) 'src\cli.js'
230
+ Write-Warn2 "service host falling back to the repo CLI: $cliJs"
231
+ }
232
+ $agentNode = $node
233
+ $svcBin = '"' + $hostExe + '" -Node "' + $agentNode + '" -Cli "' + $cliJs + '" -Root "' + $MachineRoot + '" -Server "' + $Server + '"'
234
+
235
+ # 3. (re)create the service so no stale configuration survives. An in-place
236
+ # `sc config` can leave remnants; delete + wait + create is deterministic.
237
+ $svc = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
238
+ if ($svc) {
239
+ Write-Step "removing existing service $ServiceName (clean recreate)"
240
+ try { Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue } catch { }
241
+ (sc.exe delete $ServiceName) | Out-Null
242
+ $deadline = (Get-Date).AddSeconds(20)
243
+ while ((Get-Service -Name $ServiceName -ErrorAction SilentlyContinue) -and (Get-Date) -lt $deadline) { Start-Sleep -Milliseconds 500 }
244
+ if (Get-Service -Name $ServiceName -ErrorAction SilentlyContinue) { Write-Warn2 'existing service did not disappear within 20s' }
245
+ }
246
+ Write-Step "creating service $ServiceName (account=$ServiceAccount)"
247
+ if ($ServiceAccount -eq 'LocalSystem') {
248
+ New-Service -Name $ServiceName -BinaryPathName $svcBin -DisplayName $ServiceDisplay -StartupType Automatic | Out-Null
249
+ } else {
250
+ New-Service -Name $ServiceName -BinaryPathName $svcBin -DisplayName $ServiceDisplay -StartupType Automatic -Credential $ServiceAccount | Out-Null
251
+ }
252
+ # restart-on-crash with backoff + no interactive desktop
253
+ sc.exe failure $ServiceName reset= 86400 actions= restart/5000/restart/15000/restart/60000 | Out-Null
254
+ sc.exe description $ServiceName "Machine-wide XKWDStore broker: identity, server connection, leases; spawns interactive browser workers." | Out-Null
255
+ Write-Ok 'service configured (auto-start, restart-on-crash/backoff)'
256
+
257
+ # 3a. verify the SCM binary path no longer references the old cmd wrapper.
258
+ $finalPath = ((sc.exe qc $ServiceName 2>&1) | Where-Object { $_ -match 'BINARY_PATH_NAME' })
259
+ if ($finalPath -match 'cmd\.exe /c') {
260
+ Write-Host ' X service binary path still references the old cmd wrapper.' -ForegroundColor Red
261
+ exit 1
262
+ } else {
263
+ Write-Ok "service binary path verified (no cmd wrapper): $($finalPath -replace '\s+',' ')"
264
+ }
265
+ # 3b. remove a stale diagnostic wrapper if it exists (never used by the SCM now).
266
+ $staleCmd = Join-Path $MachineRoot 'launcher\broker-service.cmd'
267
+ if (Test-Path -LiteralPath $staleCmd) { Remove-Item $staleCmd -Force -ErrorAction SilentlyContinue }
268
+
269
+ # 4. per-session worker fallback (logon task) — only used if session spawning is unavailable
270
+ $taskName = 'XKWDStoreAgentWorker'
271
+ try {
272
+ $action = New-ScheduledTaskAction -Execute $node -Argument "`"$workerEntryDst`""
273
+ $trigger = New-ScheduledTaskTrigger -AtLogOn
274
+ $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -MultipleInstances IgnoreNew
275
+ Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Settings $settings -Description 'Per-interactive-session XKWDStore browser worker (broker-token gated).' -Force | Out-Null
276
+ Write-Ok "worker logon task registered: $taskName"
277
+ } catch {
278
+ Write-Warn2 "could not register the worker logon task (broker session-spawn will be used): $($_.Exception.Message)"
279
+ }
280
+
281
+ if (-not $NoStart -and -not $NoLaunch) {
282
+ Start-Service -Name $ServiceName
283
+ # Verify the broker is actually Running BEFORE retiring the legacy startup.
284
+ $deadline = (Get-Date).AddSeconds(30)
285
+ $running = $false
286
+ while ((Get-Date) -lt $deadline) {
287
+ $svcNow = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
288
+ if ($svcNow -and $svcNow.Status -eq 'Running') { $running = $true; break }
289
+ Start-Sleep -Milliseconds 500
290
+ }
291
+ if (-not $running) {
292
+ Write-Host ' X broker service did not reach Running; NOT retiring legacy startup (rollback preserved)' -ForegroundColor Red
293
+ exit 1
294
+ }
295
+ Write-Ok "service started and verified Running: $ServiceName"
296
+
297
+ # 4d. NOW retire the legacy per-user startup (fail-safe step 4-5): disable the
298
+ # backed-up launchers, then stop only PROVEN legacy Agent processes.
299
+ if (Test-Path -LiteralPath $legacyMod) {
300
+ try {
301
+ $ld = (& node $legacyMod disable --users-root "$env:SystemDrive\Users" --backup-dir $legacyBackupDir 2>&1 | Out-String)
302
+ Write-Ok "legacy per-user startup retired (Startup-folder entries removed; backups retained)"
303
+ } catch { Write-Warn2 "legacy startup retire step failed (non-fatal): $($_.Exception.Message)" }
304
+
305
+ # Stop only an EXACT legacy Agent process (npm package invocation or the
306
+ # legacy launcher BAT), never a generic node.exe.
307
+ try {
308
+ $legacyProcs = Get-CimInstance Win32_Process | Where-Object {
309
+ ($_.CommandLine -match '@xkwdstore[\\/]agent(@\d|\\|\s|")') -or ($_.CommandLine -match 'start-xkwdstore-agent\.bat')
310
+ } | Where-Object { $_.CommandLine -notmatch 'XKWDStore\\Agent\\cli\.js' }
311
+ foreach ($lp in $legacyProcs) {
312
+ Write-Warn2 ("stopping proven legacy Agent process pid=" + $lp.ProcessId)
313
+ try { Stop-Process -Id $lp.ProcessId -Force -ErrorAction SilentlyContinue } catch {}
314
+ }
315
+ } catch {}
316
+ }
317
+ } else {
318
+ Write-Warn2 'service not started (-NoStart/-NoLaunch); legacy startup NOT retired (rollback preserved)'
319
+ }
320
+
321
+ Write-Host ''
322
+ Write-Host " Machine-wide agent installed. Device identity: $MachineRoot\state\servers\..." -ForegroundColor Cyan
323
+ Write-Host ' No console window, no taskbar agent. Browser workers attach to the active desktop only.' -ForegroundColor DarkGray
324
+ Write-Host ''
325
+ exit 0
326
+ }
327
+
328
+ # ── uninstall ────────────────────────────────────────────────────────────────
329
+ Write-Host ''
330
+ Write-Host ' XKWDStore Agent 2.1.0 — uninstall' -ForegroundColor Cyan
331
+ Assert-Elevated
332
+ $svc = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
333
+ if ($svc) {
334
+ try { Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue } catch { }
335
+ sc.exe delete $ServiceName | Out-Null
336
+ Write-Ok "service removed: $ServiceName"
337
+ } else {
338
+ Write-Warn2 'service not present'
339
+ }
340
+ try { Unregister-ScheduledTask -TaskName 'XKWDStoreAgentWorker' -Confirm:$false -ErrorAction SilentlyContinue | Out-Null; Write-Ok 'worker logon task removed' } catch { }
341
+
342
+ # Profile data is PRESERVED by default. Only -PurgeData removes it, explicitly.
343
+ if ($PurgeData) {
344
+ Write-Warn2 "PURGE: deleting machine state (identity + profiles) at $MachineRoot"
345
+ Remove-Item -LiteralPath $MachineRoot -Recurse -Force -ErrorAction SilentlyContinue
346
+ Write-Ok 'machine state deleted'
347
+ } else {
348
+ Write-Ok "profile + identity PRESERVED at $MachineRoot (use -PurgeData to delete)"
349
+ }
350
+ Write-Host ''
351
+ exit 0