@xkwdstore/agent 2.1.5 → 2.1.6

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.
@@ -1,113 +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 };
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 };