@xkwdstore/agent 2.1.5 → 2.1.7

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,1291 +1,1291 @@
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> recover
15
- * npx --yes @xkwdstore/agent@<PINNED_VERSION> logout
16
- * npx --yes @xkwdstore/agent@<PINNED_VERSION> revoke-local
17
- * npx --yes @xkwdstore/agent@<PINNED_VERSION> doctor
18
- * npx --yes @xkwdstore/agent@<PINNED_VERSION> version
19
- *
20
- * The agent runs only while the terminal process is running.
21
- * Closing the terminal or pressing Ctrl+C stops the agent cleanly.
22
- */
23
-
24
- const crypto = require('crypto');
25
- const os = require('os');
26
- const path = require('path');
27
-
28
- const CLI_VERSION = '2.1.5';
29
- const PROTOCOL_VERSION = 2;
30
-
31
- // ── Command parsing ──────────────────────────────────────────────────────────
32
-
33
- function main() {
34
- const args = process.argv.slice(2);
35
- const command = args[0] || 'help';
36
- const flags = {};
37
- const positional = [];
38
-
39
- for (let i = 1; i < args.length; i++) {
40
- const arg = args[i];
41
- if (arg.startsWith('--')) {
42
- const key = arg.slice(2);
43
- const next = args[i + 1];
44
- if (next && !next.startsWith('--')) {
45
- flags[key] = next;
46
- i++;
47
- } else {
48
- flags[key] = true;
49
- }
50
- } else {
51
- positional.push(arg);
52
- }
53
- }
54
-
55
- const serverOrigin = flags.server ||
56
- process.env.XKWDSTORE_SERVER ||
57
- 'https://x.kwdstore.com';
58
-
59
- switch (command) {
60
- case 'start':
61
- return start(serverOrigin, flags);
62
- case 'status':
63
- return status();
64
- case 'recover':
65
- return recover(serverOrigin);
66
- case 'logout':
67
- return logout();
68
- case 'revoke-local':
69
- return revokeLocal();
70
- case 'doctor':
71
- return doctor(serverOrigin);
72
- case 'machine':
73
- return machine(positional);
74
- case 'service':
75
- return service(serverOrigin, flags);
76
- case 'key-probe': {
77
- // Diagnostics: report whether the machine credential can be decrypted in
78
- // THIS process context (e.g. from the LocalSystem service) WITHOUT
79
- // printing any secret. Used by the elevated lifecycle gate.
80
- (async () => {
81
- const fs = require('fs');
82
- const path = require('path');
83
- const { loadMetadata, loadPrivateKeyFromStorage, getMachineRoot, _identitySourceRoots, _serversDirFor } = require('./deviceKeyStore');
84
- const { normalizeServerOrigin } = require('./deviceKeyStore');
85
- const meta = loadMetadata({ serverOrigin });
86
- const out = {
87
- context: { user: require('os').userInfo().username, platform: os.platform(), pid: process.pid },
88
- machineRoot: getMachineRoot(),
89
- deviceId: meta ? meta.deviceId : null,
90
- privateKeyDecryptable: false,
91
- stages: {},
92
- error: '',
93
- };
94
- // Stage 1: locate the key file the loader would use.
95
- let keyFile = null;
96
- try {
97
- const roots = _identitySourceRoots();
98
- const label = normalizeServerOrigin(serverOrigin);
99
- const candidates = [];
100
- for (const r of [roots.source, roots.target]) {
101
- if (r) candidates.push(path.join(_serversDirFor(r), label, '.device-key'));
102
- }
103
- for (const r of [roots.source, roots.target]) { if (r) candidates.push(path.join(r, '.device-key')); }
104
- out.stages.candidates = candidates;
105
- for (const c of candidates) { if (fs.existsSync(c)) { keyFile = c; break; } }
106
- out.stages.keyFile = keyFile;
107
- out.stages.keyReadable = keyFile ? (() => { try { fs.accessSync(keyFile, fs.constants.R_OK); return true; } catch { return false; } })() : false;
108
- if (keyFile) {
109
- try {
110
- const env = JSON.parse(fs.readFileSync(keyFile, 'utf8'));
111
- out.stages.envelopeScheme = env.scheme;
112
- out.stages.envelopeScope = env.scope || '(v1/unscoped)';
113
- out.stages.envelopeV = env.v;
114
- } catch (e) { out.stages.envelopeError = (e && e.message) || 'parse'; }
115
- }
116
- } catch (e) { out.stages.locateError = (e && e.message) || 'locate'; }
117
- // Stage 2: full loader (includes ACL verify).
118
- try { out.privateKeyDecryptable = !!(await loadPrivateKeyFromStorage({ serverOrigin })); } catch (e) { out.error = (e && e.message) || 'error'; }
119
- console.log(JSON.stringify(out));
120
- })().catch((e) => { console.error(JSON.stringify({ error: (e && e.message) || 'fatal' })); process.exit(1); });
121
- return;
122
- }
123
- case 'version':
124
- return version();
125
- case 'help':
126
- case '--help':
127
- case '-h':
128
- default:
129
- return help();
130
- }
131
- }
132
-
133
- // ── Commands ─────────────────────────────────────────────────────────────────
134
-
135
- /**
136
- * `xkwd-agent start` — the main runtime command.
137
- */
138
- async function start(serverOrigin, flags) {
139
- console.log(`XKWDStore Agent v${CLI_VERSION} (protocol v${PROTOCOL_VERSION})`);
140
- console.log(`Server: ${serverOrigin}`);
141
-
142
- // 0. Machine-wide state: create the ProgramData layout and adopt any
143
- // pre-2.1.0 per-user identity ONCE (copy, never move). The device identity
144
- // therefore belongs to the MACHINE, not to the current Windows user.
145
- try {
146
- const machineState = require('./machineState');
147
- const init = machineState.initializeMachineState();
148
- console.log(`✓ Machine state: ${init.root}`);
149
- if (init.adopted && init.deviceId) {
150
- console.log(`✓ Adopted existing device identity: ${init.deviceId}`);
151
- }
152
- } catch (e) {
153
- console.error(`Machine state initialization failed: ${(e && e.message) || 'unknown'}`);
154
- process.exit(1);
155
- }
156
- console.log();
157
-
158
- // 1. Detect OS and architecture (for display)
159
- const platform = os.platform();
160
- const arch = os.arch();
161
- const hostname = os.hostname();
162
- console.log(`✓ Detected computer: ${hostname}`);
163
- console.log(`✓ Platform: ${platform} ${arch}`);
164
-
165
- // 2. Resolve system Chrome (fail clearly if missing)
166
- const { resolveChromeOrFail } = require('./chromeDetector');
167
- let chromePath, chromeVersion;
168
- try {
169
- const chrome = resolveChromeOrFail();
170
- chromePath = chrome.chromePath;
171
- chromeVersion = chrome.chromeVersion;
172
- console.log(`✓ Chrome ${chromeVersion || 'detected'}: ${chromePath}`);
173
- } catch (e) {
174
- console.error(e.message);
175
- process.exit(1);
176
- }
177
-
178
- // 3. Check compatibility with server (shared strict validator)
179
- const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
180
- try {
181
- const compatResp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
182
- const compat = validateCompatibilityResponse(compatResp);
183
- if (compat.html) {
184
- console.error('\n' + COMPAT_HTML_MESSAGE);
185
- process.exit(1);
186
- }
187
- if (!compat.ok) {
188
- console.error('\nServer compatibility check failed: ' + compat.reason + '.');
189
- console.error('The agent will not start enrollment until the server is compatible.');
190
- process.exit(1);
191
- }
192
- // NOTE: the server's declared `capabilities` are INFORMATIONAL. They are
193
- // never a reason to refuse a server — a server that does not advertise the
194
- // profile-identity capability may still supply the identity tuple, and every
195
- // currently-deployed backend omits the field. A missing capability must not
196
- // block startup (see validateCompatibilityResponse).
197
- // compat.ok — enforce minimum agent version
198
- const minVer = compat.body.minimumAgentVersion;
199
- const recVer = compat.body.recommendedAgentVersion;
200
- if (minVer && _compareVersions(CLI_VERSION, minVer) < 0) {
201
- console.error(`\nThis agent version (${CLI_VERSION}) is no longer supported.`);
202
- console.error(`\nRun:\n\n npx --yes @xkwdstore/agent@${recVer} start\n`);
203
- process.exit(1);
204
- }
205
- } catch (e) {
206
- console.error(`\nServer compatibility check failed: ${e.message}`);
207
- console.error('The agent will not start enrollment until the server is reachable and compatible.');
208
- process.exit(1);
209
- }
210
-
211
- // 4. Load or generate device key (server-scoped: per-server identity)
212
- const { getStoredDevice, getStoredPrivateKey, enroll } = require('./enrollmentClient');
213
- const { isSecureStorageAvailable } = require('./deviceKeyStore');
214
-
215
- if (!isSecureStorageAvailable()) {
216
- console.error('Secure key storage is unavailable on this system.');
217
- if (os.platform() === 'win32') {
218
- console.error('On Windows, ensure System32\\WindowsPowerShell\\v1.0\\powershell.exe is present and DPAPI is available.');
219
- } else {
220
- console.error('On Linux, install gnome-keyring or seahorse (libsecret).');
221
- }
222
- console.error('The agent cannot run without secure key storage.');
223
- process.exit(1);
224
- }
225
-
226
- let deviceMeta = getStoredDevice({ serverOrigin });
227
- let privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
228
-
229
- // 5. Authorize the device when needed (first run or revoked)
230
- if (!deviceMeta || !privateKeyB64Url) {
231
- console.log('\n✓ Device identity loaded securely');
232
- try {
233
- const result = await enroll(serverOrigin, { chromePath });
234
- deviceMeta = require('./deviceKeyStore').loadMetadata({ serverOrigin });
235
- privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
236
- } catch (e) {
237
- console.error(`\nEnrollment failed: ${e.message}`);
238
- process.exit(1);
239
- }
240
- } else {
241
- console.log(`✓ Device identity loaded securely`);
242
- console.log(`✓ Device recognized: ${deviceMeta.deviceName}`);
243
- }
244
-
245
- // 6. Process lock (prevent duplicate instances)
246
- const processLock = require('./processLock');
247
- const lockResult = processLock.acquireLock({
248
- deviceId: deviceMeta.deviceId,
249
- deviceName: deviceMeta.deviceName,
250
- });
251
-
252
- if (!lockResult.acquired) {
253
- if (flags.replace) {
254
- console.log('\nAnother agent instance is running. Requesting takeover...');
255
- const took = await processLock.requestTakeover(lockResult.existing);
256
- if (!took) {
257
- console.error('Could not stop the existing instance. Please close it manually.');
258
- process.exit(1);
259
- }
260
- // Re-acquire the lock
261
- const retryLock = processLock.acquireLock({
262
- deviceId: deviceMeta.deviceId,
263
- deviceName: deviceMeta.deviceName,
264
- });
265
- if (!retryLock.acquired) {
266
- console.error('Could not acquire process lock after takeover.');
267
- process.exit(1);
268
- }
269
- } else {
270
- console.error('\nXKWDStore Agent is already running on this computer.');
271
- console.error(`PID: ${lockResult.existing.pid}`);
272
- console.error(`Started: ${lockResult.existing.startedAt}`);
273
- console.error(`Device: ${lockResult.existing.deviceName || 'unknown'}`);
274
- console.error('\nTo replace the running instance, use:');
275
- console.error(' xkwd-agent start --replace');
276
- process.exit(1);
277
- }
278
- }
279
-
280
- // 7. Connect securely via WebSocket challenge-response
281
- // 4003 auto-recovery: if the initial connection fails with 4003 (revoked/
282
- // unknown device), the agent automatically performs a server-scoped
283
- // re-enrollment and reconnects in the SAME process flow — the user does
284
- // NOT need to type a second command. Only ONE auto-recovery attempt is
285
- // allowed per startup to prevent infinite loops.
286
- const { connectWebSocket } = require('./wsClient');
287
- let ws;
288
- let autoRecovered = false;
289
-
290
- try {
291
- ws = await connectWebSocket({
292
- serverOrigin,
293
- deviceId: deviceMeta.deviceId,
294
- publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
295
- privateKeyB64Url,
296
- protocolVersion: PROTOCOL_VERSION,
297
- });
298
- } catch (connectErr) {
299
- // Check if this is a 4003 authentication failure (revoked/unknown device).
300
- // The wsClient rejects with a message containing "Device authentication
301
- // failed" for 4003 close codes, or the error may carry a .code property.
302
- const isAuthFailure = _is4003Error(connectErr);
303
-
304
- if (isAuthFailure && !autoRecovered) {
305
- autoRecovered = true;
306
- console.error('\n❌ Authentication failed (4003) — this device may be revoked.');
307
- console.error(' Automatically re-authorizing for ' + serverOrigin + '...');
308
- console.error(' (Other servers\' identities are NOT affected.)');
309
-
310
- // Release the lock before re-enrollment (enrollment opens a browser)
311
- processLock.releaseLock();
312
-
313
- // Delete only this server's identity
314
- const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
315
- await deletePrivateKey({ serverOrigin });
316
- deleteMetadata({ serverOrigin });
317
- console.error('✓ Old identity cleared for ' + serverOrigin);
318
-
319
- // Re-enroll automatically (opens browser for approval)
320
- console.log('\nOpening authorization page...');
321
- try {
322
- await enroll(serverOrigin, { chromePath });
323
- deviceMeta = require('./deviceKeyStore').loadMetadata({ serverOrigin });
324
- privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
325
-
326
- if (!deviceMeta || !privateKeyB64Url) {
327
- console.error('\n❌ Re-enrollment completed but identity could not be loaded.');
328
- process.exit(1);
329
- }
330
- console.log('✓ New identity stored for ' + serverOrigin);
331
- } catch (enrollErr) {
332
- console.error(`\n❌ Automatic re-enrollment failed: ${enrollErr.message}`);
333
- console.error(' Run `xkwd-agent start` again to retry manually.');
334
- process.exit(1);
335
- }
336
-
337
- // Re-acquire the process lock with the new device identity
338
- const retryLock = processLock.acquireLock({
339
- deviceId: deviceMeta.deviceId,
340
- deviceName: deviceMeta.deviceName,
341
- });
342
- if (!retryLock.acquired) {
343
- console.error('Could not acquire process lock after re-enrollment.');
344
- if (flags.replace) {
345
- const took = await processLock.requestTakeover(retryLock.existing);
346
- if (!took) {
347
- console.error('Could not stop the existing instance. Please close it manually.');
348
- process.exit(1);
349
- }
350
- } else {
351
- process.exit(1);
352
- }
353
- }
354
-
355
- // Attempt to reconnect with the new identity (only ONE retry)
356
- try {
357
- ws = await connectWebSocket({
358
- serverOrigin,
359
- deviceId: deviceMeta.deviceId,
360
- publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
361
- privateKeyB64Url,
362
- protocolVersion: PROTOCOL_VERSION,
363
- });
364
- console.log('\n✓ Re-authorized and reconnected automatically.');
365
- } catch (retryErr) {
366
- if (_is4003Error(retryErr)) {
367
- console.error('\n❌ Authentication failed again after re-enrollment.');
368
- console.error(' The new device may not have been approved on the dashboard.');
369
- console.error(' Run `xkwd-agent start` again after approving the device.');
370
- } else {
371
- console.error(`\n❌ Reconnection failed: ${retryErr.message}`);
372
- console.error(' Run `xkwd-agent start` again to retry.');
373
- }
374
- processLock.releaseLock();
375
- process.exit(1);
376
- }
377
- } else {
378
- // Non-4003 error, or 4003 after auto-recovery already attempted
379
- console.error(`\nConnection failed: ${connectErr.message}`);
380
- if (isAuthFailure) {
381
- console.error(' Automatic recovery was already attempted. Run `xkwd-agent start` again.');
382
- }
383
- processLock.releaseLock();
384
- process.exit(1);
385
- }
386
- }
387
-
388
- console.log('✓ Secure challenge passed');
389
- console.log('✓ Connected');
390
- console.log('\nAgent is running. Press Ctrl+C to stop.\n');
391
-
392
- // Keep SQLite-style registry state honest: the handler owns session
393
- // registration; ensure the machine runtime dir exists before the first launch.
394
- try {
395
- const ms = require('./machineState');
396
- ms.ensureMachineLayout();
397
- } catch { /* best-effort */ }
398
-
399
- // 8. Set up browser session handler (delegates to existing session management)
400
- const { setupSessionHandler, closeAllSessions, markDisconnected, recoverOrphanedSessions } = require('./sessionHandler');
401
-
402
- // 2.1.0 F1: crash recovery. A previous agent process may have left an
403
- // Agent-OWNED Chromium behind (it is alive but unmanaged). Release the stale
404
- // LOCAL locks for those proven-owned sessions so the accounts are not blocked
405
- // on this device. The SERVER durable lease is authoritative and is NOT touched
406
- // here — server recovery (recovery-probe / reconcile) still governs it.
407
- try {
408
- const recovery = recoverOrphanedSessions();
409
- if (recovery.orphans > 0) {
410
- console.log(`ℹ️ Crash recovery: found ${recovery.orphans} Agent-owned orphaned browser(s); released ${recovery.released} local lock(s).`);
411
- }
412
- } catch { /* never block startup on recovery */ }
413
-
414
- const { createBrokerConnectionSupervisor } = require('./brokerConnectionSupervisor');
415
-
416
- // 8a. Disconnect handling — the SAME reconnect supervisor as the machine
417
- // `service` broker. The foreground agent adopts the already-authenticated
418
- // socket; the supervisor owns every subsequent (re)connect, guaranteeing one
419
- // timer / one attempt / one live socket, with unbounded self-healing that uses
420
- // the SAME enrolled identity (transport recovery only, never a new identity).
421
- //
422
- // Interactive-path policy preserved:
423
- // - server-initiated restart (1000 'agent-restart' / 4002 'Server-initiated
424
- // restart'): rebind WITHOUT touching local browsers — the server reconciles
425
- // leases from our sessions-report after reconnect.
426
- // - any OTHER close: mark disconnected + close all browser contexts (profiles
427
- // persist), then reconnect.
428
- // - 4003 revoked mid-session: clear THIS server's identity and stop (explicit
429
- // re-authorization) — the supervisor NEVER regenerates identity.
430
- const _isRestartClose = (code, reasonStr) =>
431
- (code === 1000 && /agent-restart/i.test(reasonStr))
432
- || (code === 4002 && /server-initiated restart/i.test(reasonStr));
433
-
434
- const supervisor = createBrokerConnectionSupervisor({
435
- connect: () => connectWebSocket({
436
- serverOrigin,
437
- deviceId: deviceMeta.deviceId,
438
- publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
439
- privateKeyB64Url,
440
- protocolVersion: PROTOCOL_VERSION,
441
- }),
442
- onConnected: (socket) => { setupSessionHandler(socket, { chromePath, deviceMeta, serverOrigin }); },
443
- onDisconnected: async ({ code, reason }) => {
444
- const reasonStr = reason || '';
445
- if (_isRestartClose(code, reasonStr)) {
446
- console.log('\nℹ️ Server requested a connection restart. Reconnecting (browser sessions stay open)...');
447
- return; // keep local browsers; the server reconciles leases
448
- }
449
- console.error(`\n✗ Connection to server lost (code ${code}${reasonStr ? ': ' + reasonStr : ''}).`);
450
- console.error(' Closing all browser sessions and reconnecting safely...');
451
- markDisconnected();
452
- try { await closeAllSessions(); } catch { }
453
- },
454
- onAuthRejected: () => {
455
- // 4003: the credential is dead. PRESERVE the device identity and browser
456
- // profiles — a revoked device can be recovered without re-enrolling into a
457
- // new device id (which would orphan the device-bound profiles). Never
458
- // delete the key here; only an explicit `logout`/`revoke-local` does that.
459
- console.error('\n❌ Authentication failed — this device is no longer authorized.');
460
- console.error(' It may have been revoked, or replaced by another computer (single-device policy).');
461
- console.error(' Device identity and browser profiles were preserved.');
462
- console.error(' Ask the account owner to re-authorize THIS device, then run:');
463
- console.error(` xkwd-agent recover --server=${serverOrigin}`);
464
- console.error(' (Recovery requires owner approval and will revoke the currently active device.)');
465
- },
466
- onAuthBlocked: () => {
467
- // Permanent class: the supervisor has stopped retrying. Do not exit in a
468
- // loop and do not regenerate identity; make the required action visible.
469
- console.error('\n❌ Reauthorization required. Automatic retries have stopped (identity preserved).');
470
- console.error(` Run \`xkwd-agent recover --server=${serverOrigin}\` after the account owner approves.`);
471
- try { processLock.releaseLock(); } catch { /* best effort */ }
472
- process.exit(1);
473
- },
474
- onExhausted: () => {
475
- console.error('\n❌ Could not reconnect. Run `xkwd-agent start` again.');
476
- processLock.releaseLock();
477
- process.exit(1);
478
- },
479
- maxAttempts: 10,
480
- log: (m) => { try { console.log(m); } catch { } },
481
- });
482
- supervisor.adopt(ws);
483
-
484
- // Deliberate-shutdown guard (set before closing anything, so a close emitted
485
- // during shutdown cannot trigger a reconnect).
486
- let shuttingDown = false;
487
-
488
- // 9. Clean shutdown on Ctrl+C
489
- async function shutdown(signal) {
490
- if (shuttingDown) return;
491
- shuttingDown = true;
492
- console.log(`\n${signal} received. Shutting down...`);
493
-
494
- // Stop reconnecting FIRST so no retry can start after shutdown begins.
495
- try { supervisor.stop(); } catch { }
496
-
497
- // Stop accepting commands immediately.
498
- markDisconnected();
499
-
500
- // Close all browser sessions (preserves profiles/cookies via the
501
- // existing safe persistence path).
502
- try {
503
- await closeAllSessions();
504
- } catch {}
505
-
506
- // Release lock
507
- processLock.releaseLock();
508
-
509
- process.exit(0);
510
- }
511
-
512
- process.on('SIGINT', () => shutdown('Ctrl+C'));
513
- process.on('SIGTERM', () => shutdown('SIGTERM'));
514
- process.on('SIGHUP', () => shutdown('SIGHUP'));
515
-
516
- // Also release the lock on uncaught exceptions
517
- process.on('uncaughtException', (err) => {
518
- console.error('Uncaught error:', err.message);
519
- processLock.releaseLock();
520
- process.exit(1);
521
- });
522
- }
523
-
524
- /**
525
- * `xkwd-agent status` — show device and connection status.
526
- */
527
- function status() {
528
- const { getStoredDevice } = require('./enrollmentClient');
529
- const { isSecureStorageAvailable } = require('./deviceKeyStore');
530
- const processLock = require('./processLock');
531
-
532
- const args = process.argv.slice(2);
533
- const serverFlag = args.find(a => a.startsWith('--server='));
534
- const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
535
-
536
- const device = getStoredDevice({ serverOrigin });
537
- const lock = processLock.readLock();
538
-
539
- console.log(`XKWDStore Agent v${CLI_VERSION}\n`);
540
-
541
- const machineState = require('./machineState');
542
- console.log(`Machine root: ${machineState.getMachineRoot()}`);
543
- console.log(`Machine identity: ${machineState.hasMachineIdentity() ? 'present' : 'not yet adopted'}\n`);
544
-
545
- const brokerHealthModule = require('./brokerHealth');
546
- const health = brokerHealthModule.readBrokerHealth() || brokerHealthModule.readBrokerLogAuthState();
547
- if (health) {
548
- const label = health.reauthorizationRequired
549
- ? (health.source === 'broker-log'
550
- ? 'AUTHENTICATION REJECTED (legacy broker is still retrying; upgrade/restart with 2.1.5)'
551
- : 'REAUTHORIZATION REQUIRED (automatic retries stopped)')
552
- : (health.state === 'connected' ? 'connected' : (health.state || 'unknown'));
553
- console.log(`Broker: ${label}`);
554
- if (health.authFailures) console.log(` Consecutive auth failures: ${health.authFailures}`);
555
- if (health.lastDisconnectCode) console.log(` Last rejection code: ${health.lastDisconnectCode}`);
556
- if (health.hint) console.log(` Action: ${health.hint}`);
557
- console.log('');
558
- }
559
-
560
- if (!device) {
561
- console.log('Status: Not authorized');
562
- console.log('Run `xkwd-agent start` to authorize this computer.');
563
- return;
564
- }
565
-
566
- console.log(`Device ID: ${device.deviceId}`);
567
- console.log(`Device name: ${device.deviceName}`);
568
- console.log(`Server: ${device.serverOrigin || 'https://x.kwdstore.com'}`);
569
- console.log(`Public-key fingerprint: ${device.publicKeyFingerprint.slice(0, 8)}…${device.publicKeyFingerprint.slice(-8)}`);
570
- console.log(`Created: ${device.createdAt || 'unknown'}`);
571
- console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available' : 'unavailable'}`);
572
-
573
- if (lock) {
574
- console.log(`\nAgent process: RUNNING (PID ${lock.pid})`);
575
- console.log(`Started: ${lock.startedAt}`);
576
- } else {
577
- console.log('\nAgent process: not running');
578
- }
579
- }
580
-
581
- /**
582
- * `xkwd-agent recover` — re-authorize THIS existing device id.
583
- *
584
- * This is the supported recovery path after a device was revoked/replaced:
585
- * it keeps the local device identity (same deviceId and key) and asks the
586
- * account owner to approve it. The backend reactivates the SAME device record,
587
- * so device-bound browser profiles (cookies/sessions) are preserved. Because the
588
- * tenant enforces one active protocol-v2 device, approval will revoke whichever
589
- * device is currently active — the owner must consent explicitly.
590
- */
591
- async function recover(serverOrigin) {
592
- const { getStoredDevice, getStoredPrivateKey, enroll, _request } = require('./enrollmentClient');
593
- const device = getStoredDevice({ serverOrigin });
594
- const privateKey = await getStoredPrivateKey({ serverOrigin });
595
- if (!device || !privateKey) {
596
- console.error('\nNo existing device identity to recover for ' + serverOrigin + '.');
597
- console.error('Run `xkwd-agent start` to enroll this computer as a new device.');
598
- process.exit(1);
599
- }
600
- // Feature gate: an older backend would treat this as a normal enrollment and
601
- // mint a NEW device id, silently orphaning the existing profiles. Refuse.
602
- let caps = [];
603
- try {
604
- const r = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
605
- caps = (r && r.body && Array.isArray(r.body.capabilities)) ? r.body.capabilities : [];
606
- } catch (e) {
607
- console.error('\nCould not reach the server: ' + e.message);
608
- process.exit(1);
609
- }
610
- if (!caps.includes('device-recovery-v1')) {
611
- console.error('\nThis server does not support device recovery yet.');
612
- console.error(' The backend must be upgraded (capability: device-recovery-v1) before recovering.');
613
- console.error(' Do NOT run `start` instead: it would create a NEW device id and this device\'s');
614
- console.error(' browser profiles are bound to the existing id.');
615
- process.exit(1);
616
- }
617
- console.log('\nDevice recovery request');
618
- console.log(` Device ID: ${device.deviceId}`);
619
- console.log(` Name: ${device.deviceName}`);
620
- console.log(` Fingerprint: ${device.publicKeyFingerprint.slice(0, 8)}…${device.publicKeyFingerprint.slice(-8)}`);
621
- console.log('\nThe account owner must approve this request in the browser.');
622
- console.log('Approval restores THIS device and revokes the currently active device');
623
- console.log('(single-device policy). Existing browser profiles on this device are preserved.');
624
- try {
625
- const result = await enroll(serverOrigin, {
626
- keyPair: {
627
- publicKeyB64Url: device.publicKeyB64Url,
628
- publicKeyFingerprint: device.publicKeyFingerprint,
629
- privateKeyB64Url: privateKey,
630
- },
631
- recoverDeviceId: device.deviceId,
632
- existingMeta: device,
633
- });
634
- const { writeBrokerHealth } = require('./brokerHealth');
635
- writeBrokerHealth({
636
- state: 'reauthorized',
637
- authBlocked: false,
638
- reauthorizationRequired: false,
639
- deviceId: device.deviceId,
640
- deviceName: device.deviceName,
641
- serverOrigin,
642
- hint: 'Recovery approved. Restart the XKWDStoreAgentBroker service (or run start) to reconnect.',
643
- });
644
- console.log('\n✓ Device recovered: ' + result.deviceId);
645
- console.log(' Restart the broker service (or run `xkwd-agent start`) to reconnect.');
646
- } catch (e) {
647
- console.error('\nRecovery failed: ' + e.message);
648
- console.error(' Your existing device identity was NOT deleted.');
649
- process.exit(1);
650
- }
651
- }
652
-
653
- /**
654
- * `xkwd-agent logout` — delete local device identity (re-enrollment required).
655
- * Server-scoped: only deletes the identity for the specified server.
656
- * Usage: xkwd-agent logout [--server=<url>]
657
- */
658
- async function logout() {
659
- const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
660
- const processLock = require('./processLock');
661
-
662
- // Parse --server flag for scoped logout
663
- const args = process.argv.slice(2);
664
- const serverFlag = args.find(a => a.startsWith('--server='));
665
- const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
666
-
667
- const lock = processLock.readLock();
668
- if (lock) {
669
- console.error('Agent is currently running. Stop it first with Ctrl+C.');
670
- process.exit(1);
671
- }
672
-
673
- await deletePrivateKey({ serverOrigin });
674
- deleteMetadata({ serverOrigin });
675
- console.log(`Local device identity deleted for ${serverOrigin}.`);
676
- console.log('Run `xkwd-agent start` to re-authorize this computer.');
677
- }
678
-
679
- /**
680
- * `xkwd-agent revoke-local` — same as logout but also clears the process lock.
681
- * Server-scoped: only deletes the identity for the specified server.
682
- */
683
- async function revokeLocal() {
684
- const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
685
- const args = process.argv.slice(2);
686
- const serverFlag = args.find(a => a.startsWith('--server='));
687
- const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
688
- await deletePrivateKey({ serverOrigin });
689
- deleteMetadata({ serverOrigin });
690
- console.log(`Local device identity and credentials revoked for ${serverOrigin}.`);
691
- console.log('The server-side device record should also be revoked from the dashboard.');
692
- }
693
-
694
- /**
695
- * `xkwd-agent machine` — machine-wide state operations (2.1.0).
696
- *
697
- * machine status — root, layout, identity presence, migration state
698
- * machine adopt — run the one-time per-user → machine migration now
699
- * machine harden — (Windows) apply + verify the restrictive DACL on the
700
- * machine state directories
701
- */
702
- async function machine(args) {
703
- const machineState = require('./machineState');
704
- const { getMachineRoot, getLegacyDataDir, applyMachineStateAcls } = require('./deviceKeyStore');
705
- const action = (Array.isArray(args) && args[0]) || 'status';
706
-
707
- if (action === 'status' || action === 'info') {
708
- const report = machineState.migrationReport();
709
- console.log(`XKWDStore Agent v${CLI_VERSION} — Machine state\n`);
710
- console.log(`Machine root (device identity lives here): ${report.newLocation}`);
711
- console.log(` exists: ${report.machinePresent ? 'yes' : 'no'}`);
712
- console.log(` identity present: ${machineState.hasMachineIdentity() ? 'yes' : 'no'}`);
713
- console.log(`Legacy per-user root (migration source): ${report.oldLocation}`);
714
- console.log(` exists: ${report.legacyPresent ? 'yes' : 'no'}`);
715
- console.log(`Started: ${report.machinePresent ? 'yes' : 'no'}`);
716
- if (report.marker) {
717
- console.log(`Migration: ${report.marker.adoption || 'complete'} at ${report.marker.migratedAt}`);
718
- console.log(` device id(s): ${(report.marker.deviceIds || []).join(', ') || '(none)'}`);
719
- } else {
720
- console.log('Migration: not required (no legacy identity found) or not yet run');
721
- }
722
- console.log(`Rollback supported: ${report.rollbackSupported ? 'yes' : 'no'}`);
723
- console.log(` ${report.rollbackInstruction}`);
724
- return;
725
- }
726
-
727
- if (action === 'adopt') {
728
- const result = machineState.initializeMachineState();
729
- console.log(`Machine root: ${result.root}`);
730
- console.log(result.adopted
731
- ? `Adopted legacy per-user state (device id: ${result.deviceId || 'preserved'}).`
732
- : `No adoption needed (${result.reason}).`);
733
- return;
734
- }
735
-
736
- if (action === 'harden') {
737
- if (os.platform() !== 'win32') {
738
- console.log('Machine-state ACL hardening is Windows-only; nothing to do.');
739
- return;
740
- }
741
- const applied = applyMachineStateAcls({});
742
- console.log(`Applied and verified restrictive ACLs on ${applied.length} machine-state director${applied.length === 1 ? 'y' : 'ies'}:`);
743
- for (const p of applied) console.log(` ${p}`);
744
- return;
745
- }
746
-
747
- console.error(`Unknown machine action: ${action}`);
748
- console.error('Usage: xkwd-agent machine [status|adopt|harden]');
749
- process.exit(1);
750
- }
751
-
752
- /**
753
- * `xkwd-agent service` — the BROKER entry point (2.1.0).
754
- *
755
- * Runs the machine-wide broker that a Windows Service hosts. Responsibilities:
756
- * - acquire the machine-wide named mutex (exactly one broker)
757
- * - own the machine identity + device private key
758
- * - own the server WebSocket connection, leases, and session registry
759
- * - spawn an interactive Browser Worker in the active desktop session
760
- * - relay TYPED browser commands to the worker over a loopback-only channel
761
- *
762
- * It never launches Chromium itself. It is silent by design (the service host
763
- * provides no desktop). For foreground diagnostics, `start` runs a broker+worker
764
- * pair in this same session.
765
- */
766
- async function service(serverOrigin, flags) {
767
- const machineLock = require('./machineLock');
768
- const machineState = require('./machineState');
769
-
770
- // 1. machine-wide broker uniqueness (authoritative on Windows).
771
- const lock = machineLock.acquireMachineBrokerLock();
772
- if (!lock.acquired) {
773
- console.error(`Another machine broker already holds the lock (${lock.primitive}): ${lock.detail}`);
774
- process.exit(3);
775
- }
776
- // Hold it for the process lifetime via a dedicated holder process.
777
- const holder = machineLock.startMutexHolder();
778
- if (!holder.ok) {
779
- console.error(`Could not hold the machine broker lock: ${holder.detail}`);
780
- process.exit(3);
781
- }
782
-
783
- // 2. machine state + identity (broker owns the credential).
784
- try { machineState.initializeMachineState(); } catch { }
785
- const { writeBrokerHealth } = require('./brokerHealth');
786
- const brokerMeta = (() => { try { return require('./deviceKeyStore').loadMetadata({ serverOrigin }) || {}; } catch { return {}; } })();
787
- let _lastHealth = '';
788
- const _writeBrokerHealth = (patch) => {
789
- const payload = { deviceId: brokerMeta.deviceId, deviceName: brokerMeta.deviceName, serverOrigin, ...patch };
790
- const key = JSON.stringify(payload);
791
- if (key === _lastHealth) return;
792
- _lastHealth = key;
793
- try { writeBrokerHealth(payload); } catch { /* status reporting must never break the broker */ }
794
- };
795
- // After a permanent auth block, watch ONLY the local device-metadata file. A
796
- // successful `xkwd-agent recover` rewrites it; the broker then retries once,
797
- // without a network retry loop or a service restart. This is a local stat()
798
- // every 30s, not a server poll.
799
- let _authRecoveryTimer = null;
800
- const _clearAuthRecoveryWatch = () => {
801
- if (_authRecoveryTimer) { try { clearInterval(_authRecoveryTimer); } catch { /* ignore */ } _authRecoveryTimer = null; }
802
- };
803
- const _startAuthRecoveryWatch = () => {
804
- if (_authRecoveryTimer) return;
805
- const fs = require('fs');
806
- const path = require('path');
807
- const metaFile = path.join(require('./deviceKeyStore').getServerDataDir(serverOrigin), 'device-metadata.json');
808
- let baseline = null;
809
- try { baseline = fs.statSync(metaFile).mtimeMs; } catch { return; }
810
- _authRecoveryTimer = setInterval(() => {
811
- try {
812
- const now = fs.statSync(metaFile).mtimeMs;
813
- if (now !== baseline) {
814
- baseline = now;
815
- _clearAuthRecoveryWatch();
816
- _writeBrokerHealth({ state: 'connecting', authBlocked: false, reauthorizationRequired: false, hint: 'Device metadata changed; retrying authentication.' });
817
- Promise.resolve(supervisor.start()).catch(() => { /* bounded by the supervisor */ });
818
- }
819
- } catch { /* metadata absent/unreadable: keep waiting */ }
820
- }, 30000);
821
- if (typeof _authRecoveryTimer.unref === 'function') _authRecoveryTimer.unref();
822
- };
823
- _writeBrokerHealth({ state: 'connecting' });
824
-
825
- console.log(`XKWDStore Agent broker v${CLI_VERSION} (machine-wide)`);
826
- console.log(`Machine root: ${machineState.getMachineRoot()}`);
827
- console.log(`Broker lock: ${lock.detail}`);
828
-
829
- // 3. connect to the server (broker owns the WebSocket).
830
- // `--offline` (test-lifecycle only) skips the server connection so the service
831
- // host / mutex / identity can be proven without a live enrollment. Production
832
- // always connects.
833
- const offline = !!flags.offline;
834
- let ws = null;
835
- if (offline) {
836
- console.log('Broker running OFFLINE (lifecycle test mode; no server connection)');
837
- }
838
-
839
- if (offline) {
840
- // Prove identity loads and the broker stays alive; keep the mutex held.
841
- const meta = (() => { try { return require('./deviceKeyStore').loadMetadata({ serverOrigin }); } catch { return null; } })();
842
- console.log(`Broker identity: ${meta && meta.deviceId ? meta.deviceId : '(none)'}`);
843
-
844
- // --probe-worker: open the bridge, launch the interactive worker, and report
845
- // the worker's Windows session id so the Session-0 -> interactive-session
846
- // launch is PROVEN with a real process. Lifecycle-test only.
847
- if (flags['probe-worker']) {
848
- const bridge = require('./brokerWorkerBridge');
849
- const token = bridge.newChannelToken();
850
- const channel = await bridge.openBrokerChannel({ token });
851
- console.log(`probe: bridge port ${channel.port}`);
852
- const child = _spawnInteractiveWorker({ port: channel.port, token });
853
- const deadline = Date.now() + 20000;
854
- while (!channel.connected && Date.now() < deadline) { await new Promise((r) => setTimeout(r, 150)); }
855
- console.log(`probe: worker connected=${channel.connected}`);
856
- console.log(`probe: activeConsoleSession=${_activeConsoleSession()} workerSession=${typeof child.session === 'number' ? child.session : 'n/a'}`);
857
- try {
858
- const st = await channel.call('getStatus', {}, 10000);
859
- console.log('probe: worker status ' + JSON.stringify(st));
860
- } catch (e) {
861
- console.log('probe: worker status error ' + ((e && e.message) || 'unknown'));
862
- }
863
- // Give the harness time to inspect the worker process, then stop it.
864
- await new Promise((r) => setTimeout(r, 12000));
865
- try { await channel.call('shutdown', {}, 5000); } catch { }
866
- try { channel.close(); } catch { }
867
- console.log('probe: done');
868
- machineLock.releaseMachineBrokerLock();
869
- process.exit(0);
870
- }
871
-
872
- console.log('Broker alive; holding the machine lock. Ctrl+C to stop.');
873
- const t = setInterval(() => {
874
- try { console.log('broker heartbeat ' + new Date().toISOString()); } catch { }
875
- }, 15000);
876
- t.unref();
877
- await new Promise(() => { }); // run until killed
878
- }
879
-
880
- // 4. spawn one interactive worker and route typed commands to it.
881
- const bridge = require('./brokerWorkerBridge');
882
- const token = bridge.newChannelToken();
883
- const channel = await bridge.openBrokerChannel({ token });
884
- const sessionHandler = require('./sessionHandler');
885
-
886
- // The broker does NOT launch Chromium: it forwards startSession/stopSession to
887
- // the worker. A worker is SESSION-BOUND: it is launched into the currently
888
- // ACTIVE console session and is DISPOSABLE — a worker left over from a previous
889
- // user (e.g. after a fast user switch) must NEVER serve a new session's job.
890
- let worker = null;
891
- let workerSession = -1;
892
- async function ensureWorker() {
893
- const active = _activeConsoleSession();
894
- // Reuse the connected worker ONLY when it is in the CURRENT active session.
895
- // On a change of active session the stale worker is torn down first (see the
896
- // pure `shouldReplaceWorker` truth table).
897
- const replace = bridge.shouldReplaceWorker({ connected: channel.connected, workerSession, activeSession: active });
898
- if (!replace) return;
899
- if (channel.connected) {
900
- try { console.log(`worker session ${workerSession} != active ${active}; replacing the worker`); } catch { }
901
- try { await channel.call('shutdown', {}, 5000); } catch { }
902
- try { channel.dropWorker(); } catch { }
903
- try { if (worker && worker.child) worker.child.kill(); } catch { }
904
- workerSession = -1;
905
- // Give the channel a moment to clear the old worker.
906
- await new Promise((r) => setTimeout(r, 300));
907
- }
908
- worker = _spawnInteractiveWorker({ port: channel.port, token });
909
- const deadline = Date.now() + 15000;
910
- while (!channel.connected && Date.now() < deadline) { await new Promise((r) => setTimeout(r, 100)); }
911
- if (!channel.connected) throw new Error('interactive worker did not attach');
912
- // The launcher reports the target session on its stdout; wait briefly for it.
913
- const sdeadline = Date.now() + 3000;
914
- while (workerSession === -1 && Date.now() < sdeadline) {
915
- workerSession = typeof worker.session === 'number' ? worker.session : -1;
916
- if (workerSession === -1) await new Promise((r) => setTimeout(r, 100));
917
- }
918
- try { console.log(`worker attached (session=${workerSession}, active=${active})`); } catch { }
919
- }
920
-
921
- const { setupSessionHandler, closeAllSessions, markDisconnected } = sessionHandler;
922
- const { createBrokerConnectionSupervisor } = require('./brokerConnectionSupervisor');
923
-
924
- // 4a. ONE reconnect supervisor owns the production WebSocket lifecycle so a
925
- // transient network/DNS/TLS/backend/WS/heartbeat loss reconnects with the
926
- // SAME enrolled identity — no manual restart, no re-pair, no new key. Retries
927
- // are UNBOUNDED for the machine service (a long-lived broker must self-heal);
928
- // the supervisor preserves exactly one timer / one attempt / one socket.
929
- const _bindSessionHandler = (socket) => setupSessionHandler(socket, {
930
- // The broker has no chromePath: all browser work goes through the worker.
931
- chromePath: null,
932
- deviceMeta: require('./deviceKeyStore').loadMetadata({ serverOrigin }) || {},
933
- serverOrigin,
934
- // 2.1.0: route browser commands through the worker bridge.
935
- workerBridge: {
936
- ensureWorker,
937
- call: (command, payload) => channel.call(command, payload),
938
- },
939
- });
940
-
941
- const supervisor = createBrokerConnectionSupervisor({
942
- connect: () => _brokerConnect(serverOrigin),
943
- // Rebind the FULL session handler on every (re)connect; the server drives
944
- // lease reconciliation from our sessions-report (protocol v2).
945
- onConnected: (socket) => {
946
- _clearAuthRecoveryWatch();
947
- _bindSessionHandler(socket);
948
- _writeBrokerHealth({ state: 'connected', authBlocked: false, reauthorizationRequired: false, authFailures: 0 });
949
- },
950
- // On a REAL disconnect stop accepting remote commands. Durable leases are
951
- // server-owned and are NOT released locally — the server reconciles them
952
- // after we reconnect.
953
- onDisconnected: () => { try { markDisconnected(); } catch { } },
954
- // Auth/identity rejection: PRESERVE the identity, notify once, and let the
955
- // supervisor bound the attempts. A revoked/replaced device must not create a
956
- // retry/log storm; status is written for `xkwd-agent status`.
957
- onAuthRejected: () => {
958
- try { console.error('[broker] authentication/identity rejected; identity preserved, retries bounded'); } catch { }
959
- _writeBrokerHealth({
960
- state: 'authentication_failed', authBlocked: true, reauthorizationRequired: false,
961
- lastDisconnectCode: 4003,
962
- hint: 'Device revoked or replaced. Owner approval is required before retrying.',
963
- });
964
- },
965
- onAuthBlocked: (info) => {
966
- _writeBrokerHealth({
967
- state: 'authentication_failed', authBlocked: true, reauthorizationRequired: true,
968
- authFailures: info && info.authFailures, lastDisconnectCode: info && info.code,
969
- lastDisconnectReason: info && info.reason,
970
- hint: 'Retries stopped. Ask the account owner to re-authorize this device, then run: xkwd-agent recover',
971
- });
972
- try { console.error('[broker] reauthorization required; automatic retries stopped (identity preserved)'); } catch { }
973
- _startAuthRecoveryWatch();
974
- },
975
- log: (m) => { try { console.log(m); } catch { } },
976
- });
977
- console.log(`Broker connecting to ${serverOrigin} ...`);
978
- Promise.resolve(supervisor.start()).catch(() => {});
979
-
980
- async function shutdown(signal) {
981
- console.log(`\n${signal} received. Broker shutting down...`);
982
- // Stop reconnecting FIRST so no retry can start after shutdown begins.
983
- _clearAuthRecoveryWatch();
984
- try { supervisor.stop(); } catch { }
985
- // Ask the interactive worker to close every owned browser and flush its
986
- // persistent profile. Only a VERIFIED close is a clean shutdown; a failure
987
- // is reported, never silently converted into success.
988
- let workerClosed = false;
989
- try {
990
- const res = await channel.call('shutdown', {}, 25000);
991
- workerClosed = !!(res && res.closed === true);
992
- if (!workerClosed) console.error('[broker] worker shutdown did not verify every browser close');
993
- } catch (err) {
994
- console.error('[broker] worker shutdown failed: ' + ((err && err.code) || 'WORKER_SHUTDOWN_FAILED'));
995
- }
996
- // The worker exits itself after closing. If it is still alive (a wedged
997
- // browser), terminate the worker process — the profile is preserved on disk
998
- // and is recoverable on the next start.
999
- try { if (worker && worker.exitCode == null) worker.kill(); } catch { }
1000
- try { channel.close(); } catch { }
1001
- try { await closeAllSessions(); } catch { }
1002
- machineLock.releaseMachineBrokerLock();
1003
- process.exit(0);
1004
- }
1005
- process.on('SIGINT', () => shutdown('Ctrl+C'));
1006
- process.on('SIGTERM', () => shutdown('SIGTERM'));
1007
- }
1008
-
1009
- /** The currently ACTIVE Windows console session id, via the compiled launcher's
1010
- * `-Query` mode. Returns -1 when it cannot be determined (fail-safe). */
1011
- function _activeConsoleSession() {
1012
- try {
1013
- const path = require('path');
1014
- const fs = require('fs');
1015
- const { execFileSync } = require('child_process');
1016
- const machineRoot = require('./machineState').getMachineRoot();
1017
- const launcherExe = path.join(machineRoot, 'launcher', 'XKWDStoreSessionLauncher.exe');
1018
- if (os.platform() !== 'win32' || !fs.existsSync(launcherExe)) return -1;
1019
- const out = execFileSync(launcherExe, ['-Query'], { encoding: 'utf8', windowsHide: true, timeout: 5000 }).trim();
1020
- const m = /SESSION=(-?\d+)/.exec(out);
1021
- return m ? parseInt(m[1], 10) : -1;
1022
- } catch { return -1; }
1023
- }
1024
-
1025
- /** Spawn an interactive browser worker into the ACTIVE INTERACTIVE session.
1026
- *
1027
- * The broker runs as a Session-0 service, which has no desktop. A plain
1028
- * child_process.spawn would create the worker (and its Chromium) in Session 0,
1029
- * where no browser can be shown. When the broker is in Session 0 we therefore
1030
- * launch the worker via the compiled session launcher (CreateProcessAsUser with
1031
- * the active console session's user token). When the broker already runs in an
1032
- * interactive session (foreground `start`), a direct spawn is equivalent.
1033
- *
1034
- * Returns { child, session } where `session` is the Windows session the worker
1035
- * was launched into (or -1 when unknown). The broker records this so it never
1036
- * reuses a worker from a session that is no longer the active console session.
1037
- */
1038
- function _spawnInteractiveWorker({ port, token }) {
1039
- const { spawn } = require('child_process');
1040
- const path = require('path');
1041
- const fs = require('fs');
1042
- const workerScript = path.join(__dirname, 'worker.js');
1043
- const workerArgs = ['--port', String(port), '--token', token];
1044
-
1045
- const machineRoot = require('./machineState').getMachineRoot();
1046
- const launcherExe = path.join(machineRoot, 'launcher', 'XKWDStoreSessionLauncher.exe');
1047
-
1048
- if (os.platform() === 'win32' && fs.existsSync(launcherExe)) {
1049
- // Launch into the active interactive session. The launcher prints
1050
- // `LAUNCHED pid=N session=S`; capture it so the worker is session-bound.
1051
- const logDir = path.join(machineRoot, 'logs');
1052
- try { fs.mkdirSync(logDir, { recursive: true }); } catch { }
1053
- const outLog = path.join(logDir, 'worker.out.log');
1054
- const errLog = path.join(logDir, 'worker.err.log');
1055
- const child = spawn(launcherExe, [
1056
- '-Exe', process.execPath,
1057
- '-Args', '"' + workerScript + '" ' + workerArgs.join(' '),
1058
- '-Cwd', __dirname,
1059
- '-Out', outLog,
1060
- '-Err', errLog,
1061
- ], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
1062
- let session = -1;
1063
- let buf = '';
1064
- try {
1065
- child.stdout.on('data', (d) => {
1066
- buf += d.toString();
1067
- const m = /session=(-?\d+)/.exec(buf);
1068
- if (m) session = parseInt(m[1], 10);
1069
- });
1070
- } catch { }
1071
- return { child, get session() { return session; } };
1072
- }
1073
-
1074
- // Interactive/foreground fallback: the broker is already in the right session.
1075
- const child = spawn(process.execPath, [workerScript, ...workerArgs], {
1076
- detached: false,
1077
- stdio: ['ignore', 'inherit', 'inherit'],
1078
- windowsHide: true,
1079
- });
1080
- return { child, session: _activeConsoleSession() };
1081
- }
1082
-
1083
- /** Connect the broker's WebSocket using the machine credential. */
1084
- async function _brokerConnect(serverOrigin) {
1085
- const { getStoredDevice, getStoredPrivateKey } = require('./enrollmentClient');
1086
- const deviceMeta = getStoredDevice({ serverOrigin });
1087
- const privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
1088
- if (!deviceMeta || !privateKeyB64Url) {
1089
- throw new Error('device is not enrolled; run `xkwd-agent start` once to authorize this machine');
1090
- }
1091
- const { connectWebSocket } = require('./wsClient');
1092
- return connectWebSocket({
1093
- serverOrigin,
1094
- deviceId: deviceMeta.deviceId,
1095
- publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
1096
- privateKeyB64Url,
1097
- protocolVersion: PROTOCOL_VERSION,
1098
- });
1099
- }
1100
-
1101
- /**
1102
- * `xkwd-agent doctor` — diagnostic checks.
1103
- */
1104
- async function doctor(serverOrigin) {
1105
- console.log(`XKWDStore Agent v${CLI_VERSION} — Diagnostics\n`);
1106
-
1107
- // Check Node version
1108
- const nodeVersion = process.versions.node;
1109
- const major = parseInt(nodeVersion.split('.')[0], 10);
1110
- console.log(`Node.js: ${nodeVersion} ${major >= 22 ? '✓' : '✗ (requires Node.js 22+)'}`);
1111
-
1112
- // Check platform
1113
- console.log(`Platform: ${os.platform()} ${os.arch()}`);
1114
- console.log(`Hostname: ${os.hostname()}`);
1115
-
1116
- // Check Chrome
1117
- try {
1118
- const { resolveChromeOrFail } = require('./chromeDetector');
1119
- const chrome = resolveChromeOrFail();
1120
- console.log(`Chrome: ${chrome.chromeVersion || 'detected'} ✓`);
1121
- } catch (e) {
1122
- console.log(`Chrome: ✗ (${e.message.split('\n')[0]})`);
1123
- }
1124
-
1125
- // Check secure storage (real DPAPI + ACL probe on Windows)
1126
- const { isSecureStorageAvailable, getDataDir, probeWindowsStorage } = require('./deviceKeyStore');
1127
- const platform = os.platform();
1128
- if (platform === 'win32') {
1129
- console.log('Secure storage: probing real DPAPI + ACL stages...');
1130
- const probe = probeWindowsStorage();
1131
- console.log(` DPAPI Protect : ${probe.stages.protect ? '✓' : '✗'}`);
1132
- console.log(` DPAPI Unprotect: ${probe.stages.unprotect ? '✓' : '✗'}`);
1133
- console.log(` Windows SID : ${probe.stages.sidLookup ? '✓' : '✗'}`);
1134
- console.log(` ACL apply : ${probe.stages.aclApply ? '✓' : '✗'}`);
1135
- console.log(` ACL verify : ${probe.stages.aclVerify ? '✓' : '✗'}`);
1136
- console.log(`Secure storage: ${probe.ok ? 'available ✓' : 'unavailable ✗'}`);
1137
- if (!probe.ok && probe.detail) {
1138
- console.log(` Detail: ${probe.detail}`);
1139
- }
1140
- } else {
1141
- console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available ✓' : 'unavailable ✗'}`);
1142
- }
1143
-
1144
- // Check data directory (machine-wide since 2.1.0)
1145
- const dataDir = getDataDir();
1146
- const legacyDir = require('./deviceKeyStore').getLegacyDataDir();
1147
- console.log(`Machine state root: ${dataDir}`);
1148
- console.log(`Legacy per-user root: ${legacyDir}`);
1149
- const machineState = require('./machineState');
1150
- console.log(`Machine identity present: ${machineState.hasMachineIdentity() ? '✓' : '(none yet)'}`);
1151
-
1152
- // Check device identity (server-scoped)
1153
- const { getStoredDevice, getStoredPrivateKey } = require('./enrollmentClient');
1154
- const device = getStoredDevice({ serverOrigin });
1155
- if (device) {
1156
- console.log(`Device ID: ${device.deviceId} ✓`);
1157
- const privateKey = await getStoredPrivateKey({ serverOrigin });
1158
- console.log(`Private key: ${privateKey ? 'stored ✓' : 'missing ✗'}`);
1159
- } else {
1160
- console.log('Device ID: not enrolled for this server');
1161
- }
1162
- const brokerHealthModule = require('./brokerHealth');
1163
- const brokerHealth = brokerHealthModule.readBrokerHealth() || brokerHealthModule.readBrokerLogAuthState();
1164
- if (brokerHealth) {
1165
- console.log(`Broker health: ${brokerHealth.state || 'unknown'}${brokerHealth.reauthorizationRequired ? ' — REAUTHORIZATION REQUIRED' : ''}`);
1166
- if (brokerHealth.authFailures) console.log(` Consecutive auth failures: ${brokerHealth.authFailures}`);
1167
- if (brokerHealth.hint) console.log(` Action: ${brokerHealth.hint}`);
1168
- }
1169
-
1170
- // Check server connectivity (shared strict validator)
1171
- try {
1172
- const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
1173
- const resp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
1174
- const compat = validateCompatibilityResponse(resp);
1175
- if (compat.html) {
1176
- console.log(`Server (${serverOrigin}): compatibility endpoint returned frontend ✗`);
1177
- console.log(' ' + COMPAT_HTML_MESSAGE);
1178
- } else if (compat.ok) {
1179
- console.log(`Server (${serverOrigin}): reachable ✓`);
1180
- console.log(` Protocol version: ${compat.body.protocolVersion}`);
1181
- console.log(` Min agent version: ${compat.body.minimumAgentVersion}`);
1182
- console.log(` Recommended agent version: ${compat.body.recommendedAgentVersion}`);
1183
- } else {
1184
- console.log(`Server (${serverOrigin}): compatibility check failed ✗`);
1185
- console.log(` Reason: ${compat.reason}`);
1186
- }
1187
- } catch (e) {
1188
- console.log(`Server (${serverOrigin}): unreachable ✗ (${e.message})`);
1189
- }
1190
- }
1191
-
1192
- /**
1193
- * `xkwd-agent version` — print version.
1194
- */
1195
- function version() {
1196
- console.log(`@xkwdstore/agent v${CLI_VERSION}`);
1197
- console.log(`Protocol version: ${PROTOCOL_VERSION}`);
1198
- console.log(`Node.js: ${process.versions.node}`);
1199
- }
1200
-
1201
- /**
1202
- * `xkwd-agent help` — print help.
1203
- */
1204
- function help() {
1205
- console.log(`XKWDStore Agent v${CLI_VERSION}
1206
-
1207
- Usage:
1208
- xkwd-agent <command> [options]
1209
-
1210
- Commands:
1211
- start Start the agent (connects to server, runs browser sessions)
1212
- status Show device and connection status
1213
- recover Re-authorize THIS device after revocation/replacement (owner approval)
1214
- logout Delete local device identity (requires re-authorization)
1215
- revoke-local Delete local device identity and credentials
1216
- machine Machine-wide state: status | adopt | harden
1217
- service Run the machine-wide broker (Windows Service host; silent)
1218
- doctor Run diagnostic checks
1219
- version Print version information
1220
- help Show this help
1221
-
1222
- Options:
1223
- --server=<url> Server URL (default: https://x.kwdstore.com)
1224
- --replace Replace a running instance (safe takeover)
1225
-
1226
- Examples:
1227
- xkwd-agent start
1228
- xkwd-agent start --replace
1229
- xkwd-agent status
1230
- xkwd-agent recover
1231
- xkwd-agent machine status
1232
- xkwd-agent doctor
1233
-
1234
- First run:
1235
- The agent will open your browser to authorize this computer.
1236
- No pairing code, email, or API key is required.
1237
-
1238
- To stop:
1239
- Press Ctrl+C in the terminal.
1240
-
1241
- Data location (machine-wide, shared by every Windows user on this PC):
1242
- Windows: %ProgramData%\\XKWDStore\\Agent\\
1243
- Linux: ${'{XDG_DATA_HOME:-~/.local/share}/xkwdstore/'}
1244
- macOS: unsupported (fails closed)
1245
-
1246
- Device identity belongs to the MACHINE. Changing the Windows user or the
1247
- TW-manager preferred device does NOT create a second device identity.
1248
- A pre-2.1.0 per-user install is adopted once (copy, never move).
1249
-
1250
- Requirements:
1251
- - Node.js 22 or later
1252
- - Google Chrome installed
1253
- `);
1254
- }
1255
-
1256
- // ── Helpers ──────────────────────────────────────────────────────────────────
1257
-
1258
- /**
1259
- * Detect whether a connection error is a 4003 authentication failure.
1260
- * The wsClient rejects with a message containing "Device authentication
1261
- * failed" when the server closes with code 4003. The error may also carry
1262
- * a .code property in some implementations.
1263
- */
1264
- function _is4003Error(err) {
1265
- if (!err) return false;
1266
- const msg = (err.message || String(err)).toLowerCase();
1267
- if (err.code === 4003) return true;
1268
- if (msg.includes('device authentication failed')) return true;
1269
- if (msg.includes('4003')) return true;
1270
- return false;
1271
- }
1272
-
1273
- function _compareVersions(a, b) {
1274
- const pa = a.split('.').map(Number);
1275
- const pb = b.split('.').map(Number);
1276
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
1277
- const va = pa[i] || 0;
1278
- const vb = pb[i] || 0;
1279
- if (va > vb) return 1;
1280
- if (va < vb) return -1;
1281
- }
1282
- return 0;
1283
- }
1284
-
1285
- // ── Entry point ──────────────────────────────────────────────────────────────
1286
-
1287
- if (require.main === module) {
1288
- main();
1289
- }
1290
-
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> recover
15
+ * npx --yes @xkwdstore/agent@<PINNED_VERSION> logout
16
+ * npx --yes @xkwdstore/agent@<PINNED_VERSION> revoke-local
17
+ * npx --yes @xkwdstore/agent@<PINNED_VERSION> doctor
18
+ * npx --yes @xkwdstore/agent@<PINNED_VERSION> version
19
+ *
20
+ * The agent runs only while the terminal process is running.
21
+ * Closing the terminal or pressing Ctrl+C stops the agent cleanly.
22
+ */
23
+
24
+ const crypto = require('crypto');
25
+ const os = require('os');
26
+ const path = require('path');
27
+
28
+ const CLI_VERSION = '2.1.7';
29
+ const PROTOCOL_VERSION = 2;
30
+
31
+ // ── Command parsing ──────────────────────────────────────────────────────────
32
+
33
+ function main() {
34
+ const args = process.argv.slice(2);
35
+ const command = args[0] || 'help';
36
+ const flags = {};
37
+ const positional = [];
38
+
39
+ for (let i = 1; i < args.length; i++) {
40
+ const arg = args[i];
41
+ if (arg.startsWith('--')) {
42
+ const key = arg.slice(2);
43
+ const next = args[i + 1];
44
+ if (next && !next.startsWith('--')) {
45
+ flags[key] = next;
46
+ i++;
47
+ } else {
48
+ flags[key] = true;
49
+ }
50
+ } else {
51
+ positional.push(arg);
52
+ }
53
+ }
54
+
55
+ const serverOrigin = flags.server ||
56
+ process.env.XKWDSTORE_SERVER ||
57
+ 'https://x.kwdstore.com';
58
+
59
+ switch (command) {
60
+ case 'start':
61
+ return start(serverOrigin, flags);
62
+ case 'status':
63
+ return status();
64
+ case 'recover':
65
+ return recover(serverOrigin);
66
+ case 'logout':
67
+ return logout();
68
+ case 'revoke-local':
69
+ return revokeLocal();
70
+ case 'doctor':
71
+ return doctor(serverOrigin);
72
+ case 'machine':
73
+ return machine(positional);
74
+ case 'service':
75
+ return service(serverOrigin, flags);
76
+ case 'key-probe': {
77
+ // Diagnostics: report whether the machine credential can be decrypted in
78
+ // THIS process context (e.g. from the LocalSystem service) WITHOUT
79
+ // printing any secret. Used by the elevated lifecycle gate.
80
+ (async () => {
81
+ const fs = require('fs');
82
+ const path = require('path');
83
+ const { loadMetadata, loadPrivateKeyFromStorage, getMachineRoot, _identitySourceRoots, _serversDirFor } = require('./deviceKeyStore');
84
+ const { normalizeServerOrigin } = require('./deviceKeyStore');
85
+ const meta = loadMetadata({ serverOrigin });
86
+ const out = {
87
+ context: { user: require('os').userInfo().username, platform: os.platform(), pid: process.pid },
88
+ machineRoot: getMachineRoot(),
89
+ deviceId: meta ? meta.deviceId : null,
90
+ privateKeyDecryptable: false,
91
+ stages: {},
92
+ error: '',
93
+ };
94
+ // Stage 1: locate the key file the loader would use.
95
+ let keyFile = null;
96
+ try {
97
+ const roots = _identitySourceRoots();
98
+ const label = normalizeServerOrigin(serverOrigin);
99
+ const candidates = [];
100
+ for (const r of [roots.source, roots.target]) {
101
+ if (r) candidates.push(path.join(_serversDirFor(r), label, '.device-key'));
102
+ }
103
+ for (const r of [roots.source, roots.target]) { if (r) candidates.push(path.join(r, '.device-key')); }
104
+ out.stages.candidates = candidates;
105
+ for (const c of candidates) { if (fs.existsSync(c)) { keyFile = c; break; } }
106
+ out.stages.keyFile = keyFile;
107
+ out.stages.keyReadable = keyFile ? (() => { try { fs.accessSync(keyFile, fs.constants.R_OK); return true; } catch { return false; } })() : false;
108
+ if (keyFile) {
109
+ try {
110
+ const env = JSON.parse(fs.readFileSync(keyFile, 'utf8'));
111
+ out.stages.envelopeScheme = env.scheme;
112
+ out.stages.envelopeScope = env.scope || '(v1/unscoped)';
113
+ out.stages.envelopeV = env.v;
114
+ } catch (e) { out.stages.envelopeError = (e && e.message) || 'parse'; }
115
+ }
116
+ } catch (e) { out.stages.locateError = (e && e.message) || 'locate'; }
117
+ // Stage 2: full loader (includes ACL verify).
118
+ try { out.privateKeyDecryptable = !!(await loadPrivateKeyFromStorage({ serverOrigin })); } catch (e) { out.error = (e && e.message) || 'error'; }
119
+ console.log(JSON.stringify(out));
120
+ })().catch((e) => { console.error(JSON.stringify({ error: (e && e.message) || 'fatal' })); process.exit(1); });
121
+ return;
122
+ }
123
+ case 'version':
124
+ return version();
125
+ case 'help':
126
+ case '--help':
127
+ case '-h':
128
+ default:
129
+ return help();
130
+ }
131
+ }
132
+
133
+ // ── Commands ─────────────────────────────────────────────────────────────────
134
+
135
+ /**
136
+ * `xkwd-agent start` — the main runtime command.
137
+ */
138
+ async function start(serverOrigin, flags) {
139
+ console.log(`XKWDStore Agent v${CLI_VERSION} (protocol v${PROTOCOL_VERSION})`);
140
+ console.log(`Server: ${serverOrigin}`);
141
+
142
+ // 0. Machine-wide state: create the ProgramData layout and adopt any
143
+ // pre-2.1.0 per-user identity ONCE (copy, never move). The device identity
144
+ // therefore belongs to the MACHINE, not to the current Windows user.
145
+ try {
146
+ const machineState = require('./machineState');
147
+ const init = machineState.initializeMachineState();
148
+ console.log(`✓ Machine state: ${init.root}`);
149
+ if (init.adopted && init.deviceId) {
150
+ console.log(`✓ Adopted existing device identity: ${init.deviceId}`);
151
+ }
152
+ } catch (e) {
153
+ console.error(`Machine state initialization failed: ${(e && e.message) || 'unknown'}`);
154
+ process.exit(1);
155
+ }
156
+ console.log();
157
+
158
+ // 1. Detect OS and architecture (for display)
159
+ const platform = os.platform();
160
+ const arch = os.arch();
161
+ const hostname = os.hostname();
162
+ console.log(`✓ Detected computer: ${hostname}`);
163
+ console.log(`✓ Platform: ${platform} ${arch}`);
164
+
165
+ // 2. Resolve system Chrome (fail clearly if missing)
166
+ const { resolveChromeOrFail } = require('./chromeDetector');
167
+ let chromePath, chromeVersion;
168
+ try {
169
+ const chrome = resolveChromeOrFail();
170
+ chromePath = chrome.chromePath;
171
+ chromeVersion = chrome.chromeVersion;
172
+ console.log(`✓ Chrome ${chromeVersion || 'detected'}: ${chromePath}`);
173
+ } catch (e) {
174
+ console.error(e.message);
175
+ process.exit(1);
176
+ }
177
+
178
+ // 3. Check compatibility with server (shared strict validator)
179
+ const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
180
+ try {
181
+ const compatResp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
182
+ const compat = validateCompatibilityResponse(compatResp);
183
+ if (compat.html) {
184
+ console.error('\n' + COMPAT_HTML_MESSAGE);
185
+ process.exit(1);
186
+ }
187
+ if (!compat.ok) {
188
+ console.error('\nServer compatibility check failed: ' + compat.reason + '.');
189
+ console.error('The agent will not start enrollment until the server is compatible.');
190
+ process.exit(1);
191
+ }
192
+ // NOTE: the server's declared `capabilities` are INFORMATIONAL. They are
193
+ // never a reason to refuse a server — a server that does not advertise the
194
+ // profile-identity capability may still supply the identity tuple, and every
195
+ // currently-deployed backend omits the field. A missing capability must not
196
+ // block startup (see validateCompatibilityResponse).
197
+ // compat.ok — enforce minimum agent version
198
+ const minVer = compat.body.minimumAgentVersion;
199
+ const recVer = compat.body.recommendedAgentVersion;
200
+ if (minVer && _compareVersions(CLI_VERSION, minVer) < 0) {
201
+ console.error(`\nThis agent version (${CLI_VERSION}) is no longer supported.`);
202
+ console.error(`\nRun:\n\n npx --yes @xkwdstore/agent@${recVer} start\n`);
203
+ process.exit(1);
204
+ }
205
+ } catch (e) {
206
+ console.error(`\nServer compatibility check failed: ${e.message}`);
207
+ console.error('The agent will not start enrollment until the server is reachable and compatible.');
208
+ process.exit(1);
209
+ }
210
+
211
+ // 4. Load or generate device key (server-scoped: per-server identity)
212
+ const { getStoredDevice, getStoredPrivateKey, enroll } = require('./enrollmentClient');
213
+ const { isSecureStorageAvailable } = require('./deviceKeyStore');
214
+
215
+ if (!isSecureStorageAvailable()) {
216
+ console.error('Secure key storage is unavailable on this system.');
217
+ if (os.platform() === 'win32') {
218
+ console.error('On Windows, ensure System32\\WindowsPowerShell\\v1.0\\powershell.exe is present and DPAPI is available.');
219
+ } else {
220
+ console.error('On Linux, install gnome-keyring or seahorse (libsecret).');
221
+ }
222
+ console.error('The agent cannot run without secure key storage.');
223
+ process.exit(1);
224
+ }
225
+
226
+ let deviceMeta = getStoredDevice({ serverOrigin });
227
+ let privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
228
+
229
+ // 5. Authorize the device when needed (first run or revoked)
230
+ if (!deviceMeta || !privateKeyB64Url) {
231
+ console.log('\n✓ Device identity loaded securely');
232
+ try {
233
+ const result = await enroll(serverOrigin, { chromePath });
234
+ deviceMeta = require('./deviceKeyStore').loadMetadata({ serverOrigin });
235
+ privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
236
+ } catch (e) {
237
+ console.error(`\nEnrollment failed: ${e.message}`);
238
+ process.exit(1);
239
+ }
240
+ } else {
241
+ console.log(`✓ Device identity loaded securely`);
242
+ console.log(`✓ Device recognized: ${deviceMeta.deviceName}`);
243
+ }
244
+
245
+ // 6. Process lock (prevent duplicate instances)
246
+ const processLock = require('./processLock');
247
+ const lockResult = processLock.acquireLock({
248
+ deviceId: deviceMeta.deviceId,
249
+ deviceName: deviceMeta.deviceName,
250
+ });
251
+
252
+ if (!lockResult.acquired) {
253
+ if (flags.replace) {
254
+ console.log('\nAnother agent instance is running. Requesting takeover...');
255
+ const took = await processLock.requestTakeover(lockResult.existing);
256
+ if (!took) {
257
+ console.error('Could not stop the existing instance. Please close it manually.');
258
+ process.exit(1);
259
+ }
260
+ // Re-acquire the lock
261
+ const retryLock = processLock.acquireLock({
262
+ deviceId: deviceMeta.deviceId,
263
+ deviceName: deviceMeta.deviceName,
264
+ });
265
+ if (!retryLock.acquired) {
266
+ console.error('Could not acquire process lock after takeover.');
267
+ process.exit(1);
268
+ }
269
+ } else {
270
+ console.error('\nXKWDStore Agent is already running on this computer.');
271
+ console.error(`PID: ${lockResult.existing.pid}`);
272
+ console.error(`Started: ${lockResult.existing.startedAt}`);
273
+ console.error(`Device: ${lockResult.existing.deviceName || 'unknown'}`);
274
+ console.error('\nTo replace the running instance, use:');
275
+ console.error(' xkwd-agent start --replace');
276
+ process.exit(1);
277
+ }
278
+ }
279
+
280
+ // 7. Connect securely via WebSocket challenge-response
281
+ // 4003 auto-recovery: if the initial connection fails with 4003 (revoked/
282
+ // unknown device), the agent automatically performs a server-scoped
283
+ // re-enrollment and reconnects in the SAME process flow — the user does
284
+ // NOT need to type a second command. Only ONE auto-recovery attempt is
285
+ // allowed per startup to prevent infinite loops.
286
+ const { connectWebSocket } = require('./wsClient');
287
+ let ws;
288
+ let autoRecovered = false;
289
+
290
+ try {
291
+ ws = await connectWebSocket({
292
+ serverOrigin,
293
+ deviceId: deviceMeta.deviceId,
294
+ publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
295
+ privateKeyB64Url,
296
+ protocolVersion: PROTOCOL_VERSION,
297
+ });
298
+ } catch (connectErr) {
299
+ // Check if this is a 4003 authentication failure (revoked/unknown device).
300
+ // The wsClient rejects with a message containing "Device authentication
301
+ // failed" for 4003 close codes, or the error may carry a .code property.
302
+ const isAuthFailure = _is4003Error(connectErr);
303
+
304
+ if (isAuthFailure && !autoRecovered) {
305
+ autoRecovered = true;
306
+ console.error('\n❌ Authentication failed (4003) — this device may be revoked.');
307
+ console.error(' Automatically re-authorizing for ' + serverOrigin + '...');
308
+ console.error(' (Other servers\' identities are NOT affected.)');
309
+
310
+ // Release the lock before re-enrollment (enrollment opens a browser)
311
+ processLock.releaseLock();
312
+
313
+ // Delete only this server's identity
314
+ const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
315
+ await deletePrivateKey({ serverOrigin });
316
+ deleteMetadata({ serverOrigin });
317
+ console.error('✓ Old identity cleared for ' + serverOrigin);
318
+
319
+ // Re-enroll automatically (opens browser for approval)
320
+ console.log('\nOpening authorization page...');
321
+ try {
322
+ await enroll(serverOrigin, { chromePath });
323
+ deviceMeta = require('./deviceKeyStore').loadMetadata({ serverOrigin });
324
+ privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
325
+
326
+ if (!deviceMeta || !privateKeyB64Url) {
327
+ console.error('\n❌ Re-enrollment completed but identity could not be loaded.');
328
+ process.exit(1);
329
+ }
330
+ console.log('✓ New identity stored for ' + serverOrigin);
331
+ } catch (enrollErr) {
332
+ console.error(`\n❌ Automatic re-enrollment failed: ${enrollErr.message}`);
333
+ console.error(' Run `xkwd-agent start` again to retry manually.');
334
+ process.exit(1);
335
+ }
336
+
337
+ // Re-acquire the process lock with the new device identity
338
+ const retryLock = processLock.acquireLock({
339
+ deviceId: deviceMeta.deviceId,
340
+ deviceName: deviceMeta.deviceName,
341
+ });
342
+ if (!retryLock.acquired) {
343
+ console.error('Could not acquire process lock after re-enrollment.');
344
+ if (flags.replace) {
345
+ const took = await processLock.requestTakeover(retryLock.existing);
346
+ if (!took) {
347
+ console.error('Could not stop the existing instance. Please close it manually.');
348
+ process.exit(1);
349
+ }
350
+ } else {
351
+ process.exit(1);
352
+ }
353
+ }
354
+
355
+ // Attempt to reconnect with the new identity (only ONE retry)
356
+ try {
357
+ ws = await connectWebSocket({
358
+ serverOrigin,
359
+ deviceId: deviceMeta.deviceId,
360
+ publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
361
+ privateKeyB64Url,
362
+ protocolVersion: PROTOCOL_VERSION,
363
+ });
364
+ console.log('\n✓ Re-authorized and reconnected automatically.');
365
+ } catch (retryErr) {
366
+ if (_is4003Error(retryErr)) {
367
+ console.error('\n❌ Authentication failed again after re-enrollment.');
368
+ console.error(' The new device may not have been approved on the dashboard.');
369
+ console.error(' Run `xkwd-agent start` again after approving the device.');
370
+ } else {
371
+ console.error(`\n❌ Reconnection failed: ${retryErr.message}`);
372
+ console.error(' Run `xkwd-agent start` again to retry.');
373
+ }
374
+ processLock.releaseLock();
375
+ process.exit(1);
376
+ }
377
+ } else {
378
+ // Non-4003 error, or 4003 after auto-recovery already attempted
379
+ console.error(`\nConnection failed: ${connectErr.message}`);
380
+ if (isAuthFailure) {
381
+ console.error(' Automatic recovery was already attempted. Run `xkwd-agent start` again.');
382
+ }
383
+ processLock.releaseLock();
384
+ process.exit(1);
385
+ }
386
+ }
387
+
388
+ console.log('✓ Secure challenge passed');
389
+ console.log('✓ Connected');
390
+ console.log('\nAgent is running. Press Ctrl+C to stop.\n');
391
+
392
+ // Keep SQLite-style registry state honest: the handler owns session
393
+ // registration; ensure the machine runtime dir exists before the first launch.
394
+ try {
395
+ const ms = require('./machineState');
396
+ ms.ensureMachineLayout();
397
+ } catch { /* best-effort */ }
398
+
399
+ // 8. Set up browser session handler (delegates to existing session management)
400
+ const { setupSessionHandler, closeAllSessions, markDisconnected, recoverOrphanedSessions } = require('./sessionHandler');
401
+
402
+ // 2.1.0 F1: crash recovery. A previous agent process may have left an
403
+ // Agent-OWNED Chromium behind (it is alive but unmanaged). Release the stale
404
+ // LOCAL locks for those proven-owned sessions so the accounts are not blocked
405
+ // on this device. The SERVER durable lease is authoritative and is NOT touched
406
+ // here — server recovery (recovery-probe / reconcile) still governs it.
407
+ try {
408
+ const recovery = recoverOrphanedSessions();
409
+ if (recovery.orphans > 0) {
410
+ console.log(`ℹ️ Crash recovery: found ${recovery.orphans} Agent-owned orphaned browser(s); released ${recovery.released} local lock(s).`);
411
+ }
412
+ } catch { /* never block startup on recovery */ }
413
+
414
+ const { createBrokerConnectionSupervisor } = require('./brokerConnectionSupervisor');
415
+
416
+ // 8a. Disconnect handling — the SAME reconnect supervisor as the machine
417
+ // `service` broker. The foreground agent adopts the already-authenticated
418
+ // socket; the supervisor owns every subsequent (re)connect, guaranteeing one
419
+ // timer / one attempt / one live socket, with unbounded self-healing that uses
420
+ // the SAME enrolled identity (transport recovery only, never a new identity).
421
+ //
422
+ // Interactive-path policy preserved:
423
+ // - server-initiated restart (1000 'agent-restart' / 4002 'Server-initiated
424
+ // restart'): rebind WITHOUT touching local browsers — the server reconciles
425
+ // leases from our sessions-report after reconnect.
426
+ // - any OTHER close: mark disconnected + close all browser contexts (profiles
427
+ // persist), then reconnect.
428
+ // - 4003 revoked mid-session: clear THIS server's identity and stop (explicit
429
+ // re-authorization) — the supervisor NEVER regenerates identity.
430
+ const _isRestartClose = (code, reasonStr) =>
431
+ (code === 1000 && /agent-restart/i.test(reasonStr))
432
+ || (code === 4002 && /server-initiated restart/i.test(reasonStr));
433
+
434
+ const supervisor = createBrokerConnectionSupervisor({
435
+ connect: () => connectWebSocket({
436
+ serverOrigin,
437
+ deviceId: deviceMeta.deviceId,
438
+ publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
439
+ privateKeyB64Url,
440
+ protocolVersion: PROTOCOL_VERSION,
441
+ }),
442
+ onConnected: (socket) => { setupSessionHandler(socket, { chromePath, deviceMeta, serverOrigin }); },
443
+ onDisconnected: async ({ code, reason }) => {
444
+ const reasonStr = reason || '';
445
+ if (_isRestartClose(code, reasonStr)) {
446
+ console.log('\nℹ️ Server requested a connection restart. Reconnecting (browser sessions stay open)...');
447
+ return; // keep local browsers; the server reconciles leases
448
+ }
449
+ console.error(`\n✗ Connection to server lost (code ${code}${reasonStr ? ': ' + reasonStr : ''}).`);
450
+ console.error(' Closing all browser sessions and reconnecting safely...');
451
+ markDisconnected();
452
+ try { await closeAllSessions(); } catch { }
453
+ },
454
+ onAuthRejected: () => {
455
+ // 4003: the credential is dead. PRESERVE the device identity and browser
456
+ // profiles — a revoked device can be recovered without re-enrolling into a
457
+ // new device id (which would orphan the device-bound profiles). Never
458
+ // delete the key here; only an explicit `logout`/`revoke-local` does that.
459
+ console.error('\n❌ Authentication failed — this device is no longer authorized.');
460
+ console.error(' It may have been revoked, or replaced by another computer (single-device policy).');
461
+ console.error(' Device identity and browser profiles were preserved.');
462
+ console.error(' Ask the account owner to re-authorize THIS device, then run:');
463
+ console.error(` xkwd-agent recover --server=${serverOrigin}`);
464
+ console.error(' (Recovery requires owner approval and will revoke the currently active device.)');
465
+ },
466
+ onAuthBlocked: () => {
467
+ // Permanent class: the supervisor has stopped retrying. Do not exit in a
468
+ // loop and do not regenerate identity; make the required action visible.
469
+ console.error('\n❌ Reauthorization required. Automatic retries have stopped (identity preserved).');
470
+ console.error(` Run \`xkwd-agent recover --server=${serverOrigin}\` after the account owner approves.`);
471
+ try { processLock.releaseLock(); } catch { /* best effort */ }
472
+ process.exit(1);
473
+ },
474
+ onExhausted: () => {
475
+ console.error('\n❌ Could not reconnect. Run `xkwd-agent start` again.');
476
+ processLock.releaseLock();
477
+ process.exit(1);
478
+ },
479
+ maxAttempts: 10,
480
+ log: (m) => { try { console.log(m); } catch { } },
481
+ });
482
+ supervisor.adopt(ws);
483
+
484
+ // Deliberate-shutdown guard (set before closing anything, so a close emitted
485
+ // during shutdown cannot trigger a reconnect).
486
+ let shuttingDown = false;
487
+
488
+ // 9. Clean shutdown on Ctrl+C
489
+ async function shutdown(signal) {
490
+ if (shuttingDown) return;
491
+ shuttingDown = true;
492
+ console.log(`\n${signal} received. Shutting down...`);
493
+
494
+ // Stop reconnecting FIRST so no retry can start after shutdown begins.
495
+ try { supervisor.stop(); } catch { }
496
+
497
+ // Stop accepting commands immediately.
498
+ markDisconnected();
499
+
500
+ // Close all browser sessions (preserves profiles/cookies via the
501
+ // existing safe persistence path).
502
+ try {
503
+ await closeAllSessions();
504
+ } catch {}
505
+
506
+ // Release lock
507
+ processLock.releaseLock();
508
+
509
+ process.exit(0);
510
+ }
511
+
512
+ process.on('SIGINT', () => shutdown('Ctrl+C'));
513
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
514
+ process.on('SIGHUP', () => shutdown('SIGHUP'));
515
+
516
+ // Also release the lock on uncaught exceptions
517
+ process.on('uncaughtException', (err) => {
518
+ console.error('Uncaught error:', err.message);
519
+ processLock.releaseLock();
520
+ process.exit(1);
521
+ });
522
+ }
523
+
524
+ /**
525
+ * `xkwd-agent status` — show device and connection status.
526
+ */
527
+ function status() {
528
+ const { getStoredDevice } = require('./enrollmentClient');
529
+ const { isSecureStorageAvailable } = require('./deviceKeyStore');
530
+ const processLock = require('./processLock');
531
+
532
+ const args = process.argv.slice(2);
533
+ const serverFlag = args.find(a => a.startsWith('--server='));
534
+ const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
535
+
536
+ const device = getStoredDevice({ serverOrigin });
537
+ const lock = processLock.readLock();
538
+
539
+ console.log(`XKWDStore Agent v${CLI_VERSION}\n`);
540
+
541
+ const machineState = require('./machineState');
542
+ console.log(`Machine root: ${machineState.getMachineRoot()}`);
543
+ console.log(`Machine identity: ${machineState.hasMachineIdentity() ? 'present' : 'not yet adopted'}\n`);
544
+
545
+ const brokerHealthModule = require('./brokerHealth');
546
+ const health = brokerHealthModule.readBrokerHealth() || brokerHealthModule.readBrokerLogAuthState();
547
+ if (health) {
548
+ const label = health.reauthorizationRequired
549
+ ? (health.source === 'broker-log'
550
+ ? 'AUTHENTICATION REJECTED (legacy broker is still retrying; upgrade/restart with 2.1.7)'
551
+ : 'REAUTHORIZATION REQUIRED (automatic retries stopped)')
552
+ : (health.state === 'connected' ? 'connected' : (health.state || 'unknown'));
553
+ console.log(`Broker: ${label}`);
554
+ if (health.authFailures) console.log(` Consecutive auth failures: ${health.authFailures}`);
555
+ if (health.lastDisconnectCode) console.log(` Last rejection code: ${health.lastDisconnectCode}`);
556
+ if (health.hint) console.log(` Action: ${health.hint}`);
557
+ console.log('');
558
+ }
559
+
560
+ if (!device) {
561
+ console.log('Status: Not authorized');
562
+ console.log('Run `xkwd-agent start` to authorize this computer.');
563
+ return;
564
+ }
565
+
566
+ console.log(`Device ID: ${device.deviceId}`);
567
+ console.log(`Device name: ${device.deviceName}`);
568
+ console.log(`Server: ${device.serverOrigin || 'https://x.kwdstore.com'}`);
569
+ console.log(`Public-key fingerprint: ${device.publicKeyFingerprint.slice(0, 8)}…${device.publicKeyFingerprint.slice(-8)}`);
570
+ console.log(`Created: ${device.createdAt || 'unknown'}`);
571
+ console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available' : 'unavailable'}`);
572
+
573
+ if (lock) {
574
+ console.log(`\nAgent process: RUNNING (PID ${lock.pid})`);
575
+ console.log(`Started: ${lock.startedAt}`);
576
+ } else {
577
+ console.log('\nAgent process: not running');
578
+ }
579
+ }
580
+
581
+ /**
582
+ * `xkwd-agent recover` — re-authorize THIS existing device id.
583
+ *
584
+ * This is the supported recovery path after a device was revoked/replaced:
585
+ * it keeps the local device identity (same deviceId and key) and asks the
586
+ * account owner to approve it. The backend reactivates the SAME device record,
587
+ * so device-bound browser profiles (cookies/sessions) are preserved. Because the
588
+ * tenant enforces one active protocol-v2 device, approval will revoke whichever
589
+ * device is currently active — the owner must consent explicitly.
590
+ */
591
+ async function recover(serverOrigin) {
592
+ const { getStoredDevice, getStoredPrivateKey, enroll, _request } = require('./enrollmentClient');
593
+ const device = getStoredDevice({ serverOrigin });
594
+ const privateKey = await getStoredPrivateKey({ serverOrigin });
595
+ if (!device || !privateKey) {
596
+ console.error('\nNo existing device identity to recover for ' + serverOrigin + '.');
597
+ console.error('Run `xkwd-agent start` to enroll this computer as a new device.');
598
+ process.exit(1);
599
+ }
600
+ // Feature gate: an older backend would treat this as a normal enrollment and
601
+ // mint a NEW device id, silently orphaning the existing profiles. Refuse.
602
+ let caps = [];
603
+ try {
604
+ const r = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
605
+ caps = (r && r.body && Array.isArray(r.body.capabilities)) ? r.body.capabilities : [];
606
+ } catch (e) {
607
+ console.error('\nCould not reach the server: ' + e.message);
608
+ process.exit(1);
609
+ }
610
+ if (!caps.includes('device-recovery-v1')) {
611
+ console.error('\nThis server does not support device recovery yet.');
612
+ console.error(' The backend must be upgraded (capability: device-recovery-v1) before recovering.');
613
+ console.error(' Do NOT run `start` instead: it would create a NEW device id and this device\'s');
614
+ console.error(' browser profiles are bound to the existing id.');
615
+ process.exit(1);
616
+ }
617
+ console.log('\nDevice recovery request');
618
+ console.log(` Device ID: ${device.deviceId}`);
619
+ console.log(` Name: ${device.deviceName}`);
620
+ console.log(` Fingerprint: ${device.publicKeyFingerprint.slice(0, 8)}…${device.publicKeyFingerprint.slice(-8)}`);
621
+ console.log('\nThe account owner must approve this request in the browser.');
622
+ console.log('Approval restores THIS device and revokes the currently active device');
623
+ console.log('(single-device policy). Existing browser profiles on this device are preserved.');
624
+ try {
625
+ const result = await enroll(serverOrigin, {
626
+ keyPair: {
627
+ publicKeyB64Url: device.publicKeyB64Url,
628
+ publicKeyFingerprint: device.publicKeyFingerprint,
629
+ privateKeyB64Url: privateKey,
630
+ },
631
+ recoverDeviceId: device.deviceId,
632
+ existingMeta: device,
633
+ });
634
+ const { writeBrokerHealth } = require('./brokerHealth');
635
+ writeBrokerHealth({
636
+ state: 'reauthorized',
637
+ authBlocked: false,
638
+ reauthorizationRequired: false,
639
+ deviceId: device.deviceId,
640
+ deviceName: device.deviceName,
641
+ serverOrigin,
642
+ hint: 'Recovery approved. Restart the XKWDStoreAgentBroker service (or run start) to reconnect.',
643
+ });
644
+ console.log('\n✓ Device recovered: ' + result.deviceId);
645
+ console.log(' Restart the broker service (or run `xkwd-agent start`) to reconnect.');
646
+ } catch (e) {
647
+ console.error('\nRecovery failed: ' + e.message);
648
+ console.error(' Your existing device identity was NOT deleted.');
649
+ process.exit(1);
650
+ }
651
+ }
652
+
653
+ /**
654
+ * `xkwd-agent logout` — delete local device identity (re-enrollment required).
655
+ * Server-scoped: only deletes the identity for the specified server.
656
+ * Usage: xkwd-agent logout [--server=<url>]
657
+ */
658
+ async function logout() {
659
+ const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
660
+ const processLock = require('./processLock');
661
+
662
+ // Parse --server flag for scoped logout
663
+ const args = process.argv.slice(2);
664
+ const serverFlag = args.find(a => a.startsWith('--server='));
665
+ const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
666
+
667
+ const lock = processLock.readLock();
668
+ if (lock) {
669
+ console.error('Agent is currently running. Stop it first with Ctrl+C.');
670
+ process.exit(1);
671
+ }
672
+
673
+ await deletePrivateKey({ serverOrigin });
674
+ deleteMetadata({ serverOrigin });
675
+ console.log(`Local device identity deleted for ${serverOrigin}.`);
676
+ console.log('Run `xkwd-agent start` to re-authorize this computer.');
677
+ }
678
+
679
+ /**
680
+ * `xkwd-agent revoke-local` — same as logout but also clears the process lock.
681
+ * Server-scoped: only deletes the identity for the specified server.
682
+ */
683
+ async function revokeLocal() {
684
+ const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
685
+ const args = process.argv.slice(2);
686
+ const serverFlag = args.find(a => a.startsWith('--server='));
687
+ const serverOrigin = serverFlag ? serverFlag.slice(9) : process.env.XKWDSTORE_SERVER || 'https://x.kwdstore.com';
688
+ await deletePrivateKey({ serverOrigin });
689
+ deleteMetadata({ serverOrigin });
690
+ console.log(`Local device identity and credentials revoked for ${serverOrigin}.`);
691
+ console.log('The server-side device record should also be revoked from the dashboard.');
692
+ }
693
+
694
+ /**
695
+ * `xkwd-agent machine` — machine-wide state operations (2.1.0).
696
+ *
697
+ * machine status — root, layout, identity presence, migration state
698
+ * machine adopt — run the one-time per-user → machine migration now
699
+ * machine harden — (Windows) apply + verify the restrictive DACL on the
700
+ * machine state directories
701
+ */
702
+ async function machine(args) {
703
+ const machineState = require('./machineState');
704
+ const { getMachineRoot, getLegacyDataDir, applyMachineStateAcls } = require('./deviceKeyStore');
705
+ const action = (Array.isArray(args) && args[0]) || 'status';
706
+
707
+ if (action === 'status' || action === 'info') {
708
+ const report = machineState.migrationReport();
709
+ console.log(`XKWDStore Agent v${CLI_VERSION} — Machine state\n`);
710
+ console.log(`Machine root (device identity lives here): ${report.newLocation}`);
711
+ console.log(` exists: ${report.machinePresent ? 'yes' : 'no'}`);
712
+ console.log(` identity present: ${machineState.hasMachineIdentity() ? 'yes' : 'no'}`);
713
+ console.log(`Legacy per-user root (migration source): ${report.oldLocation}`);
714
+ console.log(` exists: ${report.legacyPresent ? 'yes' : 'no'}`);
715
+ console.log(`Started: ${report.machinePresent ? 'yes' : 'no'}`);
716
+ if (report.marker) {
717
+ console.log(`Migration: ${report.marker.adoption || 'complete'} at ${report.marker.migratedAt}`);
718
+ console.log(` device id(s): ${(report.marker.deviceIds || []).join(', ') || '(none)'}`);
719
+ } else {
720
+ console.log('Migration: not required (no legacy identity found) or not yet run');
721
+ }
722
+ console.log(`Rollback supported: ${report.rollbackSupported ? 'yes' : 'no'}`);
723
+ console.log(` ${report.rollbackInstruction}`);
724
+ return;
725
+ }
726
+
727
+ if (action === 'adopt') {
728
+ const result = machineState.initializeMachineState();
729
+ console.log(`Machine root: ${result.root}`);
730
+ console.log(result.adopted
731
+ ? `Adopted legacy per-user state (device id: ${result.deviceId || 'preserved'}).`
732
+ : `No adoption needed (${result.reason}).`);
733
+ return;
734
+ }
735
+
736
+ if (action === 'harden') {
737
+ if (os.platform() !== 'win32') {
738
+ console.log('Machine-state ACL hardening is Windows-only; nothing to do.');
739
+ return;
740
+ }
741
+ const applied = applyMachineStateAcls({});
742
+ console.log(`Applied and verified restrictive ACLs on ${applied.length} machine-state director${applied.length === 1 ? 'y' : 'ies'}:`);
743
+ for (const p of applied) console.log(` ${p}`);
744
+ return;
745
+ }
746
+
747
+ console.error(`Unknown machine action: ${action}`);
748
+ console.error('Usage: xkwd-agent machine [status|adopt|harden]');
749
+ process.exit(1);
750
+ }
751
+
752
+ /**
753
+ * `xkwd-agent service` — the BROKER entry point (2.1.0).
754
+ *
755
+ * Runs the machine-wide broker that a Windows Service hosts. Responsibilities:
756
+ * - acquire the machine-wide named mutex (exactly one broker)
757
+ * - own the machine identity + device private key
758
+ * - own the server WebSocket connection, leases, and session registry
759
+ * - spawn an interactive Browser Worker in the active desktop session
760
+ * - relay TYPED browser commands to the worker over a loopback-only channel
761
+ *
762
+ * It never launches Chromium itself. It is silent by design (the service host
763
+ * provides no desktop). For foreground diagnostics, `start` runs a broker+worker
764
+ * pair in this same session.
765
+ */
766
+ async function service(serverOrigin, flags) {
767
+ const machineLock = require('./machineLock');
768
+ const machineState = require('./machineState');
769
+
770
+ // 1. machine-wide broker uniqueness (authoritative on Windows).
771
+ const lock = machineLock.acquireMachineBrokerLock();
772
+ if (!lock.acquired) {
773
+ console.error(`Another machine broker already holds the lock (${lock.primitive}): ${lock.detail}`);
774
+ process.exit(3);
775
+ }
776
+ // Hold it for the process lifetime via a dedicated holder process.
777
+ const holder = machineLock.startMutexHolder();
778
+ if (!holder.ok) {
779
+ console.error(`Could not hold the machine broker lock: ${holder.detail}`);
780
+ process.exit(3);
781
+ }
782
+
783
+ // 2. machine state + identity (broker owns the credential).
784
+ try { machineState.initializeMachineState(); } catch { }
785
+ const { writeBrokerHealth } = require('./brokerHealth');
786
+ const brokerMeta = (() => { try { return require('./deviceKeyStore').loadMetadata({ serverOrigin }) || {}; } catch { return {}; } })();
787
+ let _lastHealth = '';
788
+ const _writeBrokerHealth = (patch) => {
789
+ const payload = { deviceId: brokerMeta.deviceId, deviceName: brokerMeta.deviceName, serverOrigin, ...patch };
790
+ const key = JSON.stringify(payload);
791
+ if (key === _lastHealth) return;
792
+ _lastHealth = key;
793
+ try { writeBrokerHealth(payload); } catch { /* status reporting must never break the broker */ }
794
+ };
795
+ // After a permanent auth block, watch ONLY the local device-metadata file. A
796
+ // successful `xkwd-agent recover` rewrites it; the broker then retries once,
797
+ // without a network retry loop or a service restart. This is a local stat()
798
+ // every 30s, not a server poll.
799
+ let _authRecoveryTimer = null;
800
+ const _clearAuthRecoveryWatch = () => {
801
+ if (_authRecoveryTimer) { try { clearInterval(_authRecoveryTimer); } catch { /* ignore */ } _authRecoveryTimer = null; }
802
+ };
803
+ const _startAuthRecoveryWatch = () => {
804
+ if (_authRecoveryTimer) return;
805
+ const fs = require('fs');
806
+ const path = require('path');
807
+ const metaFile = path.join(require('./deviceKeyStore').getServerDataDir(serverOrigin), 'device-metadata.json');
808
+ let baseline = null;
809
+ try { baseline = fs.statSync(metaFile).mtimeMs; } catch { return; }
810
+ _authRecoveryTimer = setInterval(() => {
811
+ try {
812
+ const now = fs.statSync(metaFile).mtimeMs;
813
+ if (now !== baseline) {
814
+ baseline = now;
815
+ _clearAuthRecoveryWatch();
816
+ _writeBrokerHealth({ state: 'connecting', authBlocked: false, reauthorizationRequired: false, hint: 'Device metadata changed; retrying authentication.' });
817
+ Promise.resolve(supervisor.start()).catch(() => { /* bounded by the supervisor */ });
818
+ }
819
+ } catch { /* metadata absent/unreadable: keep waiting */ }
820
+ }, 30000);
821
+ if (typeof _authRecoveryTimer.unref === 'function') _authRecoveryTimer.unref();
822
+ };
823
+ _writeBrokerHealth({ state: 'connecting' });
824
+
825
+ console.log(`XKWDStore Agent broker v${CLI_VERSION} (machine-wide)`);
826
+ console.log(`Machine root: ${machineState.getMachineRoot()}`);
827
+ console.log(`Broker lock: ${lock.detail}`);
828
+
829
+ // 3. connect to the server (broker owns the WebSocket).
830
+ // `--offline` (test-lifecycle only) skips the server connection so the service
831
+ // host / mutex / identity can be proven without a live enrollment. Production
832
+ // always connects.
833
+ const offline = !!flags.offline;
834
+ let ws = null;
835
+ if (offline) {
836
+ console.log('Broker running OFFLINE (lifecycle test mode; no server connection)');
837
+ }
838
+
839
+ if (offline) {
840
+ // Prove identity loads and the broker stays alive; keep the mutex held.
841
+ const meta = (() => { try { return require('./deviceKeyStore').loadMetadata({ serverOrigin }); } catch { return null; } })();
842
+ console.log(`Broker identity: ${meta && meta.deviceId ? meta.deviceId : '(none)'}`);
843
+
844
+ // --probe-worker: open the bridge, launch the interactive worker, and report
845
+ // the worker's Windows session id so the Session-0 -> interactive-session
846
+ // launch is PROVEN with a real process. Lifecycle-test only.
847
+ if (flags['probe-worker']) {
848
+ const bridge = require('./brokerWorkerBridge');
849
+ const token = bridge.newChannelToken();
850
+ const channel = await bridge.openBrokerChannel({ token });
851
+ console.log(`probe: bridge port ${channel.port}`);
852
+ const child = _spawnInteractiveWorker({ port: channel.port, token });
853
+ const deadline = Date.now() + 20000;
854
+ while (!channel.connected && Date.now() < deadline) { await new Promise((r) => setTimeout(r, 150)); }
855
+ console.log(`probe: worker connected=${channel.connected}`);
856
+ console.log(`probe: activeConsoleSession=${_activeConsoleSession()} workerSession=${typeof child.session === 'number' ? child.session : 'n/a'}`);
857
+ try {
858
+ const st = await channel.call('getStatus', {}, 10000);
859
+ console.log('probe: worker status ' + JSON.stringify(st));
860
+ } catch (e) {
861
+ console.log('probe: worker status error ' + ((e && e.message) || 'unknown'));
862
+ }
863
+ // Give the harness time to inspect the worker process, then stop it.
864
+ await new Promise((r) => setTimeout(r, 12000));
865
+ try { await channel.call('shutdown', {}, 5000); } catch { }
866
+ try { channel.close(); } catch { }
867
+ console.log('probe: done');
868
+ machineLock.releaseMachineBrokerLock();
869
+ process.exit(0);
870
+ }
871
+
872
+ console.log('Broker alive; holding the machine lock. Ctrl+C to stop.');
873
+ const t = setInterval(() => {
874
+ try { console.log('broker heartbeat ' + new Date().toISOString()); } catch { }
875
+ }, 15000);
876
+ t.unref();
877
+ await new Promise(() => { }); // run until killed
878
+ }
879
+
880
+ // 4. spawn one interactive worker and route typed commands to it.
881
+ const bridge = require('./brokerWorkerBridge');
882
+ const token = bridge.newChannelToken();
883
+ const channel = await bridge.openBrokerChannel({ token });
884
+ const sessionHandler = require('./sessionHandler');
885
+
886
+ // The broker does NOT launch Chromium: it forwards startSession/stopSession to
887
+ // the worker. A worker is SESSION-BOUND: it is launched into the currently
888
+ // ACTIVE console session and is DISPOSABLE — a worker left over from a previous
889
+ // user (e.g. after a fast user switch) must NEVER serve a new session's job.
890
+ let worker = null;
891
+ let workerSession = -1;
892
+ async function ensureWorker() {
893
+ const active = _activeConsoleSession();
894
+ // Reuse the connected worker ONLY when it is in the CURRENT active session.
895
+ // On a change of active session the stale worker is torn down first (see the
896
+ // pure `shouldReplaceWorker` truth table).
897
+ const replace = bridge.shouldReplaceWorker({ connected: channel.connected, workerSession, activeSession: active });
898
+ if (!replace) return;
899
+ if (channel.connected) {
900
+ try { console.log(`worker session ${workerSession} != active ${active}; replacing the worker`); } catch { }
901
+ try { await channel.call('shutdown', {}, 5000); } catch { }
902
+ try { channel.dropWorker(); } catch { }
903
+ try { if (worker && worker.child) worker.child.kill(); } catch { }
904
+ workerSession = -1;
905
+ // Give the channel a moment to clear the old worker.
906
+ await new Promise((r) => setTimeout(r, 300));
907
+ }
908
+ worker = _spawnInteractiveWorker({ port: channel.port, token });
909
+ const deadline = Date.now() + 15000;
910
+ while (!channel.connected && Date.now() < deadline) { await new Promise((r) => setTimeout(r, 100)); }
911
+ if (!channel.connected) throw new Error('interactive worker did not attach');
912
+ // The launcher reports the target session on its stdout; wait briefly for it.
913
+ const sdeadline = Date.now() + 3000;
914
+ while (workerSession === -1 && Date.now() < sdeadline) {
915
+ workerSession = typeof worker.session === 'number' ? worker.session : -1;
916
+ if (workerSession === -1) await new Promise((r) => setTimeout(r, 100));
917
+ }
918
+ try { console.log(`worker attached (session=${workerSession}, active=${active})`); } catch { }
919
+ }
920
+
921
+ const { setupSessionHandler, closeAllSessions, markDisconnected } = sessionHandler;
922
+ const { createBrokerConnectionSupervisor } = require('./brokerConnectionSupervisor');
923
+
924
+ // 4a. ONE reconnect supervisor owns the production WebSocket lifecycle so a
925
+ // transient network/DNS/TLS/backend/WS/heartbeat loss reconnects with the
926
+ // SAME enrolled identity — no manual restart, no re-pair, no new key. Retries
927
+ // are UNBOUNDED for the machine service (a long-lived broker must self-heal);
928
+ // the supervisor preserves exactly one timer / one attempt / one socket.
929
+ const _bindSessionHandler = (socket) => setupSessionHandler(socket, {
930
+ // The broker has no chromePath: all browser work goes through the worker.
931
+ chromePath: null,
932
+ deviceMeta: require('./deviceKeyStore').loadMetadata({ serverOrigin }) || {},
933
+ serverOrigin,
934
+ // 2.1.0: route browser commands through the worker bridge.
935
+ workerBridge: {
936
+ ensureWorker,
937
+ call: (command, payload) => channel.call(command, payload),
938
+ },
939
+ });
940
+
941
+ const supervisor = createBrokerConnectionSupervisor({
942
+ connect: () => _brokerConnect(serverOrigin),
943
+ // Rebind the FULL session handler on every (re)connect; the server drives
944
+ // lease reconciliation from our sessions-report (protocol v2).
945
+ onConnected: (socket) => {
946
+ _clearAuthRecoveryWatch();
947
+ _bindSessionHandler(socket);
948
+ _writeBrokerHealth({ state: 'connected', authBlocked: false, reauthorizationRequired: false, authFailures: 0 });
949
+ },
950
+ // On a REAL disconnect stop accepting remote commands. Durable leases are
951
+ // server-owned and are NOT released locally — the server reconciles them
952
+ // after we reconnect.
953
+ onDisconnected: () => { try { markDisconnected(); } catch { } },
954
+ // Auth/identity rejection: PRESERVE the identity, notify once, and let the
955
+ // supervisor bound the attempts. A revoked/replaced device must not create a
956
+ // retry/log storm; status is written for `xkwd-agent status`.
957
+ onAuthRejected: () => {
958
+ try { console.error('[broker] authentication/identity rejected; identity preserved, retries bounded'); } catch { }
959
+ _writeBrokerHealth({
960
+ state: 'authentication_failed', authBlocked: true, reauthorizationRequired: false,
961
+ lastDisconnectCode: 4003,
962
+ hint: 'Device revoked or replaced. Owner approval is required before retrying.',
963
+ });
964
+ },
965
+ onAuthBlocked: (info) => {
966
+ _writeBrokerHealth({
967
+ state: 'authentication_failed', authBlocked: true, reauthorizationRequired: true,
968
+ authFailures: info && info.authFailures, lastDisconnectCode: info && info.code,
969
+ lastDisconnectReason: info && info.reason,
970
+ hint: 'Retries stopped. Ask the account owner to re-authorize this device, then run: xkwd-agent recover',
971
+ });
972
+ try { console.error('[broker] reauthorization required; automatic retries stopped (identity preserved)'); } catch { }
973
+ _startAuthRecoveryWatch();
974
+ },
975
+ log: (m) => { try { console.log(m); } catch { } },
976
+ });
977
+ console.log(`Broker connecting to ${serverOrigin} ...`);
978
+ Promise.resolve(supervisor.start()).catch(() => {});
979
+
980
+ async function shutdown(signal) {
981
+ console.log(`\n${signal} received. Broker shutting down...`);
982
+ // Stop reconnecting FIRST so no retry can start after shutdown begins.
983
+ _clearAuthRecoveryWatch();
984
+ try { supervisor.stop(); } catch { }
985
+ // Ask the interactive worker to close every owned browser and flush its
986
+ // persistent profile. Only a VERIFIED close is a clean shutdown; a failure
987
+ // is reported, never silently converted into success.
988
+ let workerClosed = false;
989
+ try {
990
+ const res = await channel.call('shutdown', {}, 25000);
991
+ workerClosed = !!(res && res.closed === true);
992
+ if (!workerClosed) console.error('[broker] worker shutdown did not verify every browser close');
993
+ } catch (err) {
994
+ console.error('[broker] worker shutdown failed: ' + ((err && err.code) || 'WORKER_SHUTDOWN_FAILED'));
995
+ }
996
+ // The worker exits itself after closing. If it is still alive (a wedged
997
+ // browser), terminate the worker process — the profile is preserved on disk
998
+ // and is recoverable on the next start.
999
+ try { if (worker && worker.exitCode == null) worker.kill(); } catch { }
1000
+ try { channel.close(); } catch { }
1001
+ try { await closeAllSessions(); } catch { }
1002
+ machineLock.releaseMachineBrokerLock();
1003
+ process.exit(0);
1004
+ }
1005
+ process.on('SIGINT', () => shutdown('Ctrl+C'));
1006
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
1007
+ }
1008
+
1009
+ /** The currently ACTIVE Windows console session id, via the compiled launcher's
1010
+ * `-Query` mode. Returns -1 when it cannot be determined (fail-safe). */
1011
+ function _activeConsoleSession() {
1012
+ try {
1013
+ const path = require('path');
1014
+ const fs = require('fs');
1015
+ const { execFileSync } = require('child_process');
1016
+ const machineRoot = require('./machineState').getMachineRoot();
1017
+ const launcherExe = path.join(machineRoot, 'launcher', 'XKWDStoreSessionLauncher.exe');
1018
+ if (os.platform() !== 'win32' || !fs.existsSync(launcherExe)) return -1;
1019
+ const out = execFileSync(launcherExe, ['-Query'], { encoding: 'utf8', windowsHide: true, timeout: 5000 }).trim();
1020
+ const m = /SESSION=(-?\d+)/.exec(out);
1021
+ return m ? parseInt(m[1], 10) : -1;
1022
+ } catch { return -1; }
1023
+ }
1024
+
1025
+ /** Spawn an interactive browser worker into the ACTIVE INTERACTIVE session.
1026
+ *
1027
+ * The broker runs as a Session-0 service, which has no desktop. A plain
1028
+ * child_process.spawn would create the worker (and its Chromium) in Session 0,
1029
+ * where no browser can be shown. When the broker is in Session 0 we therefore
1030
+ * launch the worker via the compiled session launcher (CreateProcessAsUser with
1031
+ * the active console session's user token). When the broker already runs in an
1032
+ * interactive session (foreground `start`), a direct spawn is equivalent.
1033
+ *
1034
+ * Returns { child, session } where `session` is the Windows session the worker
1035
+ * was launched into (or -1 when unknown). The broker records this so it never
1036
+ * reuses a worker from a session that is no longer the active console session.
1037
+ */
1038
+ function _spawnInteractiveWorker({ port, token }) {
1039
+ const { spawn } = require('child_process');
1040
+ const path = require('path');
1041
+ const fs = require('fs');
1042
+ const workerScript = path.join(__dirname, 'worker.js');
1043
+ const workerArgs = ['--port', String(port), '--token', token];
1044
+
1045
+ const machineRoot = require('./machineState').getMachineRoot();
1046
+ const launcherExe = path.join(machineRoot, 'launcher', 'XKWDStoreSessionLauncher.exe');
1047
+
1048
+ if (os.platform() === 'win32' && fs.existsSync(launcherExe)) {
1049
+ // Launch into the active interactive session. The launcher prints
1050
+ // `LAUNCHED pid=N session=S`; capture it so the worker is session-bound.
1051
+ const logDir = path.join(machineRoot, 'logs');
1052
+ try { fs.mkdirSync(logDir, { recursive: true }); } catch { }
1053
+ const outLog = path.join(logDir, 'worker.out.log');
1054
+ const errLog = path.join(logDir, 'worker.err.log');
1055
+ const child = spawn(launcherExe, [
1056
+ '-Exe', process.execPath,
1057
+ '-Args', '"' + workerScript + '" ' + workerArgs.join(' '),
1058
+ '-Cwd', __dirname,
1059
+ '-Out', outLog,
1060
+ '-Err', errLog,
1061
+ ], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
1062
+ let session = -1;
1063
+ let buf = '';
1064
+ try {
1065
+ child.stdout.on('data', (d) => {
1066
+ buf += d.toString();
1067
+ const m = /session=(-?\d+)/.exec(buf);
1068
+ if (m) session = parseInt(m[1], 10);
1069
+ });
1070
+ } catch { }
1071
+ return { child, get session() { return session; } };
1072
+ }
1073
+
1074
+ // Interactive/foreground fallback: the broker is already in the right session.
1075
+ const child = spawn(process.execPath, [workerScript, ...workerArgs], {
1076
+ detached: false,
1077
+ stdio: ['ignore', 'inherit', 'inherit'],
1078
+ windowsHide: true,
1079
+ });
1080
+ return { child, session: _activeConsoleSession() };
1081
+ }
1082
+
1083
+ /** Connect the broker's WebSocket using the machine credential. */
1084
+ async function _brokerConnect(serverOrigin) {
1085
+ const { getStoredDevice, getStoredPrivateKey } = require('./enrollmentClient');
1086
+ const deviceMeta = getStoredDevice({ serverOrigin });
1087
+ const privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
1088
+ if (!deviceMeta || !privateKeyB64Url) {
1089
+ throw new Error('device is not enrolled; run `xkwd-agent start` once to authorize this machine');
1090
+ }
1091
+ const { connectWebSocket } = require('./wsClient');
1092
+ return connectWebSocket({
1093
+ serverOrigin,
1094
+ deviceId: deviceMeta.deviceId,
1095
+ publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
1096
+ privateKeyB64Url,
1097
+ protocolVersion: PROTOCOL_VERSION,
1098
+ });
1099
+ }
1100
+
1101
+ /**
1102
+ * `xkwd-agent doctor` — diagnostic checks.
1103
+ */
1104
+ async function doctor(serverOrigin) {
1105
+ console.log(`XKWDStore Agent v${CLI_VERSION} — Diagnostics\n`);
1106
+
1107
+ // Check Node version
1108
+ const nodeVersion = process.versions.node;
1109
+ const major = parseInt(nodeVersion.split('.')[0], 10);
1110
+ console.log(`Node.js: ${nodeVersion} ${major >= 22 ? '✓' : '✗ (requires Node.js 22+)'}`);
1111
+
1112
+ // Check platform
1113
+ console.log(`Platform: ${os.platform()} ${os.arch()}`);
1114
+ console.log(`Hostname: ${os.hostname()}`);
1115
+
1116
+ // Check Chrome
1117
+ try {
1118
+ const { resolveChromeOrFail } = require('./chromeDetector');
1119
+ const chrome = resolveChromeOrFail();
1120
+ console.log(`Chrome: ${chrome.chromeVersion || 'detected'} ✓`);
1121
+ } catch (e) {
1122
+ console.log(`Chrome: ✗ (${e.message.split('\n')[0]})`);
1123
+ }
1124
+
1125
+ // Check secure storage (real DPAPI + ACL probe on Windows)
1126
+ const { isSecureStorageAvailable, getDataDir, probeWindowsStorage } = require('./deviceKeyStore');
1127
+ const platform = os.platform();
1128
+ if (platform === 'win32') {
1129
+ console.log('Secure storage: probing real DPAPI + ACL stages...');
1130
+ const probe = probeWindowsStorage();
1131
+ console.log(` DPAPI Protect : ${probe.stages.protect ? '✓' : '✗'}`);
1132
+ console.log(` DPAPI Unprotect: ${probe.stages.unprotect ? '✓' : '✗'}`);
1133
+ console.log(` Windows SID : ${probe.stages.sidLookup ? '✓' : '✗'}`);
1134
+ console.log(` ACL apply : ${probe.stages.aclApply ? '✓' : '✗'}`);
1135
+ console.log(` ACL verify : ${probe.stages.aclVerify ? '✓' : '✗'}`);
1136
+ console.log(`Secure storage: ${probe.ok ? 'available ✓' : 'unavailable ✗'}`);
1137
+ if (!probe.ok && probe.detail) {
1138
+ console.log(` Detail: ${probe.detail}`);
1139
+ }
1140
+ } else {
1141
+ console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available ✓' : 'unavailable ✗'}`);
1142
+ }
1143
+
1144
+ // Check data directory (machine-wide since 2.1.0)
1145
+ const dataDir = getDataDir();
1146
+ const legacyDir = require('./deviceKeyStore').getLegacyDataDir();
1147
+ console.log(`Machine state root: ${dataDir}`);
1148
+ console.log(`Legacy per-user root: ${legacyDir}`);
1149
+ const machineState = require('./machineState');
1150
+ console.log(`Machine identity present: ${machineState.hasMachineIdentity() ? '✓' : '(none yet)'}`);
1151
+
1152
+ // Check device identity (server-scoped)
1153
+ const { getStoredDevice, getStoredPrivateKey } = require('./enrollmentClient');
1154
+ const device = getStoredDevice({ serverOrigin });
1155
+ if (device) {
1156
+ console.log(`Device ID: ${device.deviceId} ✓`);
1157
+ const privateKey = await getStoredPrivateKey({ serverOrigin });
1158
+ console.log(`Private key: ${privateKey ? 'stored ✓' : 'missing ✗'}`);
1159
+ } else {
1160
+ console.log('Device ID: not enrolled for this server');
1161
+ }
1162
+ const brokerHealthModule = require('./brokerHealth');
1163
+ const brokerHealth = brokerHealthModule.readBrokerHealth() || brokerHealthModule.readBrokerLogAuthState();
1164
+ if (brokerHealth) {
1165
+ console.log(`Broker health: ${brokerHealth.state || 'unknown'}${brokerHealth.reauthorizationRequired ? ' — REAUTHORIZATION REQUIRED' : ''}`);
1166
+ if (brokerHealth.authFailures) console.log(` Consecutive auth failures: ${brokerHealth.authFailures}`);
1167
+ if (brokerHealth.hint) console.log(` Action: ${brokerHealth.hint}`);
1168
+ }
1169
+
1170
+ // Check server connectivity (shared strict validator)
1171
+ try {
1172
+ const { _request, validateCompatibilityResponse, COMPAT_HTML_MESSAGE } = require('./enrollmentClient');
1173
+ const resp = await _request('GET', `${serverOrigin}/api/agent/compatibility`, null, {});
1174
+ const compat = validateCompatibilityResponse(resp);
1175
+ if (compat.html) {
1176
+ console.log(`Server (${serverOrigin}): compatibility endpoint returned frontend ✗`);
1177
+ console.log(' ' + COMPAT_HTML_MESSAGE);
1178
+ } else if (compat.ok) {
1179
+ console.log(`Server (${serverOrigin}): reachable ✓`);
1180
+ console.log(` Protocol version: ${compat.body.protocolVersion}`);
1181
+ console.log(` Min agent version: ${compat.body.minimumAgentVersion}`);
1182
+ console.log(` Recommended agent version: ${compat.body.recommendedAgentVersion}`);
1183
+ } else {
1184
+ console.log(`Server (${serverOrigin}): compatibility check failed ✗`);
1185
+ console.log(` Reason: ${compat.reason}`);
1186
+ }
1187
+ } catch (e) {
1188
+ console.log(`Server (${serverOrigin}): unreachable ✗ (${e.message})`);
1189
+ }
1190
+ }
1191
+
1192
+ /**
1193
+ * `xkwd-agent version` — print version.
1194
+ */
1195
+ function version() {
1196
+ console.log(`@xkwdstore/agent v${CLI_VERSION}`);
1197
+ console.log(`Protocol version: ${PROTOCOL_VERSION}`);
1198
+ console.log(`Node.js: ${process.versions.node}`);
1199
+ }
1200
+
1201
+ /**
1202
+ * `xkwd-agent help` — print help.
1203
+ */
1204
+ function help() {
1205
+ console.log(`XKWDStore Agent v${CLI_VERSION}
1206
+
1207
+ Usage:
1208
+ xkwd-agent <command> [options]
1209
+
1210
+ Commands:
1211
+ start Start the agent (connects to server, runs browser sessions)
1212
+ status Show device and connection status
1213
+ recover Re-authorize THIS device after revocation/replacement (owner approval)
1214
+ logout Delete local device identity (requires re-authorization)
1215
+ revoke-local Delete local device identity and credentials
1216
+ machine Machine-wide state: status | adopt | harden
1217
+ service Run the machine-wide broker (Windows Service host; silent)
1218
+ doctor Run diagnostic checks
1219
+ version Print version information
1220
+ help Show this help
1221
+
1222
+ Options:
1223
+ --server=<url> Server URL (default: https://x.kwdstore.com)
1224
+ --replace Replace a running instance (safe takeover)
1225
+
1226
+ Examples:
1227
+ xkwd-agent start
1228
+ xkwd-agent start --replace
1229
+ xkwd-agent status
1230
+ xkwd-agent recover
1231
+ xkwd-agent machine status
1232
+ xkwd-agent doctor
1233
+
1234
+ First run:
1235
+ The agent will open your browser to authorize this computer.
1236
+ No pairing code, email, or API key is required.
1237
+
1238
+ To stop:
1239
+ Press Ctrl+C in the terminal.
1240
+
1241
+ Data location (machine-wide, shared by every Windows user on this PC):
1242
+ Windows: %ProgramData%\\XKWDStore\\Agent\\
1243
+ Linux: ${'{XDG_DATA_HOME:-~/.local/share}/xkwdstore/'}
1244
+ macOS: unsupported (fails closed)
1245
+
1246
+ Device identity belongs to the MACHINE. Changing the Windows user or the
1247
+ TW-manager preferred device does NOT create a second device identity.
1248
+ A pre-2.1.0 per-user install is adopted once (copy, never move).
1249
+
1250
+ Requirements:
1251
+ - Node.js 22 or later
1252
+ - Google Chrome installed
1253
+ `);
1254
+ }
1255
+
1256
+ // ── Helpers ──────────────────────────────────────────────────────────────────
1257
+
1258
+ /**
1259
+ * Detect whether a connection error is a 4003 authentication failure.
1260
+ * The wsClient rejects with a message containing "Device authentication
1261
+ * failed" when the server closes with code 4003. The error may also carry
1262
+ * a .code property in some implementations.
1263
+ */
1264
+ function _is4003Error(err) {
1265
+ if (!err) return false;
1266
+ const msg = (err.message || String(err)).toLowerCase();
1267
+ if (err.code === 4003) return true;
1268
+ if (msg.includes('device authentication failed')) return true;
1269
+ if (msg.includes('4003')) return true;
1270
+ return false;
1271
+ }
1272
+
1273
+ function _compareVersions(a, b) {
1274
+ const pa = a.split('.').map(Number);
1275
+ const pb = b.split('.').map(Number);
1276
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
1277
+ const va = pa[i] || 0;
1278
+ const vb = pb[i] || 0;
1279
+ if (va > vb) return 1;
1280
+ if (va < vb) return -1;
1281
+ }
1282
+ return 0;
1283
+ }
1284
+
1285
+ // ── Entry point ──────────────────────────────────────────────────────────────
1286
+
1287
+ if (require.main === module) {
1288
+ main();
1289
+ }
1290
+
1291
1291
  module.exports = { main, CLI_VERSION, PROTOCOL_VERSION };