@xkwdstore/agent 2.1.1 → 2.1.3

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
@@ -4,9 +4,9 @@ Terminal-only, cryptographically authenticated CLI for XKWDStore browser automat
4
4
 
5
5
  ## Installation
6
6
 
7
- > **@xkwdstore/agent 2.1.1 is the last version published on npm.**
7
+ > **@xkwdstore/agent 2.1.3 is the last version published on npm.**
8
8
  >
9
- > The current source version is **2.1.1** (machine-wide hardening). It is
9
+ > The current source version is **2.1.3** (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.1.1 start
32
+ npx --yes @xkwdstore/agent@2.1.3 start
33
33
  ```
34
34
 
35
35
  Automated installer tests use `-NoLaunch` or a mocked `npx` command so the
@@ -203,7 +203,7 @@ The agent does NOT update itself. To use a newer version, change the version
203
203
  number in the command. The pinned command for this release is:
204
204
 
205
205
  ```powershell
206
- npx --yes @xkwdstore/agent@2.1.1 start
206
+ npx --yes @xkwdstore/agent@2.1.3 start
207
207
  ```
208
208
 
209
209
  > 2.1.0 is the current local agent version (machine-wide hardening).
package/package.json CHANGED
@@ -1,66 +1,42 @@
1
- {
2
- "name": "@xkwdstore/agent",
3
- "version": "2.1.1",
4
- "description": "XKWDStore Agent — machine-wide, cryptographically authenticated CLI for isolated browser automation",
5
- "main": "src/cli.js",
6
- "bin": {
7
- "xkwd-agent": "src/cli.js"
8
- },
9
- "scripts": {
10
- "start": "node src/cli.js start",
11
- "dev": "node src/cli.js start",
12
- "test": "node --test tests/*.test.js",
13
- "build": "echo 'No build step — this is a pure npm CLI package'"
14
- },
15
- "engines": {
16
- "node": ">=22.0.0"
17
- },
18
- "files": [
19
- "src/cli.js",
20
- "src/deviceKeyStore.js",
21
- "src/machineState.js",
22
- "src/machineLock.js",
23
- "src/legacyStartup.js",
24
- "src/brokerWorkerBridge.js",
25
- "src/worker.js",
26
- "src/chromeDetector.js",
27
- "src/enrollmentClient.js",
28
- "src/processLock.js",
29
- "src/wsClient.js",
30
- "src/challengeCodec.js",
31
- "src/sessionHandler.js",
32
- "src/sessionRegistry.js",
33
- "src/browserIsolation.js",
34
- "src/fingerprint.js",
35
- "src/fingerprintStore.js",
36
- "src/profilePath.js",
37
- "src/stealth.js",
38
- "src/leaseClient.js",
39
- "src/proxyEgress.js",
40
- "src/proxyPolicy.js",
41
- "src/configStore.js",
42
- "src/secretStore.js",
43
- "src/actions/",
44
- "scripts/worker-entry.js",
45
- "scripts/install-machine-agent.ps1",
46
- "scripts/broker-service-host.cs",
47
- "scripts/session-launcher.cs",
48
- "README.md",
49
- "LICENSE"
50
- ],
51
- "dependencies": {
52
- "otpauth": "^9.3.0",
53
- "playwright-core": "^1.58.2",
54
- "ws": "^8.19.0"
55
- },
56
- "repository": {
57
- "type": "git",
58
- "url": "git+https://github.com/EssaGhazwani/TW-manager.git",
59
- "directory": "apps/local-agent"
60
- },
61
- "license": "UNLICENSED",
62
- "private": false,
63
- "publishConfig": {
64
- "access": "public"
65
- }
1
+ {
2
+ "name": "@xkwdstore/agent",
3
+ "version": "2.1.3",
4
+ "description": "XKWDStore Agent — machine-wide, cryptographically authenticated CLI for isolated browser automation",
5
+ "main": "src/cli.js",
6
+ "bin": {
7
+ "xkwd-agent": "src/cli.js"
8
+ },
9
+ "scripts": {
10
+ "start": "node src/cli.js start",
11
+ "dev": "node src/cli.js start",
12
+ "test": "node --test tests/*.test.js",
13
+ "build": "echo 'No build step — this is a pure npm CLI package'"
14
+ },
15
+ "engines": {
16
+ "node": ">=22.0.0"
17
+ },
18
+ "files": [
19
+ "src/",
20
+ "scripts/worker-entry.js",
21
+ "scripts/install-machine-agent.ps1",
22
+ "scripts/broker-service-host.cs",
23
+ "scripts/session-launcher.cs",
24
+ "README.md",
25
+ "LICENSE"
26
+ ],
27
+ "dependencies": {
28
+ "otpauth": "^9.3.0",
29
+ "playwright-core": "^1.58.2",
30
+ "ws": "^8.19.0"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/EssaGhazwani/TW-manager.git",
35
+ "directory": "apps/local-agent"
36
+ },
37
+ "license": "UNLICENSED",
38
+ "private": false,
39
+ "publishConfig": {
40
+ "access": "public"
41
+ }
66
42
  }
@@ -1,4 +1,4 @@
1
- # XKWDStore Agent 2.1.0 — Machine-Wide Silent Startup
1
+ # XKWDStore Agent - Machine-Wide Silent Startup (version from -AgentVersion)
2
2
  #
3
3
  # Installs / removes the machine-wide BROKER + per-session interactive WORKER
4
4
  # startup. This script MUST run elevated (it creates a Windows service and writes
@@ -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.1',
38
+ [string]$AgentVersion = '2.1.3',
39
39
  [string]$Server = 'https://x.kwdstore.com',
40
40
  [string]$ServiceAccount = 'LocalSystem',
41
41
  [string]$AgentRoot,
@@ -69,10 +69,10 @@ function Get-NodePath {
69
69
  return $cmd.Source
70
70
  }
71
71
 
72
- # ── install ──────────────────────────────────────────────────────────────────
72
+ # -- install -----------------------------------------------------------------
73
73
  if (-not $Uninstall) {
74
74
  Write-Host ''
75
- Write-Host ' XKWDStore Agent 2.1.0 — machine-wide silent startup' -ForegroundColor Cyan
75
+ Write-Host " XKWDStore Agent $AgentVersion - machine-wide silent startup" -ForegroundColor Cyan
76
76
  Write-Host ' ==================================================' -ForegroundColor Cyan
77
77
  Assert-Elevated
78
78
  $node = Get-NodePath
@@ -106,6 +106,40 @@ if (-not $Uninstall) {
106
106
  Write-Warn2 "agent src not found next to the installer; using the repo path in the service wrapper"
107
107
  }
108
108
 
109
+ # 1a-bis. Provision the RUNTIME DEPENDENCIES into the install dir.
110
+ # The block above copies a `node_modules` only if one sits next to the
111
+ # installer. A normal `npm install @xkwdstore/agent` hoists the agent's
112
+ # dependencies to the CALLER's node_modules, so the package directory ships
113
+ # none. Copying only what happens to be there therefore produced an install
114
+ # with no dependencies at all, and the broker died on its first bare
115
+ # `require('playwright-core')` - a MODULE_NOT_FOUND crash-loop masked by the
116
+ # service restarting it. The installer must guarantee the dependency tree
117
+ # exists, not hope it was shipped alongside.
118
+ $agentPkgJson = Join-Path $AgentInstallDir 'package.json'
119
+ if (Test-Path -LiteralPath $agentPkgJson) {
120
+ $depProbe = Join-Path $AgentInstallDir 'node_modules\playwright-core'
121
+ if (-not (Test-Path -LiteralPath $depProbe)) {
122
+ $agentLockJson = Join-Path $AgentInstallDir 'package-lock.json'
123
+ Write-Step 'provisioning agent runtime dependencies (npm)'
124
+ Push-Location $AgentInstallDir
125
+ try {
126
+ if (Test-Path -LiteralPath $agentLockJson) {
127
+ & npm ci --omit=dev --no-audit --no-fund *> $null
128
+ } else {
129
+ & npm install --omit=dev --no-audit --no-fund *> $null
130
+ }
131
+ } finally { Pop-Location }
132
+ if (-not (Test-Path -LiteralPath $depProbe)) {
133
+ Write-Host ' X agent runtime dependencies could not be provisioned.' -ForegroundColor Red
134
+ Write-Host ' The agent needs npm + network access on this machine.' -ForegroundColor Red
135
+ exit 1
136
+ }
137
+ Write-Ok 'agent runtime dependencies provisioned'
138
+ } else {
139
+ Write-Ok 'agent runtime dependencies already present'
140
+ }
141
+ }
142
+
109
143
  # 1b. place the worker-entry launcher where the logon task expects it AND the
110
144
  # installer-managed scripts next to the installed program files.
111
145
  $workerEntrySrc = Join-Path $PSScriptRoot 'worker-entry.js'
@@ -266,7 +300,7 @@ try {
266
300
  $staleCmd = Join-Path $MachineRoot 'launcher\broker-service.cmd'
267
301
  if (Test-Path -LiteralPath $staleCmd) { Remove-Item $staleCmd -Force -ErrorAction SilentlyContinue }
268
302
 
269
- # 4. per-session worker fallback (logon task) — only used if session spawning is unavailable
303
+ # 4. per-session worker fallback (logon task) - only used if session spawning is unavailable
270
304
  $taskName = 'XKWDStoreAgentWorker'
271
305
  try {
272
306
  $action = New-ScheduledTaskAction -Execute $node -Argument "`"$workerEntryDst`""
@@ -325,9 +359,9 @@ try {
325
359
  exit 0
326
360
  }
327
361
 
328
- # ── uninstall ────────────────────────────────────────────────────────────────
362
+ # -- uninstall ---------------------------------------------------------------
329
363
  Write-Host ''
330
- Write-Host ' XKWDStore Agent 2.1.0 — uninstall' -ForegroundColor Cyan
364
+ Write-Host " XKWDStore Agent $AgentVersion - uninstall" -ForegroundColor Cyan
331
365
  Assert-Elevated
332
366
  $svc = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
333
367
  if ($svc) {
@@ -27,7 +27,7 @@ const { spawn } = require('child_process');
27
27
 
28
28
  function main() {
29
29
  let machineState;
30
- try { machineState = require('../machineState'); } catch { process.exit(0); }
30
+ try { machineState = require('../src/machineState'); } catch { process.exit(0); }
31
31
 
32
32
  const invitePath = path.join(machineState.paths.runtime, 'worker-invite.json');
33
33
  let invite = null;
@@ -0,0 +1,263 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * BrokerConnectionSupervisor — ONE reconnect lifecycle shared by the foreground
5
+ * `start` agent and the machine `service` broker (2.1.0 reconnect fix).
6
+ *
7
+ * WHY THIS EXISTS
8
+ * The production machine broker must be long-lived. A transient loss of network,
9
+ * DNS, TLS reachability, backend availability, the WebSocket, or a heartbeat must
10
+ * NOT require a manual service restart, a user login, a re-pair, or a new device
11
+ * identity. The broker must transparently reconnect with the SAME enrolled
12
+ * identity.
13
+ *
14
+ * The foreground `start` path had an ad-hoc reconnect; the `service` path had
15
+ * NONE, so a dropped production WebSocket left the broker idle forever. This
16
+ * module is the single supervisor used by BOTH paths.
17
+ *
18
+ * GUARANTEES
19
+ * - at most ONE reconnect timer and ONE in-flight connect attempt (Phase 7);
20
+ * - at most ONE active WebSocket; a stale socket's close is ignored;
21
+ * - bounded exponential backoff with jitter, reset after a stable connect;
22
+ * - `stop()` cancels the timer and prevents any later reconnect;
23
+ * - a pong watchdog terminates a half-open socket so the close path runs;
24
+ * - transport recovery only: it never touches the device id/key/pairing.
25
+ *
26
+ * Dependencies (timers, random, now, connect) are injectable for deterministic
27
+ * tests. No secrets are ever logged.
28
+ */
29
+
30
+ const DEFAULT_BACKOFF = Object.freeze({ baseMs: 1000, maxMs: 60000, jitterMs: 1000, factor: 2 });
31
+ // The agent heartbeat is every 10s (see sessionHandler). A half-open socket is
32
+ // terminated only after several missed pongs — deliberately NOT aggressive.
33
+ const DEFAULT_PONG_TIMEOUT_MS = 60000;
34
+
35
+ function _safeMsg(e) { return String((e && e.message) || e || 'unknown').slice(0, 200); }
36
+
37
+ /** Auth/credential failures must not busy-loop AND must not regenerate identity. */
38
+ function isAuthErrorMessage(msg) {
39
+ return /4003|device authentication failed|unauthorized|revoked|unknown key|invalid (device|machine) identity|protocol version|unsupported protocol/i.test(String(msg || ''));
40
+ }
41
+
42
+ function createBrokerConnectionSupervisor(opts = {}) {
43
+ const connect = opts.connect;
44
+ if (typeof connect !== 'function') throw new Error('createBrokerConnectionSupervisor: connect is required');
45
+
46
+ const onConnected = opts.onConnected || (() => {});
47
+ const onDisconnected = opts.onDisconnected || (() => {});
48
+ const onAuthRejected = opts.onAuthRejected || null;
49
+ const onStateChange = opts.onStateChange || null;
50
+ const log = opts.log || (() => {});
51
+ const timer = opts.timers || {};
52
+ const setTimeoutFn = timer.setTimeout || setTimeout;
53
+ const clearTimeoutFn = timer.clearTimeout || clearTimeout;
54
+ const setIntervalFn = timer.setInterval || setInterval;
55
+ const clearIntervalFn = timer.clearInterval || clearInterval;
56
+ const now = opts.now || (() => Date.now());
57
+ const random = opts.random || Math.random;
58
+ const backoff = { ...DEFAULT_BACKOFF, ...(opts.backoff || {}) };
59
+ // 0 = retry forever (machine service). >0 = bounded (foreground start).
60
+ const maxAttempts = Number.isInteger(opts.maxAttempts) ? opts.maxAttempts : 0;
61
+ const pongTimeoutMs = Number.isInteger(opts.pongTimeoutMs) ? opts.pongTimeoutMs : DEFAULT_PONG_TIMEOUT_MS;
62
+
63
+ let state = 'idle'; // idle|connecting|connected|disconnected|reconnecting|auth_blocked|stopping
64
+ let ws = null;
65
+ let retryTimer = null;
66
+ let stopped = false;
67
+ let attempt = 0;
68
+ let connectInFlight = false;
69
+ let heartbeatTimer = null;
70
+ let lastPongAt = 0;
71
+
72
+ const diag = {
73
+ lastConnectedAt: null,
74
+ lastDisconnectedAt: null,
75
+ lastDisconnectCode: null,
76
+ lastDisconnectReason: null,
77
+ reconnectAttempt: 0,
78
+ nextRetryMs: null,
79
+ authBlocked: false,
80
+ };
81
+
82
+ function getState() {
83
+ return {
84
+ state,
85
+ deviceIdentityPreserved: true,
86
+ ...diag,
87
+ };
88
+ }
89
+
90
+ function setState(s) {
91
+ state = s;
92
+ try { if (onStateChange) onStateChange(s, getState()); } catch { /* never break the lifecycle */ }
93
+ }
94
+
95
+ function _clearRetry() {
96
+ if (retryTimer) { try { clearTimeoutFn(retryTimer); } catch {} retryTimer = null; }
97
+ }
98
+
99
+ function _stopHeartbeatWatch() {
100
+ if (heartbeatTimer) { try { clearIntervalFn(heartbeatTimer); } catch {} heartbeatTimer = null; }
101
+ }
102
+
103
+ function _startHeartbeatWatch(sock) {
104
+ _stopHeartbeatWatch();
105
+ lastPongAt = now();
106
+ try {
107
+ sock.on('pong', () => { lastPongAt = now(); });
108
+ } catch { /* fake sockets in tests may not support on */ }
109
+ heartbeatTimer = setIntervalFn(() => {
110
+ if (stopped || ws !== sock) { _stopHeartbeatWatch(); return; }
111
+ const silentFor = now() - lastPongAt;
112
+ if (silentFor > pongTimeoutMs) {
113
+ // Half-open socket: the TCP peer is gone but no close event arrived.
114
+ // Terminating drives the normal close path -> reconnect.
115
+ log(`[broker] heartbeat timeout (silent ${Math.round(silentFor)}ms); terminating socket`);
116
+ try { sock.terminate(); } catch {}
117
+ }
118
+ }, Math.max(1000, Math.floor(pongTimeoutMs / 3)));
119
+ if (typeof heartbeatTimer.unref === 'function') heartbeatTimer.unref();
120
+ }
121
+
122
+ function _scheduleReconnect(info = {}) {
123
+ if (stopped) return;
124
+ if (retryTimer) return; // SINGLE reconnect timer invariant
125
+ attempt += 1;
126
+ diag.reconnectAttempt = attempt;
127
+ diag.authBlocked = info.auth === true;
128
+
129
+ if (maxAttempts > 0 && attempt > maxAttempts) {
130
+ setState('disconnected');
131
+ log(`[broker] reconnect exhausted after ${maxAttempts} attempts; giving up (identity preserved)`);
132
+ if (opts.onExhausted) { try { opts.onExhausted(getState()); } catch {} }
133
+ return;
134
+ }
135
+
136
+ const exp = Math.min(backoff.baseMs * Math.pow(backoff.factor, attempt - 1), backoff.maxMs);
137
+ const jitter = Math.floor(random() * backoff.jitterMs);
138
+ const delay = exp + jitter;
139
+ diag.nextRetryMs = delay;
140
+ setState(info.auth ? 'auth_blocked' : 'reconnecting');
141
+ log(`[broker] reconnect scheduled attempt=${attempt} retry=${Math.round(delay)}ms${info.auth ? ' auth=blocked' : ''}`);
142
+ retryTimer = setTimeoutFn(() => { retryTimer = null; _attemptConnect(); }, delay);
143
+ }
144
+
145
+ async function _attemptConnect() {
146
+ if (stopped) return;
147
+ if (connectInFlight) return; // SINGLE in-flight attempt invariant
148
+ if (ws) return; // already connected
149
+ connectInFlight = true;
150
+ setState(attempt > 0 ? 'reconnecting' : 'connecting');
151
+ log(`[broker] ${attempt > 0 ? 'reconnecting' : 'connecting'} attempt=${attempt}`);
152
+
153
+ let sock;
154
+ try {
155
+ sock = await connect();
156
+ } catch (err) {
157
+ connectInFlight = false;
158
+ if (stopped) return;
159
+ const auth = isAuthErrorMessage(_safeMsg(err));
160
+ log(`[broker] connect failed: ${_safeMsg(err)}`);
161
+ if (auth && onAuthRejected) { try { onAuthRejected({ error: err }); } catch {} }
162
+ _scheduleReconnect({ auth });
163
+ return;
164
+ }
165
+ connectInFlight = false;
166
+ if (stopped) { try { sock.close(1000, 'stopping'); } catch {} return; }
167
+
168
+ ws = sock;
169
+ attempt = 0;
170
+ diag.lastConnectedAt = now();
171
+ diag.nextRetryMs = null;
172
+ diag.reconnectAttempt = 0;
173
+ diag.authBlocked = false;
174
+ setState('connected');
175
+ log('[broker] connected');
176
+
177
+ try { sock.on('close', (code, reason) => _handleClose(sock, code, reason)); } catch {}
178
+ // An 'error' event immediately preceded by nothing else must not crash the
179
+ // process; the close path handles reconnection.
180
+ try { sock.on('error', () => {}); } catch {}
181
+ _startHeartbeatWatch(sock);
182
+
183
+ try { await onConnected(sock); } catch (e) { log(`[broker] onConnected error: ${_safeMsg(e)}`); }
184
+ }
185
+
186
+ function _handleClose(closedSock, code, reason) {
187
+ if (stopped) return;
188
+ if (ws !== closedSock) return; // stale socket (already replaced) — ignore
189
+ ws = null;
190
+ _stopHeartbeatWatch();
191
+ const reasonStr = reason ? reason.toString() : '';
192
+ diag.lastDisconnectedAt = now();
193
+ diag.lastDisconnectCode = code;
194
+ diag.lastDisconnectReason = reasonStr;
195
+
196
+ if (code === 4003) {
197
+ diag.authBlocked = true;
198
+ log('[broker] disconnected code=4003 (authentication/identity)');
199
+ if (onAuthRejected) { try { onAuthRejected({ code, reason: reasonStr }); } catch {} }
200
+ // Conservative retry; identity is NEVER regenerated or deleted here.
201
+ _scheduleReconnect({ auth: true });
202
+ return;
203
+ }
204
+
205
+ log(`[broker] disconnected code=${code}${reasonStr ? ' reason=' + reasonStr : ''}`);
206
+ try { const r = onDisconnected({ code, reason: reasonStr }); if (r && typeof r.catch === 'function') r.catch(() => {}); } catch {}
207
+ _scheduleReconnect({});
208
+ }
209
+
210
+ function start() {
211
+ stopped = false;
212
+ attempt = 0;
213
+ return _attemptConnect();
214
+ }
215
+
216
+ /**
217
+ * Adopt an ALREADY-authenticated socket (the foreground `start` path connects
218
+ * first, including its one-time enrollment flow, then hands the live socket to
219
+ * the supervisor for its reconnect lifecycle). Binding happens through
220
+ * `onConnected` exactly once, so the handler is never double-installed.
221
+ */
222
+ function adopt(sock) {
223
+ if (!sock) return;
224
+ stopped = false;
225
+ connectInFlight = false;
226
+ attempt = 0;
227
+ ws = sock;
228
+ diag.lastConnectedAt = now();
229
+ diag.nextRetryMs = null;
230
+ diag.reconnectAttempt = 0;
231
+ diag.authBlocked = false;
232
+ setState('connected');
233
+ log('[broker] connected');
234
+ try { sock.on('close', (code, reason) => _handleClose(sock, code, reason)); } catch {}
235
+ try { sock.on('error', () => {}); } catch {}
236
+ _startHeartbeatWatch(sock);
237
+ try { const r = onConnected(sock); if (r && typeof r.catch === 'function') r.catch(() => {}); } catch {}
238
+ }
239
+
240
+ function stop() {
241
+ if (stopped) return;
242
+ stopped = true;
243
+ _clearRetry();
244
+ _stopHeartbeatWatch();
245
+ setState('stopping');
246
+ const sock = ws;
247
+ ws = null;
248
+ if (sock) { try { sock.close(1000, 'shutdown'); } catch {} }
249
+ }
250
+
251
+ return {
252
+ start,
253
+ adopt,
254
+ stop,
255
+ getState,
256
+ // Exported for white-box deterministic tests.
257
+ _handleClose,
258
+ _attemptConnect,
259
+ _isAuthError: (e) => isAuthErrorMessage(_safeMsg(e)),
260
+ };
261
+ }
262
+
263
+ module.exports = { createBrokerConnectionSupervisor, isAuthErrorMessage, DEFAULT_BACKOFF, DEFAULT_PONG_TIMEOUT_MS };