@xkwdstore/agent 2.1.0 → 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.
package/README.md CHANGED
@@ -1,279 +1,279 @@
1
- # @xkwdstore/agent
2
-
3
- Terminal-only, cryptographically authenticated CLI for XKWDStore browser automation.
4
-
5
- ## Installation
6
-
7
- > **@xkwdstore/agent 2.0.3 is the last version published on npm.**
8
- >
9
- > The current source version is **2.1.0** (machine-wide hardening). It is
10
- > NOT claimed to be published unless the release workflow has published it — see
11
- > `reports/` for the authoritative publication state.
12
-
13
- End users install by downloading the installer file first, then running it
14
- (the installer explicitly forbids piping a remote script directly into
15
- execution). This creates a desktop launcher pinned to this version:
16
-
17
- ```powershell
18
- $installer = "$env:TEMP\xkwdstore-install.ps1"
19
- Invoke-WebRequest -Uri "https://raw.githubusercontent.com/EssaGhazwani/TW-manager-install/main/install.ps1" -OutFile $installer
20
- powershell.exe -NoProfile -ExecutionPolicy Bypass -File $installer
21
- ```
22
-
23
- Or, from CMD:
24
-
25
- ```cmd
26
- curl -L -o "%TEMP%\xkwdstore-install.ps1" https://raw.githubusercontent.com/EssaGhazwani/TW-manager-install/main/install.ps1 && powershell -NoProfile -ExecutionPolicy Bypass -File "%TEMP%\xkwdstore-install.ps1"
27
- ```
28
-
29
- The generated launcher runs the pinned command:
30
-
31
- ```powershell
32
- npx --yes @xkwdstore/agent@2.1.0 start
33
- ```
34
-
35
- Automated installer tests use `-NoLaunch` or a mocked `npx` command so the
36
- real pinned package is never executed from the public registry during
37
- installation validation.
38
-
39
- ## Platform Support
40
-
41
- | Platform | Status |
42
- |----------|--------|
43
- | **Windows** | Implementation present. ACL hardening awaits real Windows runner CI. |
44
- | **Linux (with Secret Service / libsecret)** | Implementation present. Pending platform verification on CI. |
45
- | **macOS** | **Unsupported.** Fails closed with an explicit error. No macOS Keychain integration is implemented. |
46
-
47
- ## Requirements
48
-
49
- - **Node.js 22 or later** — check with `node --version`
50
- - **Google Chrome** installed on your computer
51
- - A terminal (PowerShell, Windows Terminal, or Linux shell)
52
- - **Linux**: `gnome-keyring` or `seahorse` (provides `libsecret` / `secret-tool`)
53
-
54
- ## First Run
55
-
56
- On first run, the agent will:
57
-
58
- 1. Generate an Ed25519 key pair locally on your computer.
59
- 2. Open your browser to x.kwdstore.com for authorization.
60
- 3. Wait for you to sign in and approve the computer.
61
- 4. Connect securely after approval.
62
-
63
- **No pairing code. No email prompt. No API key. No download. No installer.**
64
-
65
- The private key is stored using your operating system's secure credential storage:
66
- - **Windows**: DPAPI (current-user scope) — pending ACL hardening CI verification
67
- - **Linux**: Secret Service / libsecret
68
- - **macOS**: Not supported — fails with an explicit error
69
-
70
- The private key **never leaves your computer**, never appears in logs, and never
71
- appears in command-line arguments.
72
-
73
- ## Subsequent Runs
74
-
75
- After first authorization, the agent connects automatically.
76
-
77
- No browser approval is needed unless:
78
- - The device key was deleted
79
- - The device was revoked from the dashboard
80
- - Secure storage was reset
81
- - The server no longer recognizes the public key
82
-
83
- ## Commands
84
-
85
- | Command | Description |
86
- |---------|-------------|
87
- | `start` | Start the agent (connect, run browser sessions) |
88
- | `status` | Show device and connection status |
89
- | `logout` | Delete local device identity (requires re-authorization) |
90
- | `revoke-local` | Delete local device identity and credentials |
91
- | `doctor` | Run diagnostic checks |
92
- | `version` | Print version information |
93
- | `help` | Show help |
94
-
95
- ### Options
96
-
97
- - `--server=<url>` — Server URL (default: `https://x.kwdstore.com`)
98
- - `--replace` — Replace a running instance (safe takeover)
99
-
100
- ## Stopping the Agent
101
-
102
- Press **Ctrl+C** in the terminal. The agent closes all browser sessions and
103
- disconnects cleanly. No background process remains.
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
-
121
- ## Data Storage
122
-
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:
125
-
126
- | Platform | Location |
127
- |----------|----------|
128
- | Windows | `%ProgramData%\XKWDStore\Agent\` (config, identity, credentials, logs, runtime, state, launcher) |
129
- | Linux | `${XDG_DATA_HOME:-~/.local/share}/xkwdstore/` (dev/CI; overridable) |
130
-
131
- This directory contains:
132
- - Chrome profiles (persistent cookies and browser storage), namespaced by
133
- `serverUuid/tenantUuid/accountUuid/deviceUuid` under `state\profiles\`
134
- - Bounded logs (no cookies, tokens, private keys, or secrets)
135
- - Non-secret device metadata (deviceId, publicKey, fingerprint)
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).
146
-
147
- **Nothing is written to Desktop, Documents, Downloads, or OneDrive.**
148
-
149
- ## Security
150
-
151
- ### Device Identity
152
-
153
- The device identity is an **Ed25519 key pair** generated locally. The server
154
- authenticates the computer by verifying signatures made by the private key.
155
- Hardware attributes (hostname, OS, architecture) are collected for display and
156
- anomaly detection only — they are **not** authentication credentials.
157
-
158
- ### WebSocket Authentication
159
-
160
- Every WebSocket connection uses **Ed25519 challenge-response**:
161
- 1. Server sends a challenge with a random nonce.
162
- 2. Client signs the challenge with its private key.
163
- 3. Server verifies the signature against the registered public key.
164
-
165
- No HTTP credential exchange. No in-memory ticket. No bearer token in the URL.
166
-
167
- ### Revocation
168
-
169
- A device can be revoked from the dashboard. Revocation immediately prevents all
170
- future challenge-response authentication. Active connections are closed when
171
- the server processes the revocation event — this requires the
172
- `protocolV2Revocation` integration test to pass.
173
-
174
- ### Windows Private Key Storage
175
-
176
- 1. Key is DPAPI-protected through stdin.
177
- 2. Encrypted envelope is written to disk.
178
- 3. A restricted DACL is applied via PowerShell.
179
- 4. ACL application is verified (not best-effort): the write **fails** if the
180
- ACL cannot be applied or verified.
181
-
182
- **Status**: Implementation present. ACL fail-closed tests require a real
183
- Windows runner (pending CI billing restoration).
184
-
185
- ## What This Agent Does NOT Do
186
-
187
- - ❌ Download or install a browser (uses your system Chrome)
188
- - ❌ Run a self-updater (you pin the version in the command)
189
- - ❌ Poll GitHub for manifests
190
- - ❌ Require a pairing code
191
- - ❌ Require an email in the terminal
192
- - ❌ Keep a tray application running
193
- - ❌ Install a Windows service
194
- - ❌ Create a Scheduled Task
195
- - ❌ Write to Desktop, Documents, Downloads, or OneDrive
196
- - ❌ Store private keys in plaintext
197
- - ❌ Use `curl | sh` or `Invoke-WebRequest | Invoke-Expression`
198
- - ❌ Support macOS (fails closed)
199
-
200
- ## Version Management
201
-
202
- The agent does NOT update itself. To use a newer version, change the version
203
- number in the command. The pinned command for this release is:
204
-
205
- ```powershell
206
- npx --yes @xkwdstore/agent@2.1.0 start
207
- ```
208
-
209
- > 2.1.0 is the current local agent version (machine-wide hardening).
210
- > 2.0.3 was the last published release.
211
- >
212
- > The server checks compatibility at startup and displays a clear message if
213
- > the agent version is no longer supported.
214
-
215
- ## Privacy
216
-
217
- The agent collects and sends the following non-secret information to the server:
218
- - Hostname (for display)
219
- - Operating system and version
220
- - CPU architecture
221
- - Current OS username
222
- - Chrome version
223
- - A locally-salted hash of machine identifiers (for anomaly detection, not
224
- authentication)
225
-
226
- The agent does **not** send:
227
- - Raw motherboard serial numbers
228
- - Raw disk serial numbers
229
- - Raw machine GUIDs
230
- - Private keys
231
- - Cookies or browser storage
232
- - Passwords or tokens
233
-
234
- ## Troubleshooting
235
-
236
- Run `xkwd-agent doctor` to check:
237
- - Node.js version
238
- - Chrome installation
239
- - Secure storage availability
240
- - Data directory
241
- - Device enrollment status
242
- - Server connectivity
243
-
244
- ### Chrome Not Found
245
-
246
- ```
247
- Google Chrome was not found.
248
- Install Chrome and run the command again.
249
- No browser was downloaded or installed automatically.
250
- ```
251
-
252
- Install Google Chrome from https://www.google.com/chrome/ and run the command again.
253
-
254
- ### Secure Storage Unavailable (Linux)
255
-
256
- ```
257
- Secure key storage is unavailable on this system.
258
- ```
259
-
260
- Install `gnome-keyring` or `seahorse` (provides `libsecret` / `secret-tool`).
261
-
262
- ### macOS Not Supported
263
-
264
- ```
265
- macOS is not supported. The agent fails closed on macOS.
266
- ```
267
-
268
- The agent does not implement macOS Keychain integration. Use a Linux or Windows computer.
269
-
270
- ### Already Running
271
-
272
- ```
273
- XKWDStore Agent is already running on this computer.
274
- PID: ...
275
- Started: ...
276
- Device: ...
277
- ```
278
-
1
+ # @xkwdstore/agent
2
+
3
+ Terminal-only, cryptographically authenticated CLI for XKWDStore browser automation.
4
+
5
+ ## Installation
6
+
7
+ > **@xkwdstore/agent 2.1.1 is the last version published on npm.**
8
+ >
9
+ > The current source version is **2.1.1** (machine-wide hardening). It is
10
+ > NOT claimed to be published unless the release workflow has published it — see
11
+ > `reports/` for the authoritative publication state.
12
+
13
+ End users install by downloading the installer file first, then running it
14
+ (the installer explicitly forbids piping a remote script directly into
15
+ execution). This creates a desktop launcher pinned to this version:
16
+
17
+ ```powershell
18
+ $installer = "$env:TEMP\xkwdstore-install.ps1"
19
+ Invoke-WebRequest -Uri "https://raw.githubusercontent.com/EssaGhazwani/TW-manager-install/main/install.ps1" -OutFile $installer
20
+ powershell.exe -NoProfile -ExecutionPolicy Bypass -File $installer
21
+ ```
22
+
23
+ Or, from CMD:
24
+
25
+ ```cmd
26
+ curl -L -o "%TEMP%\xkwdstore-install.ps1" https://raw.githubusercontent.com/EssaGhazwani/TW-manager-install/main/install.ps1 && powershell -NoProfile -ExecutionPolicy Bypass -File "%TEMP%\xkwdstore-install.ps1"
27
+ ```
28
+
29
+ The generated launcher runs the pinned command:
30
+
31
+ ```powershell
32
+ npx --yes @xkwdstore/agent@2.1.1 start
33
+ ```
34
+
35
+ Automated installer tests use `-NoLaunch` or a mocked `npx` command so the
36
+ real pinned package is never executed from the public registry during
37
+ installation validation.
38
+
39
+ ## Platform Support
40
+
41
+ | Platform | Status |
42
+ |----------|--------|
43
+ | **Windows** | Implementation present. ACL hardening awaits real Windows runner CI. |
44
+ | **Linux (with Secret Service / libsecret)** | Implementation present. Pending platform verification on CI. |
45
+ | **macOS** | **Unsupported.** Fails closed with an explicit error. No macOS Keychain integration is implemented. |
46
+
47
+ ## Requirements
48
+
49
+ - **Node.js 22 or later** — check with `node --version`
50
+ - **Google Chrome** installed on your computer
51
+ - A terminal (PowerShell, Windows Terminal, or Linux shell)
52
+ - **Linux**: `gnome-keyring` or `seahorse` (provides `libsecret` / `secret-tool`)
53
+
54
+ ## First Run
55
+
56
+ On first run, the agent will:
57
+
58
+ 1. Generate an Ed25519 key pair locally on your computer.
59
+ 2. Open your browser to x.kwdstore.com for authorization.
60
+ 3. Wait for you to sign in and approve the computer.
61
+ 4. Connect securely after approval.
62
+
63
+ **No pairing code. No email prompt. No API key. No download. No installer.**
64
+
65
+ The private key is stored using your operating system's secure credential storage:
66
+ - **Windows**: DPAPI (current-user scope) — pending ACL hardening CI verification
67
+ - **Linux**: Secret Service / libsecret
68
+ - **macOS**: Not supported — fails with an explicit error
69
+
70
+ The private key **never leaves your computer**, never appears in logs, and never
71
+ appears in command-line arguments.
72
+
73
+ ## Subsequent Runs
74
+
75
+ After first authorization, the agent connects automatically.
76
+
77
+ No browser approval is needed unless:
78
+ - The device key was deleted
79
+ - The device was revoked from the dashboard
80
+ - Secure storage was reset
81
+ - The server no longer recognizes the public key
82
+
83
+ ## Commands
84
+
85
+ | Command | Description |
86
+ |---------|-------------|
87
+ | `start` | Start the agent (connect, run browser sessions) |
88
+ | `status` | Show device and connection status |
89
+ | `logout` | Delete local device identity (requires re-authorization) |
90
+ | `revoke-local` | Delete local device identity and credentials |
91
+ | `doctor` | Run diagnostic checks |
92
+ | `version` | Print version information |
93
+ | `help` | Show help |
94
+
95
+ ### Options
96
+
97
+ - `--server=<url>` — Server URL (default: `https://x.kwdstore.com`)
98
+ - `--replace` — Replace a running instance (safe takeover)
99
+
100
+ ## Stopping the Agent
101
+
102
+ Press **Ctrl+C** in the terminal. The agent closes all browser sessions and
103
+ disconnects cleanly. No background process remains.
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
+
121
+ ## Data Storage
122
+
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:
125
+
126
+ | Platform | Location |
127
+ |----------|----------|
128
+ | Windows | `%ProgramData%\XKWDStore\Agent\` (config, identity, credentials, logs, runtime, state, launcher) |
129
+ | Linux | `${XDG_DATA_HOME:-~/.local/share}/xkwdstore/` (dev/CI; overridable) |
130
+
131
+ This directory contains:
132
+ - Chrome profiles (persistent cookies and browser storage), namespaced by
133
+ `serverUuid/tenantUuid/accountUuid/deviceUuid` under `state\profiles\`
134
+ - Bounded logs (no cookies, tokens, private keys, or secrets)
135
+ - Non-secret device metadata (deviceId, publicKey, fingerprint)
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).
146
+
147
+ **Nothing is written to Desktop, Documents, Downloads, or OneDrive.**
148
+
149
+ ## Security
150
+
151
+ ### Device Identity
152
+
153
+ The device identity is an **Ed25519 key pair** generated locally. The server
154
+ authenticates the computer by verifying signatures made by the private key.
155
+ Hardware attributes (hostname, OS, architecture) are collected for display and
156
+ anomaly detection only — they are **not** authentication credentials.
157
+
158
+ ### WebSocket Authentication
159
+
160
+ Every WebSocket connection uses **Ed25519 challenge-response**:
161
+ 1. Server sends a challenge with a random nonce.
162
+ 2. Client signs the challenge with its private key.
163
+ 3. Server verifies the signature against the registered public key.
164
+
165
+ No HTTP credential exchange. No in-memory ticket. No bearer token in the URL.
166
+
167
+ ### Revocation
168
+
169
+ A device can be revoked from the dashboard. Revocation immediately prevents all
170
+ future challenge-response authentication. Active connections are closed when
171
+ the server processes the revocation event — this requires the
172
+ `protocolV2Revocation` integration test to pass.
173
+
174
+ ### Windows Private Key Storage
175
+
176
+ 1. Key is DPAPI-protected through stdin.
177
+ 2. Encrypted envelope is written to disk.
178
+ 3. A restricted DACL is applied via PowerShell.
179
+ 4. ACL application is verified (not best-effort): the write **fails** if the
180
+ ACL cannot be applied or verified.
181
+
182
+ **Status**: Implementation present. ACL fail-closed tests require a real
183
+ Windows runner (pending CI billing restoration).
184
+
185
+ ## What This Agent Does NOT Do
186
+
187
+ - ❌ Download or install a browser (uses your system Chrome)
188
+ - ❌ Run a self-updater (you pin the version in the command)
189
+ - ❌ Poll GitHub for manifests
190
+ - ❌ Require a pairing code
191
+ - ❌ Require an email in the terminal
192
+ - ❌ Keep a tray application running
193
+ - ❌ Install a Windows service
194
+ - ❌ Create a Scheduled Task
195
+ - ❌ Write to Desktop, Documents, Downloads, or OneDrive
196
+ - ❌ Store private keys in plaintext
197
+ - ❌ Use `curl | sh` or `Invoke-WebRequest | Invoke-Expression`
198
+ - ❌ Support macOS (fails closed)
199
+
200
+ ## Version Management
201
+
202
+ The agent does NOT update itself. To use a newer version, change the version
203
+ number in the command. The pinned command for this release is:
204
+
205
+ ```powershell
206
+ npx --yes @xkwdstore/agent@2.1.1 start
207
+ ```
208
+
209
+ > 2.1.0 is the current local agent version (machine-wide hardening).
210
+ > 2.0.3 was the last published release.
211
+ >
212
+ > The server checks compatibility at startup and displays a clear message if
213
+ > the agent version is no longer supported.
214
+
215
+ ## Privacy
216
+
217
+ The agent collects and sends the following non-secret information to the server:
218
+ - Hostname (for display)
219
+ - Operating system and version
220
+ - CPU architecture
221
+ - Current OS username
222
+ - Chrome version
223
+ - A locally-salted hash of machine identifiers (for anomaly detection, not
224
+ authentication)
225
+
226
+ The agent does **not** send:
227
+ - Raw motherboard serial numbers
228
+ - Raw disk serial numbers
229
+ - Raw machine GUIDs
230
+ - Private keys
231
+ - Cookies or browser storage
232
+ - Passwords or tokens
233
+
234
+ ## Troubleshooting
235
+
236
+ Run `xkwd-agent doctor` to check:
237
+ - Node.js version
238
+ - Chrome installation
239
+ - Secure storage availability
240
+ - Data directory
241
+ - Device enrollment status
242
+ - Server connectivity
243
+
244
+ ### Chrome Not Found
245
+
246
+ ```
247
+ Google Chrome was not found.
248
+ Install Chrome and run the command again.
249
+ No browser was downloaded or installed automatically.
250
+ ```
251
+
252
+ Install Google Chrome from https://www.google.com/chrome/ and run the command again.
253
+
254
+ ### Secure Storage Unavailable (Linux)
255
+
256
+ ```
257
+ Secure key storage is unavailable on this system.
258
+ ```
259
+
260
+ Install `gnome-keyring` or `seahorse` (provides `libsecret` / `secret-tool`).
261
+
262
+ ### macOS Not Supported
263
+
264
+ ```
265
+ macOS is not supported. The agent fails closed on macOS.
266
+ ```
267
+
268
+ The agent does not implement macOS Keychain integration. Use a Linux or Windows computer.
269
+
270
+ ### Already Running
271
+
272
+ ```
273
+ XKWDStore Agent is already running on this computer.
274
+ PID: ...
275
+ Started: ...
276
+ Device: ...
277
+ ```
278
+
279
279
  Use `xkwd-agent start --replace` to safely replace the running instance.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xkwdstore/agent",
3
- "version": "2.1.0",
3
+ "version": "2.1.1",
4
4
  "description": "XKWDStore Agent — machine-wide, cryptographically authenticated CLI for isolated browser automation",
5
5
  "main": "src/cli.js",
6
6
  "bin": {
@@ -43,6 +43,8 @@
43
43
  "src/actions/",
44
44
  "scripts/worker-entry.js",
45
45
  "scripts/install-machine-agent.ps1",
46
+ "scripts/broker-service-host.cs",
47
+ "scripts/session-launcher.cs",
46
48
  "README.md",
47
49
  "LICENSE"
48
50
  ],
@@ -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
+ }
@@ -35,7 +35,7 @@
35
35
  # -NoLaunch (test) validate + write files, never start a process
36
36
 
37
37
  param(
38
- [string]$AgentVersion = '2.1.0',
38
+ [string]$AgentVersion = '2.1.1',
39
39
  [string]$Server = 'https://x.kwdstore.com',
40
40
  [string]$ServiceAccount = 'LocalSystem',
41
41
  [string]$AgentRoot,
@@ -0,0 +1,163 @@
1
+ // XKWDStore Agent 2.1.0 — interactive-session process launcher.
2
+ //
3
+ // WHY THIS EXISTS
4
+ // ---------------
5
+ // The machine broker runs as a Windows SERVICE in Session 0. Session 0 has no
6
+ // interactive desktop, so a Chromium window launched from the broker would be
7
+ // invisible/non-functional. The broker must launch its Browser Worker into the
8
+ // ACTIVE INTERACTIVE USER SESSION.
9
+ //
10
+ // This helper, run by the broker (LocalSystem), launches a process in the active
11
+ // console session using CreateProcessAsUser with the session's user token:
12
+ //
13
+ // WTSGetActiveConsoleSessionId -> WTSQueryUserToken ->
14
+ // DuplicateTokenEx -> CreateEnvironmentBlock -> CreateProcessAsUser
15
+ //
16
+ // It requires SeTcbPrivilege (LocalSystem has it). It launches EXACTLY the
17
+ // command it is given (node + worker.js + invite), never a shell, and passes no
18
+ // secret. The worker then authenticates to the broker over the loopback channel.
19
+ //
20
+ // The launched child inherits the USER's desktop (session), so Chromium appears
21
+ // on that user's screen.
22
+
23
+ using System;
24
+ using System.ComponentModel;
25
+ using System.Diagnostics;
26
+ using System.Runtime.InteropServices;
27
+
28
+ internal static class SessionLauncher
29
+ {
30
+ [DllImport("kernel32.dll")]
31
+ private static extern uint WTSGetActiveConsoleSessionId();
32
+
33
+ [DllImport("wtsapi32.dll", SetLastError = true)]
34
+ private static extern bool WTSQueryUserToken(uint sessionId, out IntPtr token);
35
+
36
+ [DllImport("advapi32.dll", SetLastError = true)]
37
+ private static extern bool DuplicateTokenEx(IntPtr existing, uint desiredAccess, IntPtr attrs,
38
+ int impersonationLevel, int tokenType, out IntPtr newToken);
39
+
40
+ [DllImport("userenv.dll", SetLastError = true)]
41
+ private static extern bool CreateEnvironmentBlock(out IntPtr env, IntPtr token, bool inherit);
42
+
43
+ [DllImport("userenv.dll", SetLastError = true)]
44
+ private static extern bool DestroyEnvironmentBlock(IntPtr env);
45
+
46
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
47
+ private static extern bool CreateProcessAsUser(IntPtr token, string app, string cmdLine,
48
+ IntPtr procAttrs, IntPtr threadAttrs, bool inherit, uint flags, IntPtr env, string cwd,
49
+ ref STARTUPINFO si, out PROCESS_INFORMATION pi);
50
+
51
+ [DllImport("kernel32.dll", SetLastError = true)]
52
+ private static extern bool CloseHandle(IntPtr h);
53
+
54
+ [StructLayout(LayoutKind.Sequential)]
55
+ private struct SECURITY_ATTRIBUTES { public int nLength; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; }
56
+
57
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
58
+ private static extern IntPtr CreateFile(string name, uint access, uint share, ref SECURITY_ATTRIBUTES sa,
59
+ uint creation, uint flags, IntPtr template);
60
+
61
+ private const uint GENERIC_WRITE = 0x40000000;
62
+ private const uint FILE_SHARE_WRITE = 0x00000002;
63
+ private const uint FILE_SHARE_READ = 0x00000001;
64
+ private const uint CREATE_ALWAYS = 2;
65
+ private const uint FILE_ATTRIBUTE_NORMAL = 0x80;
66
+ private const int STARTF_USESTDHANDLES = 0x00000100;
67
+
68
+ private const uint TOKEN_ALL_ACCESS = 0xF01FF;
69
+ private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;
70
+
71
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
72
+ private struct STARTUPINFO
73
+ {
74
+ public int cb;
75
+ public string lpReserved;
76
+ public string lpDesktop;
77
+ public string lpTitle;
78
+ public int dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags;
79
+ public short wShowWindow, cbReserved2;
80
+ public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError;
81
+ }
82
+
83
+ [StructLayout(LayoutKind.Sequential)]
84
+ private struct PROCESS_INFORMATION
85
+ {
86
+ public IntPtr hProcess, hThread;
87
+ public int dwProcessId, dwThreadId;
88
+ }
89
+
90
+ public static int Main(string[] args)
91
+ {
92
+ // Args: -Exe <node.exe> -Args "<worker args>" [-Cwd <dir>] [-Out <file>] [-Err <file>]
93
+ // -Query -> print the ACTIVE CONSOLE session id and exit (broker session check)
94
+ string exe = null, argLine = null, cwd = null, outFile = null, errFile = null;
95
+ bool query = false;
96
+ for (int i = 0; i < args.Length; i++)
97
+ {
98
+ switch (args[i])
99
+ {
100
+ case "-Exe": if (i + 1 < args.Length) exe = args[++i]; break;
101
+ case "-Args": if (i + 1 < args.Length) argLine = args[++i]; break;
102
+ case "-Cwd": if (i + 1 < args.Length) cwd = args[++i]; break;
103
+ case "-Out": if (i + 1 < args.Length) outFile = args[++i]; break;
104
+ case "-Err": if (i + 1 < args.Length) errFile = args[++i]; break;
105
+ case "-Query": query = true; break;
106
+ }
107
+ }
108
+ if (query)
109
+ {
110
+ uint qs = WTSGetActiveConsoleSessionId();
111
+ Console.WriteLine("SESSION=" + (qs == 0xFFFFFFFF ? "-1" : qs.ToString()));
112
+ return 0;
113
+ }
114
+ if (exe == null || argLine == null) { Console.Error.WriteLine("usage: -Exe <exe> -Args <args> [-Cwd <dir>] | -Query"); return 2; }
115
+
116
+ uint session = WTSGetActiveConsoleSessionId();
117
+ if (session == 0xFFFFFFFF) { Console.Error.WriteLine("no active console session"); return 3; }
118
+
119
+ IntPtr userToken;
120
+ if (!WTSQueryUserToken(session, out userToken)) { Console.Error.WriteLine("WTSQueryUserToken failed: " + new Win32Exception(Marshal.GetLastWin32Error()).Message); return 4; }
121
+
122
+ IntPtr dup;
123
+ if (!DuplicateTokenEx(userToken, TOKEN_ALL_ACCESS, IntPtr.Zero, 2 /*SecurityImpersonation*/, 1 /*Primary*/, out dup))
124
+ { Console.Error.WriteLine("DuplicateTokenEx failed: " + new Win32Exception(Marshal.GetLastWin32Error()).Message); return 5; }
125
+
126
+ IntPtr env = IntPtr.Zero;
127
+ CreateEnvironmentBlock(out env, dup, false);
128
+
129
+ var si = new STARTUPINFO();
130
+ si.cb = Marshal.SizeOf(si);
131
+ si.lpDesktop = "winsta0\\default";
132
+
133
+ // Redirect child stdio to files (a service-session launch has no console,
134
+ // so otherwise the worker's errors would be lost).
135
+ IntPtr outHandle = IntPtr.Zero, errHandle = IntPtr.Zero;
136
+ if (outFile != null || errFile != null)
137
+ {
138
+ var sa = new SECURITY_ATTRIBUTES();
139
+ sa.nLength = Marshal.SizeOf(sa);
140
+ sa.bInheritHandle = true;
141
+ outHandle = CreateFile(outFile ?? "NUL", GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ, ref sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
142
+ errHandle = CreateFile(errFile ?? (outFile ?? "NUL"), GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ, ref sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
143
+ si.dwFlags |= STARTF_USESTDHANDLES;
144
+ si.hStdOutput = outHandle;
145
+ si.hStdError = errHandle;
146
+ }
147
+
148
+ PROCESS_INFORMATION pi;
149
+ // Quote the executable path (it contains spaces); node parses argv itself
150
+ // when launched via CreateProcessAsUser without a shell.
151
+ string cmd = "\"" + exe + "\" " + argLine;
152
+ bool ok = CreateProcessAsUser(dup, exe, cmd, IntPtr.Zero, IntPtr.Zero,
153
+ (outHandle != IntPtr.Zero), CREATE_UNICODE_ENVIRONMENT, env, string.IsNullOrEmpty(cwd) ? null : cwd, ref si, out pi);
154
+ if (!ok) { Console.Error.WriteLine("CreateProcessAsUser failed: " + new Win32Exception(Marshal.GetLastWin32Error()).Message); return 6; }
155
+
156
+ Console.WriteLine("LAUNCHED pid=" + pi.dwProcessId + " session=" + session);
157
+ CloseHandle(pi.hThread); CloseHandle(pi.hProcess); CloseHandle(dup); CloseHandle(userToken);
158
+ if (outHandle != IntPtr.Zero) CloseHandle(outHandle);
159
+ if (errHandle != IntPtr.Zero) CloseHandle(errHandle);
160
+ if (env != IntPtr.Zero) DestroyEnvironmentBlock(env);
161
+ return 0;
162
+ }
163
+ }
package/src/cli.js CHANGED
@@ -24,7 +24,7 @@ const crypto = require('crypto');
24
24
  const os = require('os');
25
25
  const path = require('path');
26
26
 
27
- const CLI_VERSION = '2.1.0';
27
+ const CLI_VERSION = '2.1.1';
28
28
  const PROTOCOL_VERSION = 2;
29
29
 
30
30
  // ── Command parsing ──────────────────────────────────────────────────────────