@xkwdstore/agent 2.0.2 → 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.
package/src/cli.js CHANGED
@@ -1,529 +1,665 @@
1
- #!/usr/bin/env node
2
- 'use strict';
3
-
4
- /**
5
- * XKWDStore Agent — Terminal-only CLI (protocol v2).
6
- *
7
- * Replaces the desktop-agent distribution, pairing-code workflow, updater,
8
- * and in-memory WebSocket ticket architecture with a simpler, safer
9
- * terminal-first system.
10
- *
11
- * Usage:
12
- * npx --yes @xkwdstore/agent@<PINNED_VERSION> start
13
- * npx --yes @xkwdstore/agent@<PINNED_VERSION> status
14
- * npx --yes @xkwdstore/agent@<PINNED_VERSION> logout
15
- * npx --yes @xkwdstore/agent@<PINNED_VERSION> revoke-local
16
- * npx --yes @xkwdstore/agent@<PINNED_VERSION> doctor
17
- * npx --yes @xkwdstore/agent@<PINNED_VERSION> version
18
- *
19
- * The agent runs only while the terminal process is running.
20
- * Closing the terminal or pressing Ctrl+C stops the agent cleanly.
21
- */
22
-
23
- const crypto = require('crypto');
24
- const os = require('os');
25
- const path = require('path');
26
-
27
- const CLI_VERSION = '2.0.2';
28
- const PROTOCOL_VERSION = 2;
29
-
30
- // ── Command parsing ──────────────────────────────────────────────────────────
31
-
32
- function main() {
33
- const args = process.argv.slice(2);
34
- const command = args[0] || 'help';
35
- const flags = {};
36
- const positional = [];
37
-
38
- for (let i = 1; i < args.length; i++) {
39
- const arg = args[i];
40
- if (arg.startsWith('--')) {
41
- const key = arg.slice(2);
42
- const next = args[i + 1];
43
- if (next && !next.startsWith('--')) {
44
- flags[key] = next;
45
- i++;
46
- } else {
47
- flags[key] = true;
48
- }
49
- } else {
50
- positional.push(arg);
51
- }
52
- }
53
-
54
- const serverOrigin = flags.server ||
55
- process.env.XKWDSTORE_SERVER ||
56
- 'https://x.kwdstore.com';
57
-
58
- switch (command) {
59
- case 'start':
60
- return start(serverOrigin, flags);
61
- case 'status':
62
- return status();
63
- case 'logout':
64
- return logout();
65
- case 'revoke-local':
66
- return revokeLocal();
67
- case 'doctor':
68
- return doctor(serverOrigin);
69
- case 'version':
70
- return version();
71
- case 'help':
72
- case '--help':
73
- case '-h':
74
- default:
75
- return help();
76
- }
77
- }
78
-
79
- // ── Commands ─────────────────────────────────────────────────────────────────
80
-
81
- /**
82
- * `xkwd-agent start` — the main runtime command.
83
- */
84
- async function start(serverOrigin, flags) {
85
- console.log(`XKWDStore Agent v${CLI_VERSION} (protocol v${PROTOCOL_VERSION})`);
86
- console.log(`Server: ${serverOrigin}`);
87
- console.log();
88
-
89
- // 1. Detect OS and architecture (for display)
90
- const platform = os.platform();
91
- const arch = os.arch();
92
- const hostname = os.hostname();
93
- console.log(`✓ Detected computer: ${hostname}`);
94
- console.log(`✓ Platform: ${platform} ${arch}`);
95
-
96
- // 2. Resolve system Chrome (fail clearly if missing)
97
- const { resolveChromeOrFail } = require('./chromeDetector');
98
- let chromePath, chromeVersion;
99
- try {
100
- const chrome = resolveChromeOrFail();
101
- chromePath = chrome.chromePath;
102
- chromeVersion = chrome.chromeVersion;
103
- console.log(`✓ Chrome ${chromeVersion || 'detected'}: ${chromePath}`);
104
- } catch (e) {
105
- console.error(e.message);
106
- process.exit(1);
107
- }
108
-
109
- // 3. Check compatibility with server (shared strict validator)
110
- const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
111
- try {
112
- const compatResp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
113
- const compat = validateCompatibilityResponse(compatResp);
114
- if (compat.html) {
115
- console.error('\n' + COMPAT_HTML_MESSAGE);
116
- process.exit(1);
117
- }
118
- if (!compat.ok) {
119
- console.error('\nServer compatibility check failed: ' + compat.reason + '.');
120
- console.error('The agent will not start enrollment until the server is compatible.');
121
- process.exit(1);
122
- }
123
- // compat.ok — enforce minimum agent version
124
- const minVer = compat.body.minimumAgentVersion;
125
- const recVer = compat.body.recommendedAgentVersion;
126
- if (minVer && _compareVersions(CLI_VERSION, minVer) < 0) {
127
- console.error(`\nThis agent version (${CLI_VERSION}) is no longer supported.`);
128
- console.error(`\nRun:\n\n npx --yes @xkwdstore/agent@${recVer} start\n`);
129
- process.exit(1);
130
- }
131
- } catch (e) {
132
- console.error(`\nServer compatibility check failed: ${e.message}`);
133
- console.error('The agent will not start enrollment until the server is reachable and compatible.');
134
- process.exit(1);
135
- }
136
-
137
- // 4. Load or generate device key
138
- const { getStoredDevice, getStoredPrivateKey, enroll } = require('./enrollmentClient');
139
- const { isSecureStorageAvailable } = require('./deviceKeyStore');
140
-
141
- if (!isSecureStorageAvailable()) {
142
- console.error('Secure key storage is unavailable on this system.');
143
- if (os.platform() === 'win32') {
144
- console.error('On Windows, ensure System32\\WindowsPowerShell\\v1.0\\powershell.exe is present and DPAPI is available.');
145
- } else {
146
- console.error('On Linux, install gnome-keyring or seahorse (libsecret).');
147
- }
148
- console.error('The agent cannot run without secure key storage.');
149
- process.exit(1);
150
- }
151
-
152
- let deviceMeta = getStoredDevice();
153
- let privateKeyB64Url = await getStoredPrivateKey();
154
-
155
- // 5. Authorize the device when needed (first run or revoked)
156
- if (!deviceMeta || !privateKeyB64Url) {
157
- console.log('\n✓ Device identity loaded securely');
158
- try {
159
- const result = await enroll(serverOrigin, { chromePath });
160
- deviceMeta = require('./deviceKeyStore').loadMetadata();
161
- privateKeyB64Url = await getStoredPrivateKey();
162
- } catch (e) {
163
- console.error(`\nEnrollment failed: ${e.message}`);
164
- process.exit(1);
165
- }
166
- } else {
167
- console.log(`✓ Device identity loaded securely`);
168
- console.log(`✓ Device recognized: ${deviceMeta.deviceName}`);
169
- }
170
-
171
- // 6. Process lock (prevent duplicate instances)
172
- const processLock = require('./processLock');
173
- const lockResult = processLock.acquireLock({
174
- deviceId: deviceMeta.deviceId,
175
- deviceName: deviceMeta.deviceName,
176
- });
177
-
178
- if (!lockResult.acquired) {
179
- if (flags.replace) {
180
- console.log('\nAnother agent instance is running. Requesting takeover...');
181
- const took = await processLock.requestTakeover(lockResult.existing);
182
- if (!took) {
183
- console.error('Could not stop the existing instance. Please close it manually.');
184
- process.exit(1);
185
- }
186
- // Re-acquire the lock
187
- const retryLock = processLock.acquireLock({
188
- deviceId: deviceMeta.deviceId,
189
- deviceName: deviceMeta.deviceName,
190
- });
191
- if (!retryLock.acquired) {
192
- console.error('Could not acquire process lock after takeover.');
193
- process.exit(1);
194
- }
195
- } else {
196
- console.error('\nXKWDStore Agent is already running on this computer.');
197
- console.error(`PID: ${lockResult.existing.pid}`);
198
- console.error(`Started: ${lockResult.existing.startedAt}`);
199
- console.error(`Device: ${lockResult.existing.deviceName || 'unknown'}`);
200
- console.error('\nTo replace the running instance, use:');
201
- console.error(' xkwd-agent start --replace');
202
- process.exit(1);
203
- }
204
- }
205
-
206
- // 7. Connect securely via WebSocket challenge-response
207
- const { connectWebSocket } = require('./wsClient');
208
- let ws;
209
- try {
210
- ws = await connectWebSocket({
211
- serverOrigin,
212
- deviceId: deviceMeta.deviceId,
213
- publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
214
- privateKeyB64Url,
215
- protocolVersion: PROTOCOL_VERSION,
216
- });
217
- } catch (e) {
218
- console.error(`\nConnection failed: ${e.message}`);
219
- processLock.releaseLock();
220
- process.exit(1);
221
- }
222
-
223
- console.log('✓ Secure challenge passed');
224
- console.log('✓ Connected');
225
- console.log('\nAgent is running. Press Ctrl+C to stop.\n');
226
-
227
- // 8. Set up browser session handler (delegates to existing session management)
228
- const { setupSessionHandler, closeAllSessions, markDisconnected } = require('./sessionHandler');
229
- const sessions = setupSessionHandler(ws, { chromePath, deviceMeta, serverOrigin });
230
-
231
- // 8a. Fail-safe: an authenticated WebSocket closure is not a recoverable
232
- // event in this release. The agent must stop accepting commands, close every
233
- // active browser context (preserving profiles/cookies via the existing
234
- // safe persistence path), clear the sessions map, release the process
235
- // lock, print a clear terminal error, and exit non-zero. We deliberately
236
- // prefer a safe exit over incomplete automatic reconnection here; a future
237
- // reconnect implementation is allowed only if it rebinds the full session
238
- // handler, reconciles every lease, and is covered by deterministic tests.
239
- //
240
- // Race guard: `shuttingDown` is set by the deliberate Ctrl+C/SIGTERM path
241
- // BEFORE ws.close() is called, so the close event emitted during a
242
- // deliberate shutdown does NOT run the unexpected-disconnect fail-safe.
243
- // This prevents closeAllSessions() from being executed concurrently twice
244
- // and processLock.releaseLock() from being called twice.
245
- let disconnected = false;
246
- let shuttingDown = false;
247
- ws.on('close', (code, reason) => {
248
- // If a deliberate shutdown is in progress, the close event is expected —
249
- // do NOT run the unexpected-disconnect fail-safe.
250
- if (shuttingDown) return;
251
- if (disconnected) return;
252
- disconnected = true;
253
- markDisconnected();
254
- const reasonStr = reason ? reason.toString() : '';
255
- console.error(`\n✗ Connection to server lost (code ${code}${reasonStr ? ': ' + reasonStr : ''}).`);
256
- console.error(' Closing all browser sessions and shutting down safely...');
257
- closeAllSessions().then(({ closed }) => {
258
- if (closed > 0) console.error(` Closed ${closed} browser session(s).`);
259
- }).catch(() => {}).finally(() => {
260
- try { ws.close(1000, 'Agent shutting down after disconnect'); } catch {}
261
- processLock.releaseLock();
262
- // 4003 = authentication failed (revoked/unknown key) — re-enroll required.
263
- if (code === 4003) {
264
- console.error('\n❌ Authentication failed. This device may be revoked.');
265
- console.error(' Run `xkwd-agent logout` then `xkwd-agent start` to re-authorize.');
266
- } else {
267
- console.error('\nTo reconnect, run `xkwd-agent start` again.');
268
- }
269
- console.error('Agent stopped.');
270
- process.exit(1);
271
- });
272
- });
273
-
274
- // 9. Clean shutdown on Ctrl+C
275
- async function shutdown(signal) {
276
- if (shuttingDown) return;
277
- shuttingDown = true;
278
- console.log(`\n${signal} received. Shutting down...`);
279
-
280
- // Stop accepting commands immediately.
281
- markDisconnected();
282
-
283
- // Close all browser sessions (preserves profiles/cookies via the
284
- // existing safe persistence path).
285
- try {
286
- await closeAllSessions();
287
- } catch {}
288
-
289
- // Close WebSocket
290
- try { ws.close(1000, 'Agent shutting down'); } catch {}
291
-
292
- // Release lock
293
- processLock.releaseLock();
294
-
295
- process.exit(0);
296
- }
297
-
298
- process.on('SIGINT', () => shutdown('Ctrl+C'));
299
- process.on('SIGTERM', () => shutdown('SIGTERM'));
300
- process.on('SIGHUP', () => shutdown('SIGHUP'));
301
-
302
- // Also release the lock on uncaught exceptions
303
- process.on('uncaughtException', (err) => {
304
- console.error('Uncaught error:', err.message);
305
- processLock.releaseLock();
306
- process.exit(1);
307
- });
308
- }
309
-
310
- /**
311
- * `xkwd-agent status` — show device and connection status.
312
- */
313
- function status() {
314
- const { getStoredDevice } = require('./enrollmentClient');
315
- const { isSecureStorageAvailable } = require('./deviceKeyStore');
316
- const processLock = require('./processLock');
317
-
318
- const device = getStoredDevice();
319
- const lock = processLock.readLock();
320
-
321
- console.log(`XKWDStore Agent v${CLI_VERSION}\n`);
322
-
323
- if (!device) {
324
- console.log('Status: Not authorized');
325
- console.log('Run `xkwd-agent start` to authorize this computer.');
326
- return;
327
- }
328
-
329
- console.log(`Device ID: ${device.deviceId}`);
330
- console.log(`Device name: ${device.deviceName}`);
331
- console.log(`Server: ${device.serverOrigin || 'https://x.kwdstore.com'}`);
332
- console.log(`Public-key fingerprint: ${device.publicKeyFingerprint.slice(0, 8)}…${device.publicKeyFingerprint.slice(-8)}`);
333
- console.log(`Created: ${device.createdAt || 'unknown'}`);
334
- console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available' : 'unavailable'}`);
335
-
336
- if (lock) {
337
- console.log(`\nAgent process: RUNNING (PID ${lock.pid})`);
338
- console.log(`Started: ${lock.startedAt}`);
339
- } else {
340
- console.log('\nAgent process: not running');
341
- }
342
- }
343
-
344
- /**
345
- * `xkwd-agent logout` — delete local device identity (re-enrollment required).
346
- */
347
- async function logout() {
348
- const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
349
- const processLock = require('./processLock');
350
-
351
- const lock = processLock.readLock();
352
- if (lock) {
353
- console.error('Agent is currently running. Stop it first with Ctrl+C.');
354
- process.exit(1);
355
- }
356
-
357
- await deletePrivateKey();
358
- deleteMetadata();
359
- console.log('Local device identity deleted.');
360
- console.log('Run `xkwd-agent start` to re-authorize this computer.');
361
- }
362
-
363
- /**
364
- * `xkwd-agent revoke-local` — same as logout but also clears the process lock.
365
- */
366
- async function revokeLocal() {
367
- const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
368
- await deletePrivateKey();
369
- deleteMetadata();
370
- console.log('Local device identity and credentials revoked.');
371
- console.log('The server-side device record should also be revoked from the dashboard.');
372
- }
373
-
374
- /**
375
- * `xkwd-agent doctor` — diagnostic checks.
376
- */
377
- async function doctor(serverOrigin) {
378
- console.log(`XKWDStore Agent v${CLI_VERSION} — Diagnostics\n`);
379
-
380
- // Check Node version
381
- const nodeVersion = process.versions.node;
382
- const major = parseInt(nodeVersion.split('.')[0], 10);
383
- console.log(`Node.js: ${nodeVersion} ${major >= 22 ? '✓' : '✗ (requires Node.js 22+)'}`);
384
-
385
- // Check platform
386
- console.log(`Platform: ${os.platform()} ${os.arch()}`);
387
- console.log(`Hostname: ${os.hostname()}`);
388
-
389
- // Check Chrome
390
- try {
391
- const { resolveChromeOrFail } = require('./chromeDetector');
392
- const chrome = resolveChromeOrFail();
393
- console.log(`Chrome: ${chrome.chromeVersion || 'detected'} ✓`);
394
- } catch (e) {
395
- console.log(`Chrome: ✗ (${e.message.split('\n')[0]})`);
396
- }
397
-
398
- // Check secure storage (real DPAPI + ACL probe on Windows)
399
- const { isSecureStorageAvailable, getDataDir, probeWindowsStorage } = require('./deviceKeyStore');
400
- const platform = os.platform();
401
- if (platform === 'win32') {
402
- console.log('Secure storage: probing real DPAPI + ACL stages...');
403
- const probe = probeWindowsStorage();
404
- console.log(` DPAPI Protect : ${probe.stages.protect ? '✓' : '✗'}`);
405
- console.log(` DPAPI Unprotect: ${probe.stages.unprotect ? '✓' : '✗'}`);
406
- console.log(` Windows SID : ${probe.stages.sidLookup ? '✓' : '✗'}`);
407
- console.log(` ACL apply : ${probe.stages.aclApply ? '✓' : '✗'}`);
408
- console.log(` ACL verify : ${probe.stages.aclVerify ? '✓' : '✗'}`);
409
- console.log(`Secure storage: ${probe.ok ? 'available ✓' : 'unavailable ✗'}`);
410
- if (!probe.ok && probe.detail) {
411
- console.log(` Detail: ${probe.detail}`);
412
- }
413
- } else {
414
- console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available ✓' : 'unavailable ✗'}`);
415
- }
416
-
417
- // Check data directory
418
- const dataDir = getDataDir();
419
- console.log(`Data directory: ${dataDir}`);
420
-
421
- // Check device identity
422
- const { getStoredDevice, getStoredPrivateKey } = require('./enrollmentClient');
423
- const device = getStoredDevice();
424
- if (device) {
425
- console.log(`Device ID: ${device.deviceId} ✓`);
426
- const privateKey = await getStoredPrivateKey();
427
- console.log(`Private key: ${privateKey ? 'stored ✓' : 'missing ✗'}`);
428
- } else {
429
- console.log('Device ID: not enrolled');
430
- }
431
-
432
- // Check server connectivity (shared strict validator)
433
- try {
434
- const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
435
- const resp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
436
- const compat = validateCompatibilityResponse(resp);
437
- if (compat.html) {
438
- console.log(`Server (${serverOrigin}): compatibility endpoint returned frontend ✗`);
439
- console.log(' ' + COMPAT_HTML_MESSAGE);
440
- } else if (compat.ok) {
441
- console.log(`Server (${serverOrigin}): reachable ✓`);
442
- console.log(` Protocol version: ${compat.body.protocolVersion}`);
443
- console.log(` Min agent version: ${compat.body.minimumAgentVersion}`);
444
- console.log(` Recommended agent version: ${compat.body.recommendedAgentVersion}`);
445
- } else {
446
- console.log(`Server (${serverOrigin}): compatibility check failed ✗`);
447
- console.log(` Reason: ${compat.reason}`);
448
- }
449
- } catch (e) {
450
- console.log(`Server (${serverOrigin}): unreachable ✗ (${e.message})`);
451
- }
452
- }
453
-
454
- /**
455
- * `xkwd-agent version` — print version.
456
- */
457
- function version() {
458
- console.log(`@xkwdstore/agent v${CLI_VERSION}`);
459
- console.log(`Protocol version: ${PROTOCOL_VERSION}`);
460
- console.log(`Node.js: ${process.versions.node}`);
461
- }
462
-
463
- /**
464
- * `xkwd-agent help` — print help.
465
- */
466
- function help() {
467
- console.log(`XKWDStore Agent v${CLI_VERSION}
468
-
469
- Usage:
470
- xkwd-agent <command> [options]
471
-
472
- Commands:
473
- start Start the agent (connects to server, runs browser sessions)
474
- status Show device and connection status
475
- logout Delete local device identity (requires re-authorization)
476
- revoke-local Delete local device identity and credentials
477
- doctor Run diagnostic checks
478
- version Print version information
479
- help Show this help
480
-
481
- Options:
482
- --server=<url> Server URL (default: https://x.kwdstore.com)
483
- --replace Replace a running instance (safe takeover)
484
-
485
- Examples:
486
- xkwd-agent start
487
- xkwd-agent start --replace
488
- xkwd-agent status
489
- xkwd-agent doctor
490
-
491
- First run:
492
- The agent will open your browser to authorize this computer.
493
- No pairing code, email, or API key is required.
494
-
495
- To stop:
496
- Press Ctrl+C in the terminal.
497
-
498
- Data location:
499
- Windows: %LOCALAPPDATA%\\XKWDStore\\
500
- macOS: ~/Library/Application Support/XKWDStore/
501
- Linux: ~/.local/share/xkwdstore/
502
-
503
- Requirements:
504
- - Node.js 22 or later
505
- - Google Chrome installed
506
- `);
507
- }
508
-
509
- // ── Helpers ──────────────────────────────────────────────────────────────────
510
-
511
- function _compareVersions(a, b) {
512
- const pa = a.split('.').map(Number);
513
- const pb = b.split('.').map(Number);
514
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
515
- const va = pa[i] || 0;
516
- const vb = pb[i] || 0;
517
- if (va > vb) return 1;
518
- if (va < vb) return -1;
519
- }
520
- return 0;
521
- }
522
-
523
- // ── Entry point ──────────────────────────────────────────────────────────────
524
-
525
- if (require.main === module) {
526
- main();
527
- }
528
-
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * XKWDStore Agent — Terminal-only CLI (protocol v2).
6
+ *
7
+ * Replaces the desktop-agent distribution, pairing-code workflow, updater,
8
+ * and in-memory WebSocket ticket architecture with a simpler, safer
9
+ * terminal-first system.
10
+ *
11
+ * Usage:
12
+ * npx --yes @xkwdstore/agent@<PINNED_VERSION> start
13
+ * npx --yes @xkwdstore/agent@<PINNED_VERSION> status
14
+ * npx --yes @xkwdstore/agent@<PINNED_VERSION> logout
15
+ * npx --yes @xkwdstore/agent@<PINNED_VERSION> revoke-local
16
+ * npx --yes @xkwdstore/agent@<PINNED_VERSION> doctor
17
+ * npx --yes @xkwdstore/agent@<PINNED_VERSION> version
18
+ *
19
+ * The agent runs only while the terminal process is running.
20
+ * Closing the terminal or pressing Ctrl+C stops the agent cleanly.
21
+ */
22
+
23
+ const crypto = require('crypto');
24
+ const os = require('os');
25
+ const path = require('path');
26
+
27
+ const CLI_VERSION = '2.0.3';
28
+ const PROTOCOL_VERSION = 2;
29
+
30
+ // ── Command parsing ──────────────────────────────────────────────────────────
31
+
32
+ function main() {
33
+ const args = process.argv.slice(2);
34
+ const command = args[0] || 'help';
35
+ const flags = {};
36
+ const positional = [];
37
+
38
+ for (let i = 1; i < args.length; i++) {
39
+ const arg = args[i];
40
+ if (arg.startsWith('--')) {
41
+ const key = arg.slice(2);
42
+ const next = args[i + 1];
43
+ if (next && !next.startsWith('--')) {
44
+ flags[key] = next;
45
+ i++;
46
+ } else {
47
+ flags[key] = true;
48
+ }
49
+ } else {
50
+ positional.push(arg);
51
+ }
52
+ }
53
+
54
+ const serverOrigin = flags.server ||
55
+ process.env.XKWDSTORE_SERVER ||
56
+ 'https://x.kwdstore.com';
57
+
58
+ switch (command) {
59
+ case 'start':
60
+ return start(serverOrigin, flags);
61
+ case 'status':
62
+ return status();
63
+ case 'logout':
64
+ return logout();
65
+ case 'revoke-local':
66
+ return revokeLocal();
67
+ case 'doctor':
68
+ return doctor(serverOrigin);
69
+ case 'version':
70
+ return version();
71
+ case 'help':
72
+ case '--help':
73
+ case '-h':
74
+ default:
75
+ return help();
76
+ }
77
+ }
78
+
79
+ // ── Commands ─────────────────────────────────────────────────────────────────
80
+
81
+ /**
82
+ * `xkwd-agent start` — the main runtime command.
83
+ */
84
+ async function start(serverOrigin, flags) {
85
+ console.log(`XKWDStore Agent v${CLI_VERSION} (protocol v${PROTOCOL_VERSION})`);
86
+ console.log(`Server: ${serverOrigin}`);
87
+ console.log();
88
+
89
+ // 1. Detect OS and architecture (for display)
90
+ const platform = os.platform();
91
+ const arch = os.arch();
92
+ const hostname = os.hostname();
93
+ console.log(`✓ Detected computer: ${hostname}`);
94
+ console.log(`✓ Platform: ${platform} ${arch}`);
95
+
96
+ // 2. Resolve system Chrome (fail clearly if missing)
97
+ const { resolveChromeOrFail } = require('./chromeDetector');
98
+ let chromePath, chromeVersion;
99
+ try {
100
+ const chrome = resolveChromeOrFail();
101
+ chromePath = chrome.chromePath;
102
+ chromeVersion = chrome.chromeVersion;
103
+ console.log(`✓ Chrome ${chromeVersion || 'detected'}: ${chromePath}`);
104
+ } catch (e) {
105
+ console.error(e.message);
106
+ process.exit(1);
107
+ }
108
+
109
+ // 3. Check compatibility with server (shared strict validator)
110
+ const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
111
+ try {
112
+ const compatResp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
113
+ const compat = validateCompatibilityResponse(compatResp);
114
+ if (compat.html) {
115
+ console.error('\n' + COMPAT_HTML_MESSAGE);
116
+ process.exit(1);
117
+ }
118
+ if (!compat.ok) {
119
+ console.error('\nServer compatibility check failed: ' + compat.reason + '.');
120
+ console.error('The agent will not start enrollment until the server is compatible.');
121
+ process.exit(1);
122
+ }
123
+ // compat.ok — enforce minimum agent version
124
+ const minVer = compat.body.minimumAgentVersion;
125
+ const recVer = compat.body.recommendedAgentVersion;
126
+ if (minVer && _compareVersions(CLI_VERSION, minVer) < 0) {
127
+ console.error(`\nThis agent version (${CLI_VERSION}) is no longer supported.`);
128
+ console.error(`\nRun:\n\n npx --yes @xkwdstore/agent@${recVer} start\n`);
129
+ process.exit(1);
130
+ }
131
+ } catch (e) {
132
+ console.error(`\nServer compatibility check failed: ${e.message}`);
133
+ console.error('The agent will not start enrollment until the server is reachable and compatible.');
134
+ process.exit(1);
135
+ }
136
+
137
+ // 4. Load or generate device key (server-scoped: per-server identity)
138
+ const { getStoredDevice, getStoredPrivateKey, enroll } = require('./enrollmentClient');
139
+ const { isSecureStorageAvailable } = require('./deviceKeyStore');
140
+
141
+ if (!isSecureStorageAvailable()) {
142
+ console.error('Secure key storage is unavailable on this system.');
143
+ if (os.platform() === 'win32') {
144
+ console.error('On Windows, ensure System32\\WindowsPowerShell\\v1.0\\powershell.exe is present and DPAPI is available.');
145
+ } else {
146
+ console.error('On Linux, install gnome-keyring or seahorse (libsecret).');
147
+ }
148
+ console.error('The agent cannot run without secure key storage.');
149
+ process.exit(1);
150
+ }
151
+
152
+ let deviceMeta = getStoredDevice({ serverOrigin });
153
+ let privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
154
+
155
+ // 5. Authorize the device when needed (first run or revoked)
156
+ if (!deviceMeta || !privateKeyB64Url) {
157
+ console.log('\n✓ Device identity loaded securely');
158
+ try {
159
+ const result = await enroll(serverOrigin, { chromePath });
160
+ deviceMeta = require('./deviceKeyStore').loadMetadata({ serverOrigin });
161
+ privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
162
+ } catch (e) {
163
+ console.error(`\nEnrollment failed: ${e.message}`);
164
+ process.exit(1);
165
+ }
166
+ } else {
167
+ console.log(`✓ Device identity loaded securely`);
168
+ console.log(`✓ Device recognized: ${deviceMeta.deviceName}`);
169
+ }
170
+
171
+ // 6. Process lock (prevent duplicate instances)
172
+ const processLock = require('./processLock');
173
+ const lockResult = processLock.acquireLock({
174
+ deviceId: deviceMeta.deviceId,
175
+ deviceName: deviceMeta.deviceName,
176
+ });
177
+
178
+ if (!lockResult.acquired) {
179
+ if (flags.replace) {
180
+ console.log('\nAnother agent instance is running. Requesting takeover...');
181
+ const took = await processLock.requestTakeover(lockResult.existing);
182
+ if (!took) {
183
+ console.error('Could not stop the existing instance. Please close it manually.');
184
+ process.exit(1);
185
+ }
186
+ // Re-acquire the lock
187
+ const retryLock = processLock.acquireLock({
188
+ deviceId: deviceMeta.deviceId,
189
+ deviceName: deviceMeta.deviceName,
190
+ });
191
+ if (!retryLock.acquired) {
192
+ console.error('Could not acquire process lock after takeover.');
193
+ process.exit(1);
194
+ }
195
+ } else {
196
+ console.error('\nXKWDStore Agent is already running on this computer.');
197
+ console.error(`PID: ${lockResult.existing.pid}`);
198
+ console.error(`Started: ${lockResult.existing.startedAt}`);
199
+ console.error(`Device: ${lockResult.existing.deviceName || 'unknown'}`);
200
+ console.error('\nTo replace the running instance, use:');
201
+ console.error(' xkwd-agent start --replace');
202
+ process.exit(1);
203
+ }
204
+ }
205
+
206
+ // 7. Connect securely via WebSocket challenge-response
207
+ // 4003 auto-recovery: if the initial connection fails with 4003 (revoked/
208
+ // unknown device), the agent automatically performs a server-scoped
209
+ // re-enrollment and reconnects in the SAME process flow — the user does
210
+ // NOT need to type a second command. Only ONE auto-recovery attempt is
211
+ // allowed per startup to prevent infinite loops.
212
+ const { connectWebSocket } = require('./wsClient');
213
+ let ws;
214
+ let autoRecovered = false;
215
+
216
+ try {
217
+ ws = await connectWebSocket({
218
+ serverOrigin,
219
+ deviceId: deviceMeta.deviceId,
220
+ publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
221
+ privateKeyB64Url,
222
+ protocolVersion: PROTOCOL_VERSION,
223
+ });
224
+ } catch (connectErr) {
225
+ // Check if this is a 4003 authentication failure (revoked/unknown device).
226
+ // The wsClient rejects with a message containing "Device authentication
227
+ // failed" for 4003 close codes, or the error may carry a .code property.
228
+ const isAuthFailure = _is4003Error(connectErr);
229
+
230
+ if (isAuthFailure && !autoRecovered) {
231
+ autoRecovered = true;
232
+ console.error('\n❌ Authentication failed (4003) — this device may be revoked.');
233
+ console.error(' Automatically re-authorizing for ' + serverOrigin + '...');
234
+ console.error(' (Other servers\' identities are NOT affected.)');
235
+
236
+ // Release the lock before re-enrollment (enrollment opens a browser)
237
+ processLock.releaseLock();
238
+
239
+ // Delete only this server's identity
240
+ const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
241
+ await deletePrivateKey({ serverOrigin });
242
+ deleteMetadata({ serverOrigin });
243
+ console.error('✓ Old identity cleared for ' + serverOrigin);
244
+
245
+ // Re-enroll automatically (opens browser for approval)
246
+ console.log('\nOpening authorization page...');
247
+ try {
248
+ await enroll(serverOrigin, { chromePath });
249
+ deviceMeta = require('./deviceKeyStore').loadMetadata({ serverOrigin });
250
+ privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
251
+
252
+ if (!deviceMeta || !privateKeyB64Url) {
253
+ console.error('\n❌ Re-enrollment completed but identity could not be loaded.');
254
+ process.exit(1);
255
+ }
256
+ console.log('✓ New identity stored for ' + serverOrigin);
257
+ } catch (enrollErr) {
258
+ console.error(`\n❌ Automatic re-enrollment failed: ${enrollErr.message}`);
259
+ console.error(' Run `xkwd-agent start` again to retry manually.');
260
+ process.exit(1);
261
+ }
262
+
263
+ // Re-acquire the process lock with the new device identity
264
+ const retryLock = processLock.acquireLock({
265
+ deviceId: deviceMeta.deviceId,
266
+ deviceName: deviceMeta.deviceName,
267
+ });
268
+ if (!retryLock.acquired) {
269
+ console.error('Could not acquire process lock after re-enrollment.');
270
+ if (flags.replace) {
271
+ const took = await processLock.requestTakeover(retryLock.existing);
272
+ if (!took) {
273
+ console.error('Could not stop the existing instance. Please close it manually.');
274
+ process.exit(1);
275
+ }
276
+ } else {
277
+ process.exit(1);
278
+ }
279
+ }
280
+
281
+ // Attempt to reconnect with the new identity (only ONE retry)
282
+ try {
283
+ ws = await connectWebSocket({
284
+ serverOrigin,
285
+ deviceId: deviceMeta.deviceId,
286
+ publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
287
+ privateKeyB64Url,
288
+ protocolVersion: PROTOCOL_VERSION,
289
+ });
290
+ console.log('\n✓ Re-authorized and reconnected automatically.');
291
+ } catch (retryErr) {
292
+ if (_is4003Error(retryErr)) {
293
+ console.error('\n❌ Authentication failed again after re-enrollment.');
294
+ console.error(' The new device may not have been approved on the dashboard.');
295
+ console.error(' Run `xkwd-agent start` again after approving the device.');
296
+ } else {
297
+ console.error(`\n❌ Reconnection failed: ${retryErr.message}`);
298
+ console.error(' Run `xkwd-agent start` again to retry.');
299
+ }
300
+ processLock.releaseLock();
301
+ process.exit(1);
302
+ }
303
+ } else {
304
+ // Non-4003 error, or 4003 after auto-recovery already attempted
305
+ console.error(`\nConnection failed: ${connectErr.message}`);
306
+ if (isAuthFailure) {
307
+ console.error(' Automatic recovery was already attempted. Run `xkwd-agent start` again.');
308
+ }
309
+ processLock.releaseLock();
310
+ process.exit(1);
311
+ }
312
+ }
313
+
314
+ console.log('✓ Secure challenge passed');
315
+ console.log('✓ Connected');
316
+ console.log('\nAgent is running. Press Ctrl+C to stop.\n');
317
+
318
+ // 8. Set up browser session handler (delegates to existing session management)
319
+ const { setupSessionHandler, closeAllSessions, markDisconnected } = require('./sessionHandler');
320
+ const sessions = setupSessionHandler(ws, { chromePath, deviceMeta, serverOrigin });
321
+
322
+ // 8a. Fail-safe: an authenticated WebSocket closure is not a recoverable
323
+ // event in this release. The agent must stop accepting commands, close every
324
+ // active browser context (preserving profiles/cookies via the existing
325
+ // safe persistence path), clear the sessions map, release the process
326
+ // lock, print a clear terminal error, and exit non-zero. We deliberately
327
+ // prefer a safe exit over incomplete automatic reconnection here; a future
328
+ // reconnect implementation is allowed only if it rebinds the full session
329
+ // handler, reconciles every lease, and is covered by deterministic tests.
330
+ //
331
+ // Race guard: `shuttingDown` is set by the deliberate Ctrl+C/SIGTERM path
332
+ // BEFORE ws.close() is called, so the close event emitted during a
333
+ // deliberate shutdown does NOT run the unexpected-disconnect fail-safe.
334
+ // This prevents closeAllSessions() from being executed concurrently twice
335
+ // and processLock.releaseLock() from being called twice.
336
+ let disconnected = false;
337
+ let shuttingDown = false;
338
+ ws.on('close', (code, reason) => {
339
+ // If a deliberate shutdown is in progress, the close event is expected —
340
+ // do NOT run the unexpected-disconnect fail-safe.
341
+ if (shuttingDown) return;
342
+ if (disconnected) return;
343
+ disconnected = true;
344
+ markDisconnected();
345
+ const reasonStr = reason ? reason.toString() : '';
346
+ console.error(`\n✗ Connection to server lost (code ${code}${reasonStr ? ': ' + reasonStr : ''}).`);
347
+ console.error(' Closing all browser sessions and shutting down safely...');
348
+
349
+ // 4003 = authentication failed (revoked/unknown key). Unlike the initial
350
+ // connect path, a 4003 on an ESTABLISHED connection means the device was
351
+ // revoked mid-session. The auto-recovery on initial connect handles the
352
+ // common case (stored revoked key at startup). For mid-session revocation,
353
+ // the agent exits with a clear message — the user should investigate.
354
+ const isAuthFailure = code === 4003;
355
+
356
+ closeAllSessions().then(({ closed }) => {
357
+ if (closed > 0) console.error(` Closed ${closed} browser session(s).`);
358
+ }).catch(() => {}).finally(() => {
359
+ try { ws.close(1000, 'Agent shutting down after disconnect'); } catch {}
360
+ processLock.releaseLock();
361
+
362
+ if (isAuthFailure) {
363
+ console.error('\n❌ Authentication failed — this device was revoked during the session.');
364
+ console.error(' The server-scoped identity for ' + serverOrigin + ' has been cleared.');
365
+ console.error(' Run `xkwd-agent start` again to re-authorize this computer.');
366
+ // Server-scoped cleanup so the next start re-enrolls
367
+ try {
368
+ const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
369
+ deletePrivateKey({ serverOrigin });
370
+ deleteMetadata({ serverOrigin });
371
+ } catch {}
372
+ } else {
373
+ console.error('\nTo reconnect, run `xkwd-agent start` again.');
374
+ }
375
+ console.error('Agent stopped.');
376
+ process.exit(1);
377
+ });
378
+ });
379
+
380
+ // 9. Clean shutdown on Ctrl+C
381
+ async function shutdown(signal) {
382
+ if (shuttingDown) return;
383
+ shuttingDown = true;
384
+ console.log(`\n${signal} received. Shutting down...`);
385
+
386
+ // Stop accepting commands immediately.
387
+ markDisconnected();
388
+
389
+ // Close all browser sessions (preserves profiles/cookies via the
390
+ // existing safe persistence path).
391
+ try {
392
+ await closeAllSessions();
393
+ } catch {}
394
+
395
+ // Close WebSocket
396
+ try { ws.close(1000, 'Agent shutting down'); } catch {}
397
+
398
+ // Release lock
399
+ processLock.releaseLock();
400
+
401
+ process.exit(0);
402
+ }
403
+
404
+ process.on('SIGINT', () => shutdown('Ctrl+C'));
405
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
406
+ process.on('SIGHUP', () => shutdown('SIGHUP'));
407
+
408
+ // Also release the lock on uncaught exceptions
409
+ process.on('uncaughtException', (err) => {
410
+ console.error('Uncaught error:', err.message);
411
+ processLock.releaseLock();
412
+ process.exit(1);
413
+ });
414
+ }
415
+
416
+ /**
417
+ * `xkwd-agent status` — show device and connection status.
418
+ */
419
+ function status() {
420
+ const { getStoredDevice } = require('./enrollmentClient');
421
+ const { isSecureStorageAvailable } = require('./deviceKeyStore');
422
+ const processLock = require('./processLock');
423
+
424
+ const args = process.argv.slice(2);
425
+ const serverFlag = args.find(a => a.startsWith('--server='));
426
+ const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
427
+
428
+ const device = getStoredDevice({ serverOrigin });
429
+ const lock = processLock.readLock();
430
+
431
+ console.log(`XKWDStore Agent v${CLI_VERSION}\n`);
432
+
433
+ if (!device) {
434
+ console.log('Status: Not authorized');
435
+ console.log('Run `xkwd-agent start` to authorize this computer.');
436
+ return;
437
+ }
438
+
439
+ console.log(`Device ID: ${device.deviceId}`);
440
+ console.log(`Device name: ${device.deviceName}`);
441
+ console.log(`Server: ${device.serverOrigin || 'https://x.kwdstore.com'}`);
442
+ console.log(`Public-key fingerprint: ${device.publicKeyFingerprint.slice(0, 8)}…${device.publicKeyFingerprint.slice(-8)}`);
443
+ console.log(`Created: ${device.createdAt || 'unknown'}`);
444
+ console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available' : 'unavailable'}`);
445
+
446
+ if (lock) {
447
+ console.log(`\nAgent process: RUNNING (PID ${lock.pid})`);
448
+ console.log(`Started: ${lock.startedAt}`);
449
+ } else {
450
+ console.log('\nAgent process: not running');
451
+ }
452
+ }
453
+
454
+ /**
455
+ * `xkwd-agent logout` — delete local device identity (re-enrollment required).
456
+ * Server-scoped: only deletes the identity for the specified server.
457
+ * Usage: xkwd-agent logout [--server=<url>]
458
+ */
459
+ async function logout() {
460
+ const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
461
+ const processLock = require('./processLock');
462
+
463
+ // Parse --server flag for scoped logout
464
+ const args = process.argv.slice(2);
465
+ const serverFlag = args.find(a => a.startsWith('--server='));
466
+ const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
467
+
468
+ const lock = processLock.readLock();
469
+ if (lock) {
470
+ console.error('Agent is currently running. Stop it first with Ctrl+C.');
471
+ process.exit(1);
472
+ }
473
+
474
+ await deletePrivateKey({ serverOrigin });
475
+ deleteMetadata({ serverOrigin });
476
+ console.log(`Local device identity deleted for ${serverOrigin}.`);
477
+ console.log('Run `xkwd-agent start` to re-authorize this computer.');
478
+ }
479
+
480
+ /**
481
+ * `xkwd-agent revoke-local` — same as logout but also clears the process lock.
482
+ * Server-scoped: only deletes the identity for the specified server.
483
+ */
484
+ async function revokeLocal() {
485
+ const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
486
+ const args = process.argv.slice(2);
487
+ const serverFlag = args.find(a => a.startsWith('--server='));
488
+ const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
489
+ await deletePrivateKey({ serverOrigin });
490
+ deleteMetadata({ serverOrigin });
491
+ console.log(`Local device identity and credentials revoked for ${serverOrigin}.`);
492
+ console.log('The server-side device record should also be revoked from the dashboard.');
493
+ }
494
+
495
+ /**
496
+ * `xkwd-agent doctor` — diagnostic checks.
497
+ */
498
+ async function doctor(serverOrigin) {
499
+ console.log(`XKWDStore Agent v${CLI_VERSION} — Diagnostics\n`);
500
+
501
+ // Check Node version
502
+ const nodeVersion = process.versions.node;
503
+ const major = parseInt(nodeVersion.split('.')[0], 10);
504
+ console.log(`Node.js: ${nodeVersion} ${major >= 22 ? '✓' : '✗ (requires Node.js 22+)'}`);
505
+
506
+ // Check platform
507
+ console.log(`Platform: ${os.platform()} ${os.arch()}`);
508
+ console.log(`Hostname: ${os.hostname()}`);
509
+
510
+ // Check Chrome
511
+ try {
512
+ const { resolveChromeOrFail } = require('./chromeDetector');
513
+ const chrome = resolveChromeOrFail();
514
+ console.log(`Chrome: ${chrome.chromeVersion || 'detected'} ✓`);
515
+ } catch (e) {
516
+ console.log(`Chrome: ✗ (${e.message.split('\n')[0]})`);
517
+ }
518
+
519
+ // Check secure storage (real DPAPI + ACL probe on Windows)
520
+ const { isSecureStorageAvailable, getDataDir, probeWindowsStorage } = require('./deviceKeyStore');
521
+ const platform = os.platform();
522
+ if (platform === 'win32') {
523
+ console.log('Secure storage: probing real DPAPI + ACL stages...');
524
+ const probe = probeWindowsStorage();
525
+ console.log(` DPAPI Protect : ${probe.stages.protect ? '✓' : '✗'}`);
526
+ console.log(` DPAPI Unprotect: ${probe.stages.unprotect ? '✓' : '✗'}`);
527
+ console.log(` Windows SID : ${probe.stages.sidLookup ? '✓' : '✗'}`);
528
+ console.log(` ACL apply : ${probe.stages.aclApply ? '✓' : '✗'}`);
529
+ console.log(` ACL verify : ${probe.stages.aclVerify ? '✓' : '✗'}`);
530
+ console.log(`Secure storage: ${probe.ok ? 'available ✓' : 'unavailable ✗'}`);
531
+ if (!probe.ok && probe.detail) {
532
+ console.log(` Detail: ${probe.detail}`);
533
+ }
534
+ } else {
535
+ console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available ✓' : 'unavailable ✗'}`);
536
+ }
537
+
538
+ // Check data directory
539
+ const dataDir = getDataDir();
540
+ console.log(`Data directory: ${dataDir}`);
541
+
542
+ // Check device identity (server-scoped)
543
+ const { getStoredDevice, getStoredPrivateKey } = require('./enrollmentClient');
544
+ const device = getStoredDevice({ serverOrigin });
545
+ if (device) {
546
+ console.log(`Device ID: ${device.deviceId} ✓`);
547
+ const privateKey = await getStoredPrivateKey({ serverOrigin });
548
+ console.log(`Private key: ${privateKey ? 'stored ✓' : 'missing ✗'}`);
549
+ } else {
550
+ console.log('Device ID: not enrolled for this server');
551
+ }
552
+
553
+ // Check server connectivity (shared strict validator)
554
+ try {
555
+ const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
556
+ const resp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
557
+ const compat = validateCompatibilityResponse(resp);
558
+ if (compat.html) {
559
+ console.log(`Server (${serverOrigin}): compatibility endpoint returned frontend ✗`);
560
+ console.log(' ' + COMPAT_HTML_MESSAGE);
561
+ } else if (compat.ok) {
562
+ console.log(`Server (${serverOrigin}): reachable ✓`);
563
+ console.log(` Protocol version: ${compat.body.protocolVersion}`);
564
+ console.log(` Min agent version: ${compat.body.minimumAgentVersion}`);
565
+ console.log(` Recommended agent version: ${compat.body.recommendedAgentVersion}`);
566
+ } else {
567
+ console.log(`Server (${serverOrigin}): compatibility check failed ✗`);
568
+ console.log(` Reason: ${compat.reason}`);
569
+ }
570
+ } catch (e) {
571
+ console.log(`Server (${serverOrigin}): unreachable ✗ (${e.message})`);
572
+ }
573
+ }
574
+
575
+ /**
576
+ * `xkwd-agent version` — print version.
577
+ */
578
+ function version() {
579
+ console.log(`@xkwdstore/agent v${CLI_VERSION}`);
580
+ console.log(`Protocol version: ${PROTOCOL_VERSION}`);
581
+ console.log(`Node.js: ${process.versions.node}`);
582
+ }
583
+
584
+ /**
585
+ * `xkwd-agent help` — print help.
586
+ */
587
+ function help() {
588
+ console.log(`XKWDStore Agent v${CLI_VERSION}
589
+
590
+ Usage:
591
+ xkwd-agent <command> [options]
592
+
593
+ Commands:
594
+ start Start the agent (connects to server, runs browser sessions)
595
+ status Show device and connection status
596
+ logout Delete local device identity (requires re-authorization)
597
+ revoke-local Delete local device identity and credentials
598
+ doctor Run diagnostic checks
599
+ version Print version information
600
+ help Show this help
601
+
602
+ Options:
603
+ --server=<url> Server URL (default: https://x.kwdstore.com)
604
+ --replace Replace a running instance (safe takeover)
605
+
606
+ Examples:
607
+ xkwd-agent start
608
+ xkwd-agent start --replace
609
+ xkwd-agent status
610
+ xkwd-agent doctor
611
+
612
+ First run:
613
+ The agent will open your browser to authorize this computer.
614
+ No pairing code, email, or API key is required.
615
+
616
+ To stop:
617
+ Press Ctrl+C in the terminal.
618
+
619
+ Data location:
620
+ Windows: %LOCALAPPDATA%\\XKWDStore\\
621
+ macOS: ~/Library/Application Support/XKWDStore/
622
+ Linux: ~/.local/share/xkwdstore/
623
+
624
+ Requirements:
625
+ - Node.js 22 or later
626
+ - Google Chrome installed
627
+ `);
628
+ }
629
+
630
+ // ── Helpers ──────────────────────────────────────────────────────────────────
631
+
632
+ /**
633
+ * Detect whether a connection error is a 4003 authentication failure.
634
+ * The wsClient rejects with a message containing "Device authentication
635
+ * failed" when the server closes with code 4003. The error may also carry
636
+ * a .code property in some implementations.
637
+ */
638
+ function _is4003Error(err) {
639
+ if (!err) return false;
640
+ const msg = (err.message || String(err)).toLowerCase();
641
+ if (err.code === 4003) return true;
642
+ if (msg.includes('device authentication failed')) return true;
643
+ if (msg.includes('4003')) return true;
644
+ return false;
645
+ }
646
+
647
+ function _compareVersions(a, b) {
648
+ const pa = a.split('.').map(Number);
649
+ const pb = b.split('.').map(Number);
650
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
651
+ const va = pa[i] || 0;
652
+ const vb = pb[i] || 0;
653
+ if (va > vb) return 1;
654
+ if (va < vb) return -1;
655
+ }
656
+ return 0;
657
+ }
658
+
659
+ // ── Entry point ──────────────────────────────────────────────────────────────
660
+
661
+ if (require.main === module) {
662
+ main();
663
+ }
664
+
529
665
  module.exports = { main, CLI_VERSION, PROTOCOL_VERSION };