@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.
@@ -0,0 +1,195 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Legacy per-user startup retirement (TW-manager Agent 2.1.0).
5
+ *
6
+ * WHY THIS EXISTS
7
+ * ---------------
8
+ * A 2.0.x install created a PER-USER launcher
9
+ * (`start-xkwdstore-agent.bat`) that starts the old Agent when a Windows user
10
+ * logs in. After the 2.1.0 machine-wide service is installed and VERIFIED, that
11
+ * legacy auto-start must never run: a machine-wide service and the old per-user
12
+ * Agent must not own Agent lifecycle concurrently (they would both connect as the
13
+ * same machine device).
14
+ *
15
+ * FAIL-SAFE ORDER (the installer enforces this):
16
+ * 1. detect legacy launchers (positive identification only)
17
+ * 2. back them up (hash + metadata) to a rollback-only location
18
+ * 3. install + VERIFY the 2.1.0 broker service
19
+ * 4. ONLY THEN disable the legacy launchers
20
+ * 5. stop a PROVEN legacy Agent process (exact command line), never a generic node
21
+ *
22
+ * If step 3 fails, the installer MUST NOT call disable: rollback stays possible.
23
+ *
24
+ * SAFETY: identification is CONTENT-based, never filename-only. An unrelated
25
+ * `*.bat` in a Startup folder is never touched. Pure functions are unit-tested;
26
+ * fs operations are thin wrappers.
27
+ */
28
+
29
+ const fs = require('fs');
30
+ const path = require('path');
31
+ const crypto = require('crypto');
32
+
33
+ const LAUNCHER_BASENAME = 'start-xkwdstore-agent.bat';
34
+ const DEFAULT_BACKUP_SUBDIR = path.join('state', 'legacy-startup-backup');
35
+
36
+ /**
37
+ * Is this file CONTENT a legacy XKWDStore per-user Agent launcher?
38
+ * Positive identification: it must reference the `@xkwdstore/agent` package AND
39
+ * a `start` invocation. A filename match alone is NOT sufficient.
40
+ */
41
+ function isLegacyLauncherContent(content) {
42
+ const c = String(content || '');
43
+ if (!/@xkwdstore\/agent/i.test(c)) return false;
44
+ if (!/\bstart\b/i.test(c)) return false;
45
+ // It must be a self-starting launcher (batch/cmd/powershell), not a data file.
46
+ return /@echo off|npx|node |Invoke-|Start-Process/i.test(c);
47
+ }
48
+
49
+ /** sha256 hex of a string or Buffer. */
50
+ function sha256(data) {
51
+ return crypto.createHash('sha256').update(data).digest('hex');
52
+ }
53
+
54
+ /**
55
+ * Find legacy launcher CANDIDATES under a set of roots.
56
+ *
57
+ * @param {object} opts
58
+ * @param {string} opts.usersRoot — e.g. C:\Users
59
+ * @param {string} [opts.machineRoot] — for the legacy install dir per profile
60
+ * @returns {Array<{profile, path, sha256, content}>} only POSITIVELY identified entries
61
+ */
62
+ function findLegacyLaunchers(opts = {}) {
63
+ const usersRoot = opts.usersRoot || 'C:\\Users';
64
+ const found = [];
65
+ let profiles;
66
+ try { profiles = fs.readdirSync(usersRoot, { withFileTypes: true }); } catch { return found; }
67
+ for (const p of profiles) {
68
+ if (!p.isDirectory()) continue;
69
+ const profile = path.join(usersRoot, p.name);
70
+ // Candidate locations for a per-user install:
71
+ // 1. the Startup folder (auto-start)
72
+ // 2. the legacy install dir (launcher artifact, not auto-started)
73
+ const candidates = [
74
+ path.join(profile, 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', LAUNCHER_BASENAME),
75
+ path.join(profile, 'AppData', 'Local', 'XKWDStore', 'Agent', LAUNCHER_BASENAME),
76
+ ];
77
+ for (const c of candidates) {
78
+ let content;
79
+ try { content = fs.readFileSync(c, 'utf8'); } catch { continue; }
80
+ if (!isLegacyLauncherContent(content)) continue;
81
+ found.push({
82
+ profile: p.name,
83
+ path: c,
84
+ inStartupFolder: /[\\/]Startup[\\/]/i.test(c),
85
+ sha256: sha256(content),
86
+ content,
87
+ });
88
+ }
89
+ }
90
+ return found;
91
+ }
92
+
93
+ /** Backup a launcher to <backupDir>/<profile>/<basename> plus a metadata JSON. */
94
+ function backupLauncher(entry, backupDir) {
95
+ const destDir = path.join(backupDir, entry.profile);
96
+ fs.mkdirSync(destDir, { recursive: true });
97
+ const dest = path.join(destDir, LAUNCHER_BASENAME);
98
+ fs.copyFileSync(entry.path, dest);
99
+ const meta = {
100
+ profile: entry.profile,
101
+ originalPath: entry.path,
102
+ backedUpTo: dest,
103
+ sha256: entry.sha256,
104
+ inStartupFolder: !!entry.inStartupFolder,
105
+ backedUpAt: new Date().toISOString(),
106
+ };
107
+ fs.writeFileSync(path.join(destDir, 'metadata.json'), JSON.stringify(meta, null, 2), 'utf8');
108
+ return meta;
109
+ }
110
+
111
+ /**
112
+ * Disable a legacy launcher. If it lives in a Startup folder it is REMOVED from
113
+ * there (auto-start stops); a copy in the legacy install dir is left in place
114
+ * (it is not auto-started and the backup preserves rollback). Never called unless
115
+ * a backup exists.
116
+ */
117
+ function disableLauncher(entry, backupDir) {
118
+ const metaPath = path.join(backupDir, entry.profile, 'metadata.json');
119
+ if (!fs.existsSync(metaPath)) {
120
+ throw new Error('refusing to disable a legacy launcher without a backup: ' + entry.path);
121
+ }
122
+ if (entry.inStartupFolder) {
123
+ fs.unlinkSync(entry.path);
124
+ return { path: entry.path, action: 'removed_from_startup' };
125
+ }
126
+ return { path: entry.path, action: 'left_in_place_not_autostarted' };
127
+ }
128
+
129
+ /**
130
+ * Classify running processes (given {pid, name, commandLine}) into the 2.1.0
131
+ * roles and PROVEN legacy Agent processes. Ownership is decided by EXACT command
132
+ * line content, never by process name.
133
+ *
134
+ * @returns {{serviceHost:[], broker:[], worker:[], legacyAgent:[], unrelated:[]}}
135
+ */
136
+ function classifyAgentProcesses(processes) {
137
+ const out = { serviceHost: [], broker: [], worker: [], legacyAgent: [], unrelated: [] };
138
+ for (const p of processes || []) {
139
+ const cmd = String(p.commandLine || '');
140
+ if (/XKWDStoreBrokerService\.exe/i.test(cmd)) { out.serviceHost.push(p); continue; }
141
+ if (/XKWDStoreSessionLauncher\.exe/i.test(cmd)) { out.worker.push(p); continue; }
142
+ if (/worker\.js/i.test(cmd) && /XKWDStore/i.test(cmd)) { out.worker.push(p); continue; }
143
+ if (/[\\/]XKWDStore[\\/]Agent[\\/]cli\.js"?\s+service/i.test(cmd)) { out.broker.push(p); continue; }
144
+ // A LEGACY agent: the npm package invocation, or the legacy launcher BAT,
145
+ // pinned to a 2.0.x version (or unpinned `@xkwdstore/agent`).
146
+ if (/@xkwdstore[\\/]agent(@\d|\\|\s|")/.test(cmd) || /start-xkwdstore-agent\.bat/i.test(cmd)) {
147
+ out.legacyAgent.push(p);
148
+ continue;
149
+ }
150
+ out.unrelated.push(p);
151
+ }
152
+ return out;
153
+ }
154
+
155
+ module.exports = {
156
+ LAUNCHER_BASENAME,
157
+ DEFAULT_BACKUP_SUBDIR,
158
+ isLegacyLauncherContent,
159
+ sha256,
160
+ findLegacyLaunchers,
161
+ backupLauncher,
162
+ disableLauncher,
163
+ classifyAgentProcesses,
164
+ };
165
+
166
+ // ── CLI (used by the installer; safe, JSON output, no secrets) ────────────────
167
+ if (require.main === module) {
168
+ const argv = process.argv.slice(2);
169
+ const cmd = argv[0];
170
+ const arg = (k, d) => { const i = argv.indexOf(k); return i >= 0 ? argv[i + 1] : d; };
171
+ const usersRoot = arg('--users-root', 'C:\\Users');
172
+ const backupDir = arg('--backup-dir', '');
173
+ try {
174
+ if (cmd === 'detect') {
175
+ const found = findLegacyLaunchers({ usersRoot });
176
+ process.stdout.write(JSON.stringify({ ok: true, count: found.length, entries: found.map((e) => ({ profile: e.profile, path: e.path, inStartupFolder: e.inStartupFolder, sha256: e.sha256 })) }));
177
+ } else if (cmd === 'backup') {
178
+ if (!backupDir) throw new Error('--backup-dir is required');
179
+ const found = findLegacyLaunchers({ usersRoot });
180
+ const metas = found.map((e) => backupLauncher(e, backupDir));
181
+ process.stdout.write(JSON.stringify({ ok: true, count: metas.length, metas }));
182
+ } else if (cmd === 'disable') {
183
+ if (!backupDir) throw new Error('--backup-dir is required');
184
+ const found = findLegacyLaunchers({ usersRoot });
185
+ const results = found.map((e) => disableLauncher(e, backupDir));
186
+ process.stdout.write(JSON.stringify({ ok: true, count: results.length, results }));
187
+ } else {
188
+ process.stderr.write('usage: legacyStartup.js detect|backup|disable [--users-root <dir>] [--backup-dir <dir>]');
189
+ process.exit(2);
190
+ }
191
+ } catch (e) {
192
+ process.stdout.write(JSON.stringify({ ok: false, error: (e && e.message) || 'error' }));
193
+ process.exit(1);
194
+ }
195
+ }
@@ -0,0 +1,202 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Machine-wide broker uniqueness (TW-manager Agent 2.1.0).
5
+ *
6
+ * WHY THIS EXISTS
7
+ * ---------------
8
+ * The file lock in `processLock.js` is advisory and per-path. It is NOT a true
9
+ * machine-wide synchronization primitive:
10
+ *
11
+ * - two processes can race between "check the lock file" and "create it";
12
+ * - a lock file can be deleted/stale-reclaimed by a second broker while the
13
+ * first is still alive;
14
+ * - on Windows it cannot by itself guarantee exactly one broker across
15
+ * DIFFERENT Windows users (delete permission, timing).
16
+ *
17
+ * A Windows NAMED MUTEX is a kernel object: the OS guarantees that exactly one
18
+ * process can hold it, across every session and every Windows user on the
19
+ * machine. We use a Global\ mutex (machine-wide namespace) with a fixed,
20
+ * well-known name derived from the product, so:
21
+ *
22
+ * - starting a second broker (same user, different user, elevated, or from a
23
+ * Windows Service) fails cleanly instead of racing;
24
+ * - the mutex is released automatically by the kernel when the owning process
25
+ * dies (no stale file to reclaim);
26
+ * - it does NOT depend on ACL denial for correctness.
27
+ *
28
+ * The file lock is retained as a fast, human-inspectable status surface and for
29
+ * non-Windows dev/CI; on Windows the named mutex is the AUTHORITATIVE broker
30
+ * uniqueness guarantee and the file lock is advisory metadata.
31
+ *
32
+ * This module is dependency-free (node:net is used only as a fallback lock for
33
+ * non-Windows) so it can be required from anywhere without a cycle.
34
+ */
35
+
36
+ const os = require('os');
37
+ const net = require('net');
38
+
39
+ // The mutex name is resolved at CALL time so tests can isolate with a unique
40
+ // name (XKWDSTORE_MUTEX_NAME) without colliding with a real running broker.
41
+ function mutexName() {
42
+ return process.env.XKWDSTORE_MUTEX_NAME || 'Global\\XKWDStoreAgentMachineBroker-v1';
43
+ }
44
+
45
+ let _windowsHandle = null;
46
+ let _tcpFallback = null;
47
+
48
+ /**
49
+ * Try to acquire the machine-wide broker lock.
50
+ *
51
+ * @returns {{ acquired: boolean, primitive: 'mutex'|'tcp'|'none', detail: string }}
52
+ * acquired=true -> this process is the machine broker
53
+ * acquired=false -> another broker already holds it (detail names the primitive)
54
+ */
55
+ function acquireMachineBrokerLock() {
56
+ if (os.platform() === 'win32') {
57
+ return _acquireWindowsMutex();
58
+ }
59
+ return _acquireTcpFallback();
60
+ }
61
+
62
+ /**
63
+ * Release the machine-wide broker lock, if held by this process. Safe to call
64
+ * multiple times and on a lock that was never acquired.
65
+ */
66
+ function releaseMachineBrokerLock() {
67
+ if (_windowsHandle != null) {
68
+ try { _windowsHandle.release(); } catch { /* kernel may have already released */ }
69
+ try { if (typeof _windowsHandle.close === 'function') _windowsHandle.close(); } catch { }
70
+ _windowsHandle = null;
71
+ }
72
+ if (_tcpFallback) {
73
+ try { _tcpFallback.server.close(); } catch { }
74
+ _tcpFallback = null;
75
+ }
76
+ }
77
+
78
+ /** True when THIS process currently holds the machine broker lock. */
79
+ function holdsMachineBrokerLock() {
80
+ return _windowsHandle != null || _tcpFallback != null;
81
+ }
82
+
83
+ /**
84
+ * Windows named mutex via a tiny PowerShell host.
85
+ *
86
+ * Node has no built-in Win32 mutex API, so we host one in PowerShell 5.1 (already
87
+ * a hard dependency of this agent for DPAPI/ACL). The child:
88
+ * - opens/creates the Global\ named mutex;
89
+ * - calls WaitOne(0): a zero-timeout acquire. `false` means another process
90
+ * holds it (that IS the duplicate-broker signal);
91
+ * - on success, HOLDS the handle until the parent writes a line to its stdin
92
+ * (then exits and releases), or is killed (kernel releases automatically).
93
+ *
94
+ * This is synchronous and bounded (5s) so a hung shell cannot wedge startup.
95
+ */
96
+ function _acquireWindowsMutex() {
97
+ const { spawnSync } = require('child_process');
98
+ const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
99
+ const path = require('path');
100
+ const psExe = path.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
101
+
102
+ // The script prints ACQUIRED / BUSY, then waits on stdin before releasing.
103
+ // PowerShell 5.1 emits routine text on stderr; we capture the two streams
104
+ // separately and only trust the parsed marker.
105
+ const script = [
106
+ "$ErrorActionPreference='Stop'",
107
+ "$name = '" + mutexName().replace(/'/g, "''") + "'",
108
+ "$createdNew = $false",
109
+ "$m = New-Object System.Threading.Mutex($true, $name, [ref]$createdNew)",
110
+ "$got = $m.WaitOne(0)",
111
+ "if ($got) { [Console]::Out.Write('ACQUIRED'); [Console]::Out.Flush(); $null = [Console]::In.ReadLine(); $m.ReleaseMutex() } else { [Console]::Out.Write('BUSY') }",
112
+ "$m.Dispose()",
113
+ ].join('; ');
114
+
115
+ const r = spawnSync(psExe, ['-NoProfile', '-NonInteractive', '-Command', script], {
116
+ encoding: 'utf8',
117
+ timeout: 5000,
118
+ windowsHide: true,
119
+ input: '', // EOF immediately after the write: the child acquires, writes, releases.
120
+ });
121
+
122
+ const out = String(r.stdout || '').trim();
123
+ if (out.includes('ACQUIRED')) {
124
+ // NOTE: with `input:''` the child has already exited and released the mutex by
125
+ // the time we return. That is intentional for the STARTUP uniqueness probe:
126
+ // we record the outcome and then rely on the long-lived broker holding the
127
+ // mutex via a dedicated holder process (see startMutexHolder).
128
+ return { acquired: true, primitive: 'mutex', detail: 'named mutex ' + mutexName() + ' acquired (probe)' };
129
+ }
130
+ if (out.includes('BUSY')) {
131
+ return { acquired: false, primitive: 'mutex', detail: 'another broker holds ' + mutexName() };
132
+ }
133
+ // The probe could not run (PowerShell missing / unsupported). Fail CLOSED for
134
+ // uniqueness by falling back to the TCP lock; never claim acquired on error.
135
+ return _acquireTcpFallback('mutex-probe-failed');
136
+ }
137
+
138
+ /**
139
+ * Hold the named mutex for the LIFETIME of the broker. Spawns a detached child
140
+ * that acquires the mutex and blocks until its stdin closes (broker exit) or it
141
+ * is killed. Returns a controller with stop().
142
+ *
143
+ * @returns {{ ok: boolean, pid?: number, detail: string, stop: function }}
144
+ */
145
+ function startMutexHolder() {
146
+ if (os.platform() !== 'win32') {
147
+ return { ok: false, detail: 'mutex holder is Windows-only', stop() {} };
148
+ }
149
+ const { spawn } = require('child_process');
150
+ const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
151
+ const path = require('path');
152
+ const psExe = path.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
153
+ const script = [
154
+ "$ErrorActionPreference='Stop'",
155
+ "$name = '" + mutexName().replace(/'/g, "''") + "'",
156
+ "$createdNew = $false",
157
+ "$m = New-Object System.Threading.Mutex($true, $name, [ref]$createdNew)",
158
+ "$got = $m.WaitOne(0)",
159
+ "if ($got) { [Console]::Out.Write('ACQUIRED'); [Console]::Out.Flush(); $null = [Console]::In.ReadLine(); $m.ReleaseMutex() } else { [Console]::Out.Write('BUSY') }",
160
+ "$m.Dispose()",
161
+ ].join('; ');
162
+ const child = spawn(psExe, ['-NoProfile', '-NonInteractive', '-Command', script], {
163
+ windowsHide: true,
164
+ stdio: ['pipe', 'pipe', 'ignore'],
165
+ });
166
+ _windowsHandle = {
167
+ release() { try { child.stdin.write('\n'); } catch { } try { child.stdin.end(); } catch { } },
168
+ close() { try { child.kill(); } catch { } },
169
+ pid: child.pid,
170
+ };
171
+ return {
172
+ ok: true,
173
+ pid: child.pid,
174
+ detail: 'holding ' + mutexName() + ' (holder pid ' + child.pid + ')',
175
+ stop() { releaseMachineBrokerLock(); },
176
+ };
177
+ }
178
+
179
+ /**
180
+ * Non-Windows fallback: bind a loopback TCP port as an exclusive machine lock.
181
+ * Not required for production (Windows), but keeps dev/CI honest.
182
+ */
183
+ function _acquireTcpFallback(reason) {
184
+ if (_tcpFallback) return { acquired: true, primitive: 'tcp', detail: 'already held' };
185
+ try {
186
+ const server = net.createServer();
187
+ // Synchronous bind probe: listen then immediately report.
188
+ server.listen({ host: '127.0.0.1', port: 49_713, exclusive: true });
189
+ _tcpFallback = { server };
190
+ return { acquired: true, primitive: 'tcp', detail: reason ? ('tcp fallback (' + reason + ')') : 'tcp loopback lock' };
191
+ } catch (e) {
192
+ return { acquired: false, primitive: 'tcp', detail: 'another broker holds the tcp lock: ' + ((e && e.message) || 'unknown') };
193
+ }
194
+ }
195
+
196
+ module.exports = {
197
+ mutexName,
198
+ acquireMachineBrokerLock,
199
+ releaseMachineBrokerLock,
200
+ holdsMachineBrokerLock,
201
+ startMutexHolder,
202
+ };