@xkwdstore/agent 2.0.1 → 2.0.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.
@@ -1,149 +1,149 @@
1
- 'use strict';
2
-
3
- /**
4
- * Phase 11 — Per-user local process lock.
5
- *
6
- * Prevents two terminal processes from silently operating the same device
7
- * simultaneously. Uses a lock file under the standard runtime directory.
8
- *
9
- * The lock file contains:
10
- * { pid, startedAt, deviceId, deviceName }
11
- *
12
- * When another instance is running, shows a clear message.
13
- * Supports `--replace` for safe takeover.
14
- */
15
-
16
- const fs = require('fs');
17
- const path = require('path');
18
- const os = require('os');
19
- const { getDataDir } = require('./deviceKeyStore');
20
-
21
- // Defect 15 fix: Lock path is environment-overridable for test isolation.
22
- // Tests must NEVER write to the developer's actual XKWDStore application-data
23
- // directory. Set XKWDSTORE_LOCK_FILE to a temp path in tests.
24
- const LOCK_FILE = process.env.XKWDSTORE_LOCK_FILE || path.join(getDataDir(), 'agent.lock');
25
-
26
- /**
27
- * Read the current lock file.
28
- * Returns null if no lock exists or the lock is stale (PID not running).
29
- */
30
- function readLock() {
31
- if (!fs.existsSync(LOCK_FILE)) return null;
32
- try {
33
- const lock = JSON.parse(fs.readFileSync(LOCK_FILE, 'utf8'));
34
- if (!lock.pid) return null;
35
-
36
- // Check if the PID is still running
37
- if (!_isProcessRunning(lock.pid)) {
38
- // Stale lock — clean up
39
- try { fs.unlinkSync(LOCK_FILE); } catch {}
40
- return null;
41
- }
42
-
43
- return lock;
44
- } catch {
45
- // Corrupt lock file — clean up
46
- try { fs.unlinkSync(LOCK_FILE); } catch {}
47
- return null;
48
- }
49
- }
50
-
51
- /**
52
- * Acquire the process lock. Fails if another instance is running.
53
- *
54
- * @param {object} opts — { deviceId, deviceName }
55
- * @returns {boolean} true if acquired, false if another instance is running
56
- */
57
- function acquireLock(opts) {
58
- // Ensure data dir exists
59
- const dir = path.dirname(LOCK_FILE);
60
- if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
61
-
62
- const existing = readLock();
63
- if (existing) {
64
- return {
65
- acquired: false,
66
- existing,
67
- };
68
- }
69
-
70
- const lock = {
71
- pid: process.pid,
72
- startedAt: new Date().toISOString(),
73
- deviceId: (opts && opts.deviceId) || null,
74
- deviceName: (opts && opts.deviceName) || null,
75
- };
76
-
77
- fs.writeFileSync(LOCK_FILE, JSON.stringify(lock, null, 2), {
78
- encoding: 'utf8',
79
- mode: 0o600,
80
- });
81
-
82
- return { acquired: true };
83
- }
84
-
85
- /**
86
- * Request graceful shutdown of the existing process.
87
- * Sends SIGTERM to the existing PID and waits up to 10 seconds.
88
- *
89
- * @param {object} existingLock
90
- * @returns {boolean} true if the existing process stopped
91
- */
92
- async function requestTakeover(existingLock) {
93
- if (!existingLock || !existingLock.pid) return true;
94
-
95
- try {
96
- process.kill(existingLock.pid, 'SIGTERM');
97
- } catch {
98
- // Process may have already exited
99
- return true;
100
- }
101
-
102
- // Wait up to 10 seconds for the process to exit
103
- for (let i = 0; i < 100; i++) {
104
- await new Promise(resolve => setTimeout(resolve, 100));
105
- if (!_isProcessRunning(existingLock.pid)) {
106
- // Clean up the lock file
107
- try { fs.unlinkSync(LOCK_FILE); } catch {}
108
- return true;
109
- }
110
- }
111
-
112
- return false;
113
- }
114
-
115
- /**
116
- * Release the process lock (only if we own it).
117
- */
118
- function releaseLock() {
119
- try {
120
- if (!fs.existsSync(LOCK_FILE)) return;
121
- const lock = JSON.parse(fs.readFileSync(LOCK_FILE, 'utf8'));
122
- if (lock.pid === process.pid) {
123
- fs.unlinkSync(LOCK_FILE);
124
- }
125
- } catch {
126
- // Best effort
127
- }
128
- }
129
-
130
- /**
131
- * Check if a process with the given PID is running.
132
- */
133
- function _isProcessRunning(pid) {
134
- try {
135
- // Sending signal 0 checks if the process exists without actually sending a signal
136
- process.kill(pid, 0);
137
- return true;
138
- } catch {
139
- return false;
140
- }
141
- }
142
-
143
- module.exports = {
144
- readLock,
145
- acquireLock,
146
- requestTakeover,
147
- releaseLock,
148
- LOCK_FILE,
1
+ 'use strict';
2
+
3
+ /**
4
+ * Phase 11 — Per-user local process lock.
5
+ *
6
+ * Prevents two terminal processes from silently operating the same device
7
+ * simultaneously. Uses a lock file under the standard runtime directory.
8
+ *
9
+ * The lock file contains:
10
+ * { pid, startedAt, deviceId, deviceName }
11
+ *
12
+ * When another instance is running, shows a clear message.
13
+ * Supports `--replace` for safe takeover.
14
+ */
15
+
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+ const os = require('os');
19
+ const { getDataDir } = require('./deviceKeyStore');
20
+
21
+ // Defect 15 fix: Lock path is environment-overridable for test isolation.
22
+ // Tests must NEVER write to the developer's actual XKWDStore application-data
23
+ // directory. Set XKWDSTORE_LOCK_FILE to a temp path in tests.
24
+ const LOCK_FILE = process.env.XKWDSTORE_LOCK_FILE || path.join(getDataDir(), 'agent.lock');
25
+
26
+ /**
27
+ * Read the current lock file.
28
+ * Returns null if no lock exists or the lock is stale (PID not running).
29
+ */
30
+ function readLock() {
31
+ if (!fs.existsSync(LOCK_FILE)) return null;
32
+ try {
33
+ const lock = JSON.parse(fs.readFileSync(LOCK_FILE, 'utf8'));
34
+ if (!lock.pid) return null;
35
+
36
+ // Check if the PID is still running
37
+ if (!_isProcessRunning(lock.pid)) {
38
+ // Stale lock — clean up
39
+ try { fs.unlinkSync(LOCK_FILE); } catch {}
40
+ return null;
41
+ }
42
+
43
+ return lock;
44
+ } catch {
45
+ // Corrupt lock file — clean up
46
+ try { fs.unlinkSync(LOCK_FILE); } catch {}
47
+ return null;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Acquire the process lock. Fails if another instance is running.
53
+ *
54
+ * @param {object} opts — { deviceId, deviceName }
55
+ * @returns {boolean} true if acquired, false if another instance is running
56
+ */
57
+ function acquireLock(opts) {
58
+ // Ensure data dir exists
59
+ const dir = path.dirname(LOCK_FILE);
60
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
61
+
62
+ const existing = readLock();
63
+ if (existing) {
64
+ return {
65
+ acquired: false,
66
+ existing,
67
+ };
68
+ }
69
+
70
+ const lock = {
71
+ pid: process.pid,
72
+ startedAt: new Date().toISOString(),
73
+ deviceId: (opts && opts.deviceId) || null,
74
+ deviceName: (opts && opts.deviceName) || null,
75
+ };
76
+
77
+ fs.writeFileSync(LOCK_FILE, JSON.stringify(lock, null, 2), {
78
+ encoding: 'utf8',
79
+ mode: 0o600,
80
+ });
81
+
82
+ return { acquired: true };
83
+ }
84
+
85
+ /**
86
+ * Request graceful shutdown of the existing process.
87
+ * Sends SIGTERM to the existing PID and waits up to 10 seconds.
88
+ *
89
+ * @param {object} existingLock
90
+ * @returns {boolean} true if the existing process stopped
91
+ */
92
+ async function requestTakeover(existingLock) {
93
+ if (!existingLock || !existingLock.pid) return true;
94
+
95
+ try {
96
+ process.kill(existingLock.pid, 'SIGTERM');
97
+ } catch {
98
+ // Process may have already exited
99
+ return true;
100
+ }
101
+
102
+ // Wait up to 10 seconds for the process to exit
103
+ for (let i = 0; i < 100; i++) {
104
+ await new Promise(resolve => setTimeout(resolve, 100));
105
+ if (!_isProcessRunning(existingLock.pid)) {
106
+ // Clean up the lock file
107
+ try { fs.unlinkSync(LOCK_FILE); } catch {}
108
+ return true;
109
+ }
110
+ }
111
+
112
+ return false;
113
+ }
114
+
115
+ /**
116
+ * Release the process lock (only if we own it).
117
+ */
118
+ function releaseLock() {
119
+ try {
120
+ if (!fs.existsSync(LOCK_FILE)) return;
121
+ const lock = JSON.parse(fs.readFileSync(LOCK_FILE, 'utf8'));
122
+ if (lock.pid === process.pid) {
123
+ fs.unlinkSync(LOCK_FILE);
124
+ }
125
+ } catch {
126
+ // Best effort
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Check if a process with the given PID is running.
132
+ */
133
+ function _isProcessRunning(pid) {
134
+ try {
135
+ // Sending signal 0 checks if the process exists without actually sending a signal
136
+ process.kill(pid, 0);
137
+ return true;
138
+ } catch {
139
+ return false;
140
+ }
141
+ }
142
+
143
+ module.exports = {
144
+ readLock,
145
+ acquireLock,
146
+ requestTakeover,
147
+ releaseLock,
148
+ LOCK_FILE,
149
149
  };