@xkwdstore/agent 2.0.7 → 2.1.0
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.
- package/README.md +37 -11
- package/package.json +11 -2
- package/scripts/install-machine-agent.ps1 +351 -0
- package/scripts/worker-entry.js +53 -0
- package/src/brokerWorkerBridge.js +352 -0
- package/src/browserIsolation.js +691 -0
- package/src/cli.js +490 -123
- package/src/deviceKeyStore.js +446 -71
- package/src/legacyStartup.js +195 -0
- package/src/machineLock.js +202 -0
- package/src/machineState.js +354 -0
- package/src/processLock.js +15 -2
- package/src/proxyEgress.js +28 -4
- package/src/sessionHandler.js +560 -33
- package/src/sessionRegistry.js +280 -0
- package/src/worker.js +253 -0
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ Terminal-only, cryptographically authenticated CLI for XKWDStore browser automat
|
|
|
6
6
|
|
|
7
7
|
> **@xkwdstore/agent 2.0.3 is the last version published on npm.**
|
|
8
8
|
>
|
|
9
|
-
> The current source version is **2.0
|
|
9
|
+
> The current source version is **2.1.0** (machine-wide hardening). It is
|
|
10
10
|
> NOT claimed to be published unless the release workflow has published it — see
|
|
11
11
|
> `reports/` for the authoritative publication state.
|
|
12
12
|
|
|
@@ -29,7 +29,7 @@ curl -L -o "%TEMP%\xkwdstore-install.ps1" https://raw.githubusercontent.com/Essa
|
|
|
29
29
|
The generated launcher runs the pinned command:
|
|
30
30
|
|
|
31
31
|
```powershell
|
|
32
|
-
npx --yes @xkwdstore/agent@2.0
|
|
32
|
+
npx --yes @xkwdstore/agent@2.1.0 start
|
|
33
33
|
```
|
|
34
34
|
|
|
35
35
|
Automated installer tests use `-NoLaunch` or a mocked `npx` command so the
|
|
@@ -102,21 +102,47 @@ No browser approval is needed unless:
|
|
|
102
102
|
Press **Ctrl+C** in the terminal. The agent closes all browser sessions and
|
|
103
103
|
disconnects cleanly. No background process remains.
|
|
104
104
|
|
|
105
|
+
## Machine-wide broker + interactive worker (2.1.0)
|
|
106
|
+
|
|
107
|
+
The agent can run as a **machine-wide broker** (`xkwd-agent service`, hosted by a
|
|
108
|
+
Windows Service) plus a per-session **interactive browser worker**:
|
|
109
|
+
|
|
110
|
+
- the **broker** owns the machine identity, the device private key, the server
|
|
111
|
+
WebSocket, leases, and the session registry — and never launches a browser;
|
|
112
|
+
- the **worker** runs in the active interactive Windows session, launches
|
|
113
|
+
Chromium, and accepts only typed browser commands over a loopback-only channel
|
|
114
|
+
with a one-time token. It cannot read the private key or enroll the device.
|
|
115
|
+
|
|
116
|
+
One broker per machine is enforced by a Windows named mutex
|
|
117
|
+
(`Global\XKWDStoreAgentMachineBroker-v1`). Silent startup is installed by
|
|
118
|
+
`scripts/install-machine-agent.ps1` (elevated). See
|
|
119
|
+
[`docs/MACHINE-AGENT-2.1.0.md`](../../docs/MACHINE-AGENT-2.1.0.md).
|
|
120
|
+
|
|
105
121
|
## Data Storage
|
|
106
122
|
|
|
107
|
-
The agent stores runtime data in
|
|
108
|
-
|
|
123
|
+
The agent stores runtime data in a **machine-wide** directory, so one physical
|
|
124
|
+
computer keeps one device identity across Windows users and reboots:
|
|
109
125
|
|
|
110
126
|
| Platform | Location |
|
|
111
127
|
|----------|----------|
|
|
112
|
-
| Windows | `%
|
|
113
|
-
| Linux | `${XDG_DATA_HOME:-~/.local/share}/xkwdstore/` |
|
|
128
|
+
| Windows | `%ProgramData%\XKWDStore\Agent\` (config, identity, credentials, logs, runtime, state, launcher) |
|
|
129
|
+
| Linux | `${XDG_DATA_HOME:-~/.local/share}/xkwdstore/` (dev/CI; overridable) |
|
|
114
130
|
|
|
115
131
|
This directory contains:
|
|
116
|
-
- Chrome profiles (persistent cookies and browser storage)
|
|
132
|
+
- Chrome profiles (persistent cookies and browser storage), namespaced by
|
|
133
|
+
`serverUuid/tenantUuid/accountUuid/deviceUuid` under `state\profiles\`
|
|
117
134
|
- Bounded logs (no cookies, tokens, private keys, or secrets)
|
|
118
135
|
- Non-secret device metadata (deviceId, publicKey, fingerprint)
|
|
119
|
-
-
|
|
136
|
+
- Per-session runtime dirs (temp/downloads/crash/ipc) under `state\sessions\`
|
|
137
|
+
- An Agent-local session registry (non-secret metadata only) in `runtime\`
|
|
138
|
+
|
|
139
|
+
Sensitive files are ACL-restricted to the owning user, Administrators, and
|
|
140
|
+
SYSTEM. Credentials are DPAPI-protected; they are not world-readable.
|
|
141
|
+
|
|
142
|
+
**Migration:** a pre-2.1.0 per-user install (`%LOCALAPPDATA%\XKWDStore\`) is
|
|
143
|
+
adopted **once**, by copy — the existing `deviceId` and pairing are preserved
|
|
144
|
+
exactly, and the old tree is left intact for rollback. See
|
|
145
|
+
[`docs/MACHINE-AGENT-2.1.0.md`](../../docs/MACHINE-AGENT-2.1.0.md).
|
|
120
146
|
|
|
121
147
|
**Nothing is written to Desktop, Documents, Downloads, or OneDrive.**
|
|
122
148
|
|
|
@@ -177,11 +203,11 @@ The agent does NOT update itself. To use a newer version, change the version
|
|
|
177
203
|
number in the command. The pinned command for this release is:
|
|
178
204
|
|
|
179
205
|
```powershell
|
|
180
|
-
npx --yes @xkwdstore/agent@2.0
|
|
206
|
+
npx --yes @xkwdstore/agent@2.1.0 start
|
|
181
207
|
```
|
|
182
208
|
|
|
183
|
-
> 2.0
|
|
184
|
-
> 2.0.3 was the
|
|
209
|
+
> 2.1.0 is the current local agent version (machine-wide hardening).
|
|
210
|
+
> 2.0.3 was the last published release.
|
|
185
211
|
>
|
|
186
212
|
> The server checks compatibility at startup and displays a clear message if
|
|
187
213
|
> the agent version is no longer supported.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xkwdstore/agent",
|
|
3
|
-
"version": "2.0
|
|
4
|
-
"description": "XKWDStore Agent —
|
|
3
|
+
"version": "2.1.0",
|
|
4
|
+
"description": "XKWDStore Agent — machine-wide, cryptographically authenticated CLI for isolated browser automation",
|
|
5
5
|
"main": "src/cli.js",
|
|
6
6
|
"bin": {
|
|
7
7
|
"xkwd-agent": "src/cli.js"
|
|
@@ -18,12 +18,19 @@
|
|
|
18
18
|
"files": [
|
|
19
19
|
"src/cli.js",
|
|
20
20
|
"src/deviceKeyStore.js",
|
|
21
|
+
"src/machineState.js",
|
|
22
|
+
"src/machineLock.js",
|
|
23
|
+
"src/legacyStartup.js",
|
|
24
|
+
"src/brokerWorkerBridge.js",
|
|
25
|
+
"src/worker.js",
|
|
21
26
|
"src/chromeDetector.js",
|
|
22
27
|
"src/enrollmentClient.js",
|
|
23
28
|
"src/processLock.js",
|
|
24
29
|
"src/wsClient.js",
|
|
25
30
|
"src/challengeCodec.js",
|
|
26
31
|
"src/sessionHandler.js",
|
|
32
|
+
"src/sessionRegistry.js",
|
|
33
|
+
"src/browserIsolation.js",
|
|
27
34
|
"src/fingerprint.js",
|
|
28
35
|
"src/fingerprintStore.js",
|
|
29
36
|
"src/profilePath.js",
|
|
@@ -34,6 +41,8 @@
|
|
|
34
41
|
"src/configStore.js",
|
|
35
42
|
"src/secretStore.js",
|
|
36
43
|
"src/actions/",
|
|
44
|
+
"scripts/worker-entry.js",
|
|
45
|
+
"scripts/install-machine-agent.ps1",
|
|
37
46
|
"README.md",
|
|
38
47
|
"LICENSE"
|
|
39
48
|
],
|
|
@@ -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.0',
|
|
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
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Per-interactive-session worker launcher (TW-manager Agent 2.1.0).
|
|
5
|
+
*
|
|
6
|
+
* A Scheduled Task (AtLogOn, per user) runs this tiny helper. It does NOT carry
|
|
7
|
+
* any credential and cannot enroll. Its ONLY job is to ask the machine broker
|
|
8
|
+
* (over the local machine-state directory) for a one-time channel token, then
|
|
9
|
+
* start `worker.js` attached to THAT active desktop session.
|
|
10
|
+
*
|
|
11
|
+
* The broker writes a short-lived "worker invitation" file into
|
|
12
|
+
* `<machineRoot>\runtime\worker-invite.json` containing { port, token, expiresAt }.
|
|
13
|
+
* The invitation is:
|
|
14
|
+
* - written with 0o600 / restrictive ACL,
|
|
15
|
+
* - single-use (the broker regenerates the token per worker),
|
|
16
|
+
* - short-lived (expires in 60s),
|
|
17
|
+
* - worthless without the loopback channel (no network exposure).
|
|
18
|
+
*
|
|
19
|
+
* If the invitation is absent/expired (broker not up yet), the helper exits
|
|
20
|
+
* quietly; the broker will spawn a worker itself when it needs one.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const fs = require('fs');
|
|
24
|
+
const os = require('os');
|
|
25
|
+
const path = require('path');
|
|
26
|
+
const { spawn } = require('child_process');
|
|
27
|
+
|
|
28
|
+
function main() {
|
|
29
|
+
let machineState;
|
|
30
|
+
try { machineState = require('../machineState'); } catch { process.exit(0); }
|
|
31
|
+
|
|
32
|
+
const invitePath = path.join(machineState.paths.runtime, 'worker-invite.json');
|
|
33
|
+
let invite = null;
|
|
34
|
+
try { invite = JSON.parse(fs.readFileSync(invitePath, 'utf8')); } catch { invite = null; }
|
|
35
|
+
if (!invite || !invite.port || !invite.token) {
|
|
36
|
+
// No broker invitation (broker not running yet). Nothing to do.
|
|
37
|
+
process.exit(0);
|
|
38
|
+
}
|
|
39
|
+
if (invite.expiresAt && Date.parse(invite.expiresAt) < Date.now()) {
|
|
40
|
+
try { fs.unlinkSync(invitePath); } catch { }
|
|
41
|
+
process.exit(0);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const workerScript = path.join(__dirname, '..', 'src', 'worker.js');
|
|
45
|
+
const child = spawn(process.execPath, [workerScript, '--port', String(invite.port), '--token', String(invite.token)], {
|
|
46
|
+
stdio: 'ignore',
|
|
47
|
+
windowsHide: true,
|
|
48
|
+
});
|
|
49
|
+
child.unref();
|
|
50
|
+
process.exit(0);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
main();
|