@xkwdstore/agent 2.1.4 → 2.1.5

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,113 @@
1
+ 'use strict';
2
+ /**
3
+ * Broker health snapshot (2.1.5).
4
+ *
5
+ * The machine broker runs as a Windows service, so `xkwd-agent status` (a
6
+ * different process) cannot ask it directly. This writes a small, NON-SECRET
7
+ * status file under the machine runtime directory so an operator can see the
8
+ * authentication state — especially "reauthorization required" after a device
9
+ * was revoked/replaced. It never contains a key, token, cookie or proxy string.
10
+ *
11
+ * Writes happen only on state transitions (the caller dedupes), so this file is
12
+ * not a heartbeat and cannot become a write storm.
13
+ */
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+ const machineState = require('./machineState');
17
+
18
+ const HEALTH_FILE_NAME = 'broker-health.json';
19
+
20
+ function getBrokerHealthPath() {
21
+ return path.join(machineState.paths.runtime, HEALTH_FILE_NAME);
22
+ }
23
+
24
+ /**
25
+ * Persist a health snapshot. Best-effort: status reporting must never break the
26
+ * broker. Values are bounded/sanitized here as a second line of defence.
27
+ *
28
+ * @param {object} patch
29
+ * @returns {boolean}
30
+ */
31
+ function writeBrokerHealth(patch = {}) {
32
+ const file = getBrokerHealthPath();
33
+ const data = {
34
+ schema: 1,
35
+ updatedAt: new Date().toISOString(),
36
+ state: patch.state ? String(patch.state).slice(0, 40) : 'unknown',
37
+ authBlocked: patch.authBlocked === true,
38
+ reauthorizationRequired: patch.reauthorizationRequired === true,
39
+ authFailures: Number.isFinite(patch.authFailures) ? Math.max(0, Math.min(1000, patch.authFailures)) : 0,
40
+ lastDisconnectCode: Number.isFinite(patch.lastDisconnectCode) ? patch.lastDisconnectCode : null,
41
+ lastDisconnectReason: patch.lastDisconnectReason ? String(patch.lastDisconnectReason).slice(0, 200) : null,
42
+ deviceId: patch.deviceId ? String(patch.deviceId).slice(0, 64) : null,
43
+ deviceName: patch.deviceName ? String(patch.deviceName).slice(0, 128) : null,
44
+ serverOrigin: patch.serverOrigin ? String(patch.serverOrigin).slice(0, 200) : null,
45
+ hint: patch.hint ? String(patch.hint).slice(0, 300) : null,
46
+ };
47
+ try {
48
+ fs.writeFileSync(file, JSON.stringify(data, null, 2) + '\n', { encoding: 'utf8', mode: 0o644 });
49
+ return true;
50
+ } catch {
51
+ return false;
52
+ }
53
+ }
54
+
55
+ /** Read the last snapshot, or null when absent/unreadable. */
56
+ function readBrokerHealth() {
57
+ try {
58
+ return JSON.parse(fs.readFileSync(getBrokerHealthPath(), 'utf8'));
59
+ } catch {
60
+ return null;
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Fallback for agents/brokers that predate the structured health file: read the
66
+ * tail of the broker log (read-only, bounded) and derive the authentication
67
+ * state. This makes an existing 4003 retry storm visible in `status`/`doctor`
68
+ * without modifying any production file.
69
+ */
70
+ function readBrokerLogAuthState() {
71
+ const file = path.join(machineState.paths.logs, 'broker.out.log');
72
+ try {
73
+ const st = fs.statSync(file);
74
+ const len = Math.min(st.size, 64 * 1024);
75
+ if (len <= 0) return null;
76
+ const fd = fs.openSync(file, 'r');
77
+ let text = '';
78
+ try {
79
+ const buf = Buffer.alloc(len);
80
+ fs.readSync(fd, buf, 0, len, st.size - len);
81
+ text = buf.toString('utf8');
82
+ } finally {
83
+ try { fs.closeSync(fd); } catch { /* ignore */ }
84
+ }
85
+ const lines = text.split(/\r?\n/).filter(Boolean);
86
+ let state = null;
87
+ let code = null;
88
+ for (let i = lines.length - 1; i >= 0; i--) {
89
+ const l = lines[i];
90
+ if (/reauthorization required/i.test(l)) { state = 'authentication_failed'; break; }
91
+ if (/auth=blocked/.test(l)) { state = 'authentication_rejected'; break; }
92
+ if (/disconnected code=4003/.test(l)) { state = 'authentication_failed'; code = 4003; break; }
93
+ if (/\[broker\] connected/.test(l)) { state = 'connected'; break; }
94
+ }
95
+ if (!state) return null;
96
+ return {
97
+ schema: 0,
98
+ source: 'broker-log',
99
+ state,
100
+ authBlocked: state !== 'connected',
101
+ reauthorizationRequired: state !== 'connected',
102
+ authFailures: null,
103
+ lastDisconnectCode: code,
104
+ hint: state === 'connected'
105
+ ? null
106
+ : 'The broker is rejecting this device identity. Check the account owner/authorization state; retries should not run forever.',
107
+ };
108
+ } catch {
109
+ return null;
110
+ }
111
+ }
112
+
113
+ module.exports = { getBrokerHealthPath, writeBrokerHealth, readBrokerHealth, readBrokerLogAuthState, HEALTH_FILE_NAME };
@@ -49,11 +49,20 @@ const crypto = require('crypto');
49
49
  const WORKER_COMMANDS = Object.freeze(new Set([
50
50
  'startSession',
51
51
  'stopSession',
52
+ 'refreshSession',
52
53
  'getStatus',
54
+ 'checkAuth',
55
+ 'navigate',
56
+ 'type',
57
+ 'paste',
58
+ 'press',
59
+ 'click',
60
+ 'runAction',
53
61
  'focus',
54
62
  'closeAll',
55
63
  'recoverOrphans',
56
64
  'proxy-test',
65
+ 'connectivity-test',
57
66
  'shutdown',
58
67
  ]));
59
68
 
@@ -176,7 +185,18 @@ function openBrokerChannel(opts) {
176
185
  const timer = setTimeout(() => { waiters.delete(id); rej(new BridgeError('worker call timed out: ' + command, 'WORKER_TIMEOUT')); }, timeoutMs);
177
186
  const _reject = (r) => rej(Object.assign(
178
187
  new Error(r.detail || r.error || 'worker error'),
179
- { code: r.error, stage: r.stage || null, accountId: r.accountId, accountUuid: r.accountUuid, proxyId: r.proxyId, proxy: r.proxy || null },
188
+ {
189
+ code: r.error,
190
+ stage: r.stage || null,
191
+ accountId: r.accountId,
192
+ accountUuid: r.accountUuid,
193
+ proxyId: r.proxyId,
194
+ proxy: r.proxy || null,
195
+ // Safe auth classification raised by the worker (never secrets).
196
+ authState: r.authState || null,
197
+ reason: r.reason || null,
198
+ failureStage: r.failureStage || null,
199
+ },
180
200
  ));
181
201
  waiters.set(id, (r) => { clearTimeout(timer); if (r.ok) res(r.result); else _reject(r); });
182
202
  if (results.has(id)) { const r = results.get(id); results.delete(id); waiters.delete(id); clearTimeout(timer); if (r.ok) res(r.result); else _reject(r); }
@@ -251,6 +271,11 @@ function openWorkerChannel(opts) {
251
271
  accountUuid: (err && err.accountUuid) || null,
252
272
  proxyId: (err && err.proxyId != null) ? err.proxyId : null,
253
273
  proxy: (err && err.proxy) || null,
274
+ // Safe auth classification: lets the broker separate "browser
275
+ // opened" from "session verified" without leaking page content.
276
+ authState: (err && err.authState) || null,
277
+ reason: (err && err.reason) || null,
278
+ failureStage: (err && err.failureStage) || null,
254
279
  }) + '\n');
255
280
  });
256
281
  }