@xkwdstore/agent 2.0.7 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.js CHANGED
@@ -24,7 +24,7 @@ const crypto = require('crypto');
24
24
  const os = require('os');
25
25
  const path = require('path');
26
26
 
27
- const CLI_VERSION = '2.0.7';
27
+ const CLI_VERSION = '2.1.0';
28
28
  const PROTOCOL_VERSION = 2;
29
29
 
30
30
  // ── Command parsing ──────────────────────────────────────────────────────────
@@ -66,6 +66,57 @@ function main() {
66
66
  return revokeLocal();
67
67
  case 'doctor':
68
68
  return doctor(serverOrigin);
69
+ case 'machine':
70
+ return machine(positional);
71
+ case 'service':
72
+ return service(serverOrigin, flags);
73
+ case 'key-probe': {
74
+ // Diagnostics: report whether the machine credential can be decrypted in
75
+ // THIS process context (e.g. from the LocalSystem service) WITHOUT
76
+ // printing any secret. Used by the elevated lifecycle gate.
77
+ (async () => {
78
+ const fs = require('fs');
79
+ const path = require('path');
80
+ const { loadMetadata, loadPrivateKeyFromStorage, getMachineRoot, _identitySourceRoots, _serversDirFor } = require('./deviceKeyStore');
81
+ const { normalizeServerOrigin } = require('./deviceKeyStore');
82
+ const meta = loadMetadata({ serverOrigin });
83
+ const out = {
84
+ context: { user: require('os').userInfo().username, platform: os.platform(), pid: process.pid },
85
+ machineRoot: getMachineRoot(),
86
+ deviceId: meta ? meta.deviceId : null,
87
+ privateKeyDecryptable: false,
88
+ stages: {},
89
+ error: '',
90
+ };
91
+ // Stage 1: locate the key file the loader would use.
92
+ let keyFile = null;
93
+ try {
94
+ const roots = _identitySourceRoots();
95
+ const label = normalizeServerOrigin(serverOrigin);
96
+ const candidates = [];
97
+ for (const r of [roots.source, roots.target]) {
98
+ if (r) candidates.push(path.join(_serversDirFor(r), label, '.device-key'));
99
+ }
100
+ for (const r of [roots.source, roots.target]) { if (r) candidates.push(path.join(r, '.device-key')); }
101
+ out.stages.candidates = candidates;
102
+ for (const c of candidates) { if (fs.existsSync(c)) { keyFile = c; break; } }
103
+ out.stages.keyFile = keyFile;
104
+ out.stages.keyReadable = keyFile ? (() => { try { fs.accessSync(keyFile, fs.constants.R_OK); return true; } catch { return false; } })() : false;
105
+ if (keyFile) {
106
+ try {
107
+ const env = JSON.parse(fs.readFileSync(keyFile, 'utf8'));
108
+ out.stages.envelopeScheme = env.scheme;
109
+ out.stages.envelopeScope = env.scope || '(v1/unscoped)';
110
+ out.stages.envelopeV = env.v;
111
+ } catch (e) { out.stages.envelopeError = (e && e.message) || 'parse'; }
112
+ }
113
+ } catch (e) { out.stages.locateError = (e && e.message) || 'locate'; }
114
+ // Stage 2: full loader (includes ACL verify).
115
+ try { out.privateKeyDecryptable = !!(await loadPrivateKeyFromStorage({ serverOrigin })); } catch (e) { out.error = (e && e.message) || 'error'; }
116
+ console.log(JSON.stringify(out));
117
+ })().catch((e) => { console.error(JSON.stringify({ error: (e && e.message) || 'fatal' })); process.exit(1); });
118
+ return;
119
+ }
69
120
  case 'version':
70
121
  return version();
71
122
  case 'help':
@@ -84,6 +135,21 @@ function main() {
84
135
  async function start(serverOrigin, flags) {
85
136
  console.log(`XKWDStore Agent v${CLI_VERSION} (protocol v${PROTOCOL_VERSION})`);
86
137
  console.log(`Server: ${serverOrigin}`);
138
+
139
+ // 0. Machine-wide state: create the ProgramData layout and adopt any
140
+ // pre-2.1.0 per-user identity ONCE (copy, never move). The device identity
141
+ // therefore belongs to the MACHINE, not to the current Windows user.
142
+ try {
143
+ const machineState = require('./machineState');
144
+ const init = machineState.initializeMachineState();
145
+ console.log(`✓ Machine state: ${init.root}`);
146
+ if (init.adopted && init.deviceId) {
147
+ console.log(`✓ Adopted existing device identity: ${init.deviceId}`);
148
+ }
149
+ } catch (e) {
150
+ console.error(`Machine state initialization failed: ${(e && e.message) || 'unknown'}`);
151
+ process.exit(1);
152
+ }
87
153
  console.log();
88
154
 
89
155
  // 1. Detect OS and architecture (for display)
@@ -320,139 +386,93 @@ async function start(serverOrigin, flags) {
320
386
  console.log('✓ Connected');
321
387
  console.log('\nAgent is running. Press Ctrl+C to stop.\n');
322
388
 
389
+ // Keep SQLite-style registry state honest: the handler owns session
390
+ // registration; ensure the machine runtime dir exists before the first launch.
391
+ try {
392
+ const ms = require('./machineState');
393
+ ms.ensureMachineLayout();
394
+ } catch { /* best-effort */ }
395
+
323
396
  // 8. Set up browser session handler (delegates to existing session management)
324
- const { setupSessionHandler, closeAllSessions, markDisconnected } = require('./sessionHandler');
325
- const sessions = setupSessionHandler(ws, { chromePath, deviceMeta, serverOrigin });
397
+ const { setupSessionHandler, closeAllSessions, markDisconnected, recoverOrphanedSessions } = require('./sessionHandler');
326
398
 
327
- // 8a. Disconnect handling with bounded auto-reconnect.
328
- //
329
- // The server deliberately closes the WS in two situations where the agent is
330
- // EXPECTED to reconnect (the dashboard's Restart Agent button promises "the
331
- // agent will reconnect in a few seconds"):
332
- // - graceful 'agent-restart' message → code 1000 'agent-restart'
333
- // - fallback restart → code 4002 'Server-initiated restart'
334
- // In BOTH cases the local browser sessions are meant to STAY OPEN (only the
335
- // WS is re-established) — see localAgentServer.restartAgent. On reconnect the
336
- // server requests a sessions-report and reconciles every lease-bound session
337
- // itself, so lease reconciliation is server-driven and authoritative.
338
- //
339
- // Any OTHER close (heartbeat timeout 4002 'Heartbeat timeout', network 1006,
340
- // protocol error) is a genuine disconnect: the agent marks itself
341
- // disconnected, closes every browser context (preserving profiles/cookies),
342
- // and retries with exponential backoff. After MAX_WS_RECONNECTS consecutive
343
- // failures the agent exits non-zero with a clear message (the original
344
- // fail-safe).
345
- //
346
- // Race guard: `shuttingDown` is set by the deliberate Ctrl+C/SIGTERM path
347
- // BEFORE ws.close() is called, so the close event emitted during a
348
- // deliberate shutdown does NOT run this handler.
349
- let shuttingDown = false;
350
- let reconnectAttempts = 0;
351
- const MAX_WS_RECONNECTS = 10;
352
- const RECONNECT_BASE_MS = 1000;
353
- const RECONNECT_MAX_MS = 60000;
399
+ // 2.1.0 F1: crash recovery. A previous agent process may have left an
400
+ // Agent-OWNED Chromium behind (it is alive but unmanaged). Release the stale
401
+ // LOCAL locks for those proven-owned sessions so the accounts are not blocked
402
+ // on this device. The SERVER durable lease is authoritative and is NOT touched
403
+ // here — server recovery (recovery-probe / reconcile) still governs it.
404
+ try {
405
+ const recovery = recoverOrphanedSessions();
406
+ if (recovery.orphans > 0) {
407
+ console.log(`ℹ️ Crash recovery: found ${recovery.orphans} Agent-owned orphaned browser(s); released ${recovery.released} local lock(s).`);
408
+ }
409
+ } catch { /* never block startup on recovery */ }
354
410
 
355
- const _connectOpts = () => ({
356
- serverOrigin,
357
- deviceId: deviceMeta.deviceId,
358
- publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
359
- privateKeyB64Url,
360
- protocolVersion: PROTOCOL_VERSION,
361
- });
411
+ const { createBrokerConnectionSupervisor } = require('./brokerConnectionSupervisor');
362
412
 
413
+ // 8a. Disconnect handling — the SAME reconnect supervisor as the machine
414
+ // `service` broker. The foreground agent adopts the already-authenticated
415
+ // socket; the supervisor owns every subsequent (re)connect, guaranteeing one
416
+ // timer / one attempt / one live socket, with unbounded self-healing that uses
417
+ // the SAME enrolled identity (transport recovery only, never a new identity).
418
+ //
419
+ // Interactive-path policy preserved:
420
+ // - server-initiated restart (1000 'agent-restart' / 4002 'Server-initiated
421
+ // restart'): rebind WITHOUT touching local browsers — the server reconciles
422
+ // leases from our sessions-report after reconnect.
423
+ // - any OTHER close: mark disconnected + close all browser contexts (profiles
424
+ // persist), then reconnect.
425
+ // - 4003 revoked mid-session: clear THIS server's identity and stop (explicit
426
+ // re-authorization) — the supervisor NEVER regenerates identity.
363
427
  const _isRestartClose = (code, reasonStr) =>
364
428
  (code === 1000 && /agent-restart/i.test(reasonStr))
365
429
  || (code === 4002 && /server-initiated restart/i.test(reasonStr));
366
430
 
367
- const _delayMs = () => Math.min(RECONNECT_BASE_MS * Math.pow(2, reconnectAttempts), RECONNECT_MAX_MS)
368
- + Math.floor(Math.random() * 1000);
369
-
370
- async function _handleWsClose(code, reason) {
371
- if (shuttingDown) return;
372
- const reasonStr = reason ? reason.toString() : '';
373
-
374
- // Deliberate server-initiated restart: rebind WITHOUT touching sessions.
375
- if (_isRestartClose(code, reasonStr)) {
376
- console.log('\nℹ️ Server requested a connection restart. Reconnecting (browser sessions stay open)...');
377
- // Do NOT markDisconnected / closeAllSessions here — the local browsers
378
- // remain valid; the server reconciles their leases from our
379
- // sessions-report after we reconnect.
380
- try { ws.removeAllListeners('close'); } catch {}
381
- } else {
382
- // Genuine disconnect: fail-safe. No further commands may run, and every
383
- // browser context is closed (profiles persist on close).
431
+ const supervisor = createBrokerConnectionSupervisor({
432
+ connect: () => connectWebSocket({
433
+ serverOrigin,
434
+ deviceId: deviceMeta.deviceId,
435
+ publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
436
+ privateKeyB64Url,
437
+ protocolVersion: PROTOCOL_VERSION,
438
+ }),
439
+ onConnected: (socket) => { setupSessionHandler(socket, { chromePath, deviceMeta, serverOrigin }); },
440
+ onDisconnected: async ({ code, reason }) => {
441
+ const reasonStr = reason || '';
442
+ if (_isRestartClose(code, reasonStr)) {
443
+ console.log('\nℹ️ Server requested a connection restart. Reconnecting (browser sessions stay open)...');
444
+ return; // keep local browsers; the server reconciles leases
445
+ }
384
446
  console.error(`\n✗ Connection to server lost (code ${code}${reasonStr ? ': ' + reasonStr : ''}).`);
385
- console.error(' Closing all browser sessions and shutting down safely...');
447
+ console.error(' Closing all browser sessions and reconnecting safely...');
386
448
  markDisconnected();
387
- const { closed } = await closeAllSessions().catch(() => ({ closed: 0 }));
388
- if (closed > 0) console.error(` Closed ${closed} browser session(s).`);
389
- try { ws.removeAllListeners('close'); } catch {}
390
- }
391
-
392
- // 4003 = revoked mid-session: the credential is dead — re-enroll requires
393
- // user interaction, so exit with a clear message (no auto-retry loop).
394
- if (code === 4003) {
395
- console.error('\n❌ Authentication failed — this device was revoked during the session.');
396
- console.error(' The server-scoped identity for ' + serverOrigin + ' has been cleared.');
449
+ try { await closeAllSessions(); } catch { }
450
+ },
451
+ onAuthRejected: () => {
452
+ // 4003: the credential is dead. Do NOT regenerate identity automatically.
453
+ console.error('\n❌ Authentication failed — this device was revoked.');
397
454
  console.error(' Run `xkwd-agent start` again to re-authorize this computer.');
398
455
  try {
399
456
  const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
400
457
  deletePrivateKey({ serverOrigin });
401
458
  deleteMetadata({ serverOrigin });
402
- } catch {}
459
+ } catch { }
403
460
  processLock.releaseLock();
404
- console.error('Agent stopped.');
405
461
  process.exit(1);
406
- }
407
-
408
- // Bounded reconnect with backoff + jitter (a fresh challenge every time —
409
- // network loss never re-enrolls; only a 4003 does, handled above).
410
- reconnectAttempts += 1;
411
- if (reconnectAttempts > MAX_WS_RECONNECTS) {
412
- console.error(`\n❌ Could not reconnect after ${MAX_WS_RECONNECTS} attempts.`);
413
- console.error(' Run `xkwd-agent start` again.');
462
+ },
463
+ onExhausted: () => {
464
+ console.error('\n❌ Could not reconnect. Run `xkwd-agent start` again.');
414
465
  processLock.releaseLock();
415
- console.error('Agent stopped.');
416
466
  process.exit(1);
417
- }
418
- const delay = _delayMs();
419
- console.log(` Reconnecting in ${Math.round(delay / 1000)}s (attempt ${reconnectAttempts}/${MAX_WS_RECONNECTS})...`);
420
- setTimeout(() => { _reconnect().catch(() => {}); }, delay);
421
- }
422
-
423
- async function _reconnect() {
424
- try {
425
- ws = await connectWebSocket(_connectOpts());
426
- reconnectAttempts = 0; // reset on a successful re-establish
427
- // Rebind the FULL session handler on the new socket (fresh runtime
428
- // state: connected, heartbeat timer, command envelope handling).
429
- setupSessionHandler(ws, { chromePath, deviceMeta, serverOrigin });
430
- // A sessions-report request arrives from the server right after
431
- // authentication; the handler answers it from the live sessions map,
432
- // which lets the server reconcile/restore every lease.
433
- console.log('✓ Reconnected.');
434
- ws.on('close', (code, reason) => { _handleWsClose(code, reason).catch(() => {}); });
435
- } catch (err) {
436
- if (_is4003Error(err)) {
437
- // Fall into the 4003 exit path via the same handler logic.
438
- await _handleWsClose(4003, Buffer.from('revoked during reconnect'));
439
- return;
440
- }
441
- reconnectAttempts += 1;
442
- if (reconnectAttempts > MAX_WS_RECONNECTS) {
443
- console.error(`\n❌ Could not reconnect after ${MAX_WS_RECONNECTS} attempts: ${err.message}`);
444
- console.error(' Run `xkwd-agent start` again.');
445
- processLock.releaseLock();
446
- console.error('Agent stopped.');
447
- process.exit(1);
448
- }
449
- const delay = _delayMs();
450
- console.log(` Reconnect failed (${err.message}). Retrying in ${Math.round(delay / 1000)}s (attempt ${reconnectAttempts}/${MAX_WS_RECONNECTS})...`);
451
- setTimeout(() => { _reconnect().catch(() => {}); }, delay);
452
- }
453
- }
467
+ },
468
+ maxAttempts: 10,
469
+ log: (m) => { try { console.log(m); } catch { } },
470
+ });
471
+ supervisor.adopt(ws);
454
472
 
455
- ws.on('close', (code, reason) => { _handleWsClose(code, reason).catch(() => {}); });
473
+ // Deliberate-shutdown guard (set before closing anything, so a close emitted
474
+ // during shutdown cannot trigger a reconnect).
475
+ let shuttingDown = false;
456
476
 
457
477
  // 9. Clean shutdown on Ctrl+C
458
478
  async function shutdown(signal) {
@@ -460,6 +480,9 @@ async function start(serverOrigin, flags) {
460
480
  shuttingDown = true;
461
481
  console.log(`\n${signal} received. Shutting down...`);
462
482
 
483
+ // Stop reconnecting FIRST so no retry can start after shutdown begins.
484
+ try { supervisor.stop(); } catch { }
485
+
463
486
  // Stop accepting commands immediately.
464
487
  markDisconnected();
465
488
 
@@ -469,9 +492,6 @@ async function start(serverOrigin, flags) {
469
492
  await closeAllSessions();
470
493
  } catch {}
471
494
 
472
- // Close WebSocket
473
- try { ws.close(1000, 'Agent shutting down'); } catch {}
474
-
475
495
  // Release lock
476
496
  processLock.releaseLock();
477
497
 
@@ -507,6 +527,10 @@ function status() {
507
527
 
508
528
  console.log(`XKWDStore Agent v${CLI_VERSION}\n`);
509
529
 
530
+ const machineState = require('./machineState');
531
+ console.log(`Machine root: ${machineState.getMachineRoot()}`);
532
+ console.log(`Machine identity: ${machineState.hasMachineIdentity() ? 'present' : 'not yet adopted'}\n`);
533
+
510
534
  if (!device) {
511
535
  console.log('Status: Not authorized');
512
536
  console.log('Run `xkwd-agent start` to authorize this computer.');
@@ -569,6 +593,338 @@ async function revokeLocal() {
569
593
  console.log('The server-side device record should also be revoked from the dashboard.');
570
594
  }
571
595
 
596
+ /**
597
+ * `xkwd-agent machine` — machine-wide state operations (2.1.0).
598
+ *
599
+ * machine status — root, layout, identity presence, migration state
600
+ * machine adopt — run the one-time per-user → machine migration now
601
+ * machine harden — (Windows) apply + verify the restrictive DACL on the
602
+ * machine state directories
603
+ */
604
+ async function machine(args) {
605
+ const machineState = require('./machineState');
606
+ const { getMachineRoot, getLegacyDataDir, applyMachineStateAcls } = require('./deviceKeyStore');
607
+ const action = (Array.isArray(args) && args[0]) || 'status';
608
+
609
+ if (action === 'status' || action === 'info') {
610
+ const report = machineState.migrationReport();
611
+ console.log(`XKWDStore Agent v${CLI_VERSION} — Machine state\n`);
612
+ console.log(`Machine root (device identity lives here): ${report.newLocation}`);
613
+ console.log(` exists: ${report.machinePresent ? 'yes' : 'no'}`);
614
+ console.log(` identity present: ${machineState.hasMachineIdentity() ? 'yes' : 'no'}`);
615
+ console.log(`Legacy per-user root (migration source): ${report.oldLocation}`);
616
+ console.log(` exists: ${report.legacyPresent ? 'yes' : 'no'}`);
617
+ console.log(`Started: ${report.machinePresent ? 'yes' : 'no'}`);
618
+ if (report.marker) {
619
+ console.log(`Migration: ${report.marker.adoption || 'complete'} at ${report.marker.migratedAt}`);
620
+ console.log(` device id(s): ${(report.marker.deviceIds || []).join(', ') || '(none)'}`);
621
+ } else {
622
+ console.log('Migration: not required (no legacy identity found) or not yet run');
623
+ }
624
+ console.log(`Rollback supported: ${report.rollbackSupported ? 'yes' : 'no'}`);
625
+ console.log(` ${report.rollbackInstruction}`);
626
+ return;
627
+ }
628
+
629
+ if (action === 'adopt') {
630
+ const result = machineState.initializeMachineState();
631
+ console.log(`Machine root: ${result.root}`);
632
+ console.log(result.adopted
633
+ ? `Adopted legacy per-user state (device id: ${result.deviceId || 'preserved'}).`
634
+ : `No adoption needed (${result.reason}).`);
635
+ return;
636
+ }
637
+
638
+ if (action === 'harden') {
639
+ if (os.platform() !== 'win32') {
640
+ console.log('Machine-state ACL hardening is Windows-only; nothing to do.');
641
+ return;
642
+ }
643
+ const applied = applyMachineStateAcls({});
644
+ console.log(`Applied and verified restrictive ACLs on ${applied.length} machine-state director${applied.length === 1 ? 'y' : 'ies'}:`);
645
+ for (const p of applied) console.log(` ${p}`);
646
+ return;
647
+ }
648
+
649
+ console.error(`Unknown machine action: ${action}`);
650
+ console.error('Usage: xkwd-agent machine [status|adopt|harden]');
651
+ process.exit(1);
652
+ }
653
+
654
+ /**
655
+ * `xkwd-agent service` — the BROKER entry point (2.1.0).
656
+ *
657
+ * Runs the machine-wide broker that a Windows Service hosts. Responsibilities:
658
+ * - acquire the machine-wide named mutex (exactly one broker)
659
+ * - own the machine identity + device private key
660
+ * - own the server WebSocket connection, leases, and session registry
661
+ * - spawn an interactive Browser Worker in the active desktop session
662
+ * - relay TYPED browser commands to the worker over a loopback-only channel
663
+ *
664
+ * It never launches Chromium itself. It is silent by design (the service host
665
+ * provides no desktop). For foreground diagnostics, `start` runs a broker+worker
666
+ * pair in this same session.
667
+ */
668
+ async function service(serverOrigin, flags) {
669
+ const machineLock = require('./machineLock');
670
+ const machineState = require('./machineState');
671
+
672
+ // 1. machine-wide broker uniqueness (authoritative on Windows).
673
+ const lock = machineLock.acquireMachineBrokerLock();
674
+ if (!lock.acquired) {
675
+ console.error(`Another machine broker already holds the lock (${lock.primitive}): ${lock.detail}`);
676
+ process.exit(3);
677
+ }
678
+ // Hold it for the process lifetime via a dedicated holder process.
679
+ const holder = machineLock.startMutexHolder();
680
+ if (!holder.ok) {
681
+ console.error(`Could not hold the machine broker lock: ${holder.detail}`);
682
+ process.exit(3);
683
+ }
684
+
685
+ // 2. machine state + identity (broker owns the credential).
686
+ try { machineState.initializeMachineState(); } catch { }
687
+
688
+ console.log(`XKWDStore Agent broker v${CLI_VERSION} (machine-wide)`);
689
+ console.log(`Machine root: ${machineState.getMachineRoot()}`);
690
+ console.log(`Broker lock: ${lock.detail}`);
691
+
692
+ // 3. connect to the server (broker owns the WebSocket).
693
+ // `--offline` (test-lifecycle only) skips the server connection so the service
694
+ // host / mutex / identity can be proven without a live enrollment. Production
695
+ // always connects.
696
+ const offline = !!flags.offline;
697
+ let ws = null;
698
+ if (offline) {
699
+ console.log('Broker running OFFLINE (lifecycle test mode; no server connection)');
700
+ }
701
+
702
+ if (offline) {
703
+ // Prove identity loads and the broker stays alive; keep the mutex held.
704
+ const meta = (() => { try { return require('./deviceKeyStore').loadMetadata({ serverOrigin }); } catch { return null; } })();
705
+ console.log(`Broker identity: ${meta && meta.deviceId ? meta.deviceId : '(none)'}`);
706
+
707
+ // --probe-worker: open the bridge, launch the interactive worker, and report
708
+ // the worker's Windows session id so the Session-0 -> interactive-session
709
+ // launch is PROVEN with a real process. Lifecycle-test only.
710
+ if (flags['probe-worker']) {
711
+ const bridge = require('./brokerWorkerBridge');
712
+ const token = bridge.newChannelToken();
713
+ const channel = await bridge.openBrokerChannel({ token });
714
+ console.log(`probe: bridge port ${channel.port}`);
715
+ const child = _spawnInteractiveWorker({ port: channel.port, token });
716
+ const deadline = Date.now() + 20000;
717
+ while (!channel.connected && Date.now() < deadline) { await new Promise((r) => setTimeout(r, 150)); }
718
+ console.log(`probe: worker connected=${channel.connected}`);
719
+ console.log(`probe: activeConsoleSession=${_activeConsoleSession()} workerSession=${typeof child.session === 'number' ? child.session : 'n/a'}`);
720
+ try {
721
+ const st = await channel.call('getStatus', {}, 10000);
722
+ console.log('probe: worker status ' + JSON.stringify(st));
723
+ } catch (e) {
724
+ console.log('probe: worker status error ' + ((e && e.message) || 'unknown'));
725
+ }
726
+ // Give the harness time to inspect the worker process, then stop it.
727
+ await new Promise((r) => setTimeout(r, 12000));
728
+ try { await channel.call('shutdown', {}, 5000); } catch { }
729
+ try { channel.close(); } catch { }
730
+ console.log('probe: done');
731
+ machineLock.releaseMachineBrokerLock();
732
+ process.exit(0);
733
+ }
734
+
735
+ console.log('Broker alive; holding the machine lock. Ctrl+C to stop.');
736
+ const t = setInterval(() => {
737
+ try { console.log('broker heartbeat ' + new Date().toISOString()); } catch { }
738
+ }, 15000);
739
+ t.unref();
740
+ await new Promise(() => { }); // run until killed
741
+ }
742
+
743
+ // 4. spawn one interactive worker and route typed commands to it.
744
+ const bridge = require('./brokerWorkerBridge');
745
+ const token = bridge.newChannelToken();
746
+ const channel = await bridge.openBrokerChannel({ token });
747
+ const sessionHandler = require('./sessionHandler');
748
+
749
+ // The broker does NOT launch Chromium: it forwards startSession/stopSession to
750
+ // the worker. A worker is SESSION-BOUND: it is launched into the currently
751
+ // ACTIVE console session and is DISPOSABLE — a worker left over from a previous
752
+ // user (e.g. after a fast user switch) must NEVER serve a new session's job.
753
+ let worker = null;
754
+ let workerSession = -1;
755
+ async function ensureWorker() {
756
+ const active = _activeConsoleSession();
757
+ // Reuse the connected worker ONLY when it is in the CURRENT active session.
758
+ // On a change of active session the stale worker is torn down first (see the
759
+ // pure `shouldReplaceWorker` truth table).
760
+ const replace = bridge.shouldReplaceWorker({ connected: channel.connected, workerSession, activeSession: active });
761
+ if (!replace) return;
762
+ if (channel.connected) {
763
+ try { console.log(`worker session ${workerSession} != active ${active}; replacing the worker`); } catch { }
764
+ try { await channel.call('shutdown', {}, 5000); } catch { }
765
+ try { channel.dropWorker(); } catch { }
766
+ try { if (worker && worker.child) worker.child.kill(); } catch { }
767
+ workerSession = -1;
768
+ // Give the channel a moment to clear the old worker.
769
+ await new Promise((r) => setTimeout(r, 300));
770
+ }
771
+ worker = _spawnInteractiveWorker({ port: channel.port, token });
772
+ const deadline = Date.now() + 15000;
773
+ while (!channel.connected && Date.now() < deadline) { await new Promise((r) => setTimeout(r, 100)); }
774
+ if (!channel.connected) throw new Error('interactive worker did not attach');
775
+ // The launcher reports the target session on its stdout; wait briefly for it.
776
+ const sdeadline = Date.now() + 3000;
777
+ while (workerSession === -1 && Date.now() < sdeadline) {
778
+ workerSession = typeof worker.session === 'number' ? worker.session : -1;
779
+ if (workerSession === -1) await new Promise((r) => setTimeout(r, 100));
780
+ }
781
+ try { console.log(`worker attached (session=${workerSession}, active=${active})`); } catch { }
782
+ }
783
+
784
+ const { setupSessionHandler, closeAllSessions, markDisconnected } = sessionHandler;
785
+ const { createBrokerConnectionSupervisor } = require('./brokerConnectionSupervisor');
786
+
787
+ // 4a. ONE reconnect supervisor owns the production WebSocket lifecycle so a
788
+ // transient network/DNS/TLS/backend/WS/heartbeat loss reconnects with the
789
+ // SAME enrolled identity — no manual restart, no re-pair, no new key. Retries
790
+ // are UNBOUNDED for the machine service (a long-lived broker must self-heal);
791
+ // the supervisor preserves exactly one timer / one attempt / one socket.
792
+ const _bindSessionHandler = (socket) => setupSessionHandler(socket, {
793
+ // The broker has no chromePath: all browser work goes through the worker.
794
+ chromePath: null,
795
+ deviceMeta: require('./deviceKeyStore').loadMetadata({ serverOrigin }) || {},
796
+ serverOrigin,
797
+ // 2.1.0: route browser commands through the worker bridge.
798
+ workerBridge: {
799
+ ensureWorker,
800
+ call: (command, payload) => channel.call(command, payload),
801
+ },
802
+ });
803
+
804
+ const supervisor = createBrokerConnectionSupervisor({
805
+ connect: () => _brokerConnect(serverOrigin),
806
+ // Rebind the FULL session handler on every (re)connect; the server drives
807
+ // lease reconciliation from our sessions-report (protocol v2).
808
+ onConnected: (socket) => { _bindSessionHandler(socket); },
809
+ // On a REAL disconnect stop accepting remote commands. Durable leases are
810
+ // server-owned and are NOT released locally — the server reconciles them
811
+ // after we reconnect.
812
+ onDisconnected: () => { try { markDisconnected(); } catch { } },
813
+ // Auth/identity rejection: stay running and retry conservatively. NEVER
814
+ // delete the credential or mint a new identity here.
815
+ onAuthRejected: () => { try { console.error('[broker] authentication/identity rejected; identity preserved, retrying conservatively'); } catch { } },
816
+ log: (m) => { try { console.log(m); } catch { } },
817
+ });
818
+ console.log(`Broker connecting to ${serverOrigin} ...`);
819
+ Promise.resolve(supervisor.start()).catch(() => {});
820
+
821
+ async function shutdown(signal) {
822
+ console.log(`\n${signal} received. Broker shutting down...`);
823
+ // Stop reconnecting FIRST so no retry can start after shutdown begins.
824
+ try { supervisor.stop(); } catch { }
825
+ try { await channel.call('shutdown', {}, 5000); } catch { }
826
+ try { if (worker) worker.kill(); } catch { }
827
+ try { channel.close(); } catch { }
828
+ try { await closeAllSessions(); } catch { }
829
+ machineLock.releaseMachineBrokerLock();
830
+ process.exit(0);
831
+ }
832
+ process.on('SIGINT', () => shutdown('Ctrl+C'));
833
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
834
+ }
835
+
836
+ /** The currently ACTIVE Windows console session id, via the compiled launcher's
837
+ * `-Query` mode. Returns -1 when it cannot be determined (fail-safe). */
838
+ function _activeConsoleSession() {
839
+ try {
840
+ const path = require('path');
841
+ const fs = require('fs');
842
+ const { execFileSync } = require('child_process');
843
+ const machineRoot = require('./machineState').getMachineRoot();
844
+ const launcherExe = path.join(machineRoot, 'launcher', 'XKWDStoreSessionLauncher.exe');
845
+ if (os.platform() !== 'win32' || !fs.existsSync(launcherExe)) return -1;
846
+ const out = execFileSync(launcherExe, ['-Query'], { encoding: 'utf8', windowsHide: true, timeout: 5000 }).trim();
847
+ const m = /SESSION=(-?\d+)/.exec(out);
848
+ return m ? parseInt(m[1], 10) : -1;
849
+ } catch { return -1; }
850
+ }
851
+
852
+ /** Spawn an interactive browser worker into the ACTIVE INTERACTIVE session.
853
+ *
854
+ * The broker runs as a Session-0 service, which has no desktop. A plain
855
+ * child_process.spawn would create the worker (and its Chromium) in Session 0,
856
+ * where no browser can be shown. When the broker is in Session 0 we therefore
857
+ * launch the worker via the compiled session launcher (CreateProcessAsUser with
858
+ * the active console session's user token). When the broker already runs in an
859
+ * interactive session (foreground `start`), a direct spawn is equivalent.
860
+ *
861
+ * Returns { child, session } where `session` is the Windows session the worker
862
+ * was launched into (or -1 when unknown). The broker records this so it never
863
+ * reuses a worker from a session that is no longer the active console session.
864
+ */
865
+ function _spawnInteractiveWorker({ port, token }) {
866
+ const { spawn } = require('child_process');
867
+ const path = require('path');
868
+ const fs = require('fs');
869
+ const workerScript = path.join(__dirname, 'worker.js');
870
+ const workerArgs = ['--port', String(port), '--token', token];
871
+
872
+ const machineRoot = require('./machineState').getMachineRoot();
873
+ const launcherExe = path.join(machineRoot, 'launcher', 'XKWDStoreSessionLauncher.exe');
874
+
875
+ if (os.platform() === 'win32' && fs.existsSync(launcherExe)) {
876
+ // Launch into the active interactive session. The launcher prints
877
+ // `LAUNCHED pid=N session=S`; capture it so the worker is session-bound.
878
+ const logDir = path.join(machineRoot, 'logs');
879
+ try { fs.mkdirSync(logDir, { recursive: true }); } catch { }
880
+ const outLog = path.join(logDir, 'worker.out.log');
881
+ const errLog = path.join(logDir, 'worker.err.log');
882
+ const child = spawn(launcherExe, [
883
+ '-Exe', process.execPath,
884
+ '-Args', '"' + workerScript + '" ' + workerArgs.join(' '),
885
+ '-Cwd', __dirname,
886
+ '-Out', outLog,
887
+ '-Err', errLog,
888
+ ], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
889
+ let session = -1;
890
+ let buf = '';
891
+ try {
892
+ child.stdout.on('data', (d) => {
893
+ buf += d.toString();
894
+ const m = /session=(-?\d+)/.exec(buf);
895
+ if (m) session = parseInt(m[1], 10);
896
+ });
897
+ } catch { }
898
+ return { child, get session() { return session; } };
899
+ }
900
+
901
+ // Interactive/foreground fallback: the broker is already in the right session.
902
+ const child = spawn(process.execPath, [workerScript, ...workerArgs], {
903
+ detached: false,
904
+ stdio: ['ignore', 'inherit', 'inherit'],
905
+ windowsHide: true,
906
+ });
907
+ return { child, session: _activeConsoleSession() };
908
+ }
909
+
910
+ /** Connect the broker's WebSocket using the machine credential. */
911
+ async function _brokerConnect(serverOrigin) {
912
+ const { getStoredDevice, getStoredPrivateKey } = require('./enrollmentClient');
913
+ const deviceMeta = getStoredDevice({ serverOrigin });
914
+ const privateKeyB64Url = await getStoredPrivateKey({ serverOrigin });
915
+ if (!deviceMeta || !privateKeyB64Url) {
916
+ throw new Error('device is not enrolled; run `xkwd-agent start` once to authorize this machine');
917
+ }
918
+ const { connectWebSocket } = require('./wsClient');
919
+ return connectWebSocket({
920
+ serverOrigin,
921
+ deviceId: deviceMeta.deviceId,
922
+ publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
923
+ privateKeyB64Url,
924
+ protocolVersion: PROTOCOL_VERSION,
925
+ });
926
+ }
927
+
572
928
  /**
573
929
  * `xkwd-agent doctor` — diagnostic checks.
574
930
  */
@@ -612,9 +968,13 @@ async function doctor(serverOrigin) {
612
968
  console.log(`Secure storage: ${isSecureStorageAvailable() ? 'available ✓' : 'unavailable ✗'}`);
613
969
  }
614
970
 
615
- // Check data directory
971
+ // Check data directory (machine-wide since 2.1.0)
616
972
  const dataDir = getDataDir();
617
- console.log(`Data directory: ${dataDir}`);
973
+ const legacyDir = require('./deviceKeyStore').getLegacyDataDir();
974
+ console.log(`Machine state root: ${dataDir}`);
975
+ console.log(`Legacy per-user root: ${legacyDir}`);
976
+ const machineState = require('./machineState');
977
+ console.log(`Machine identity present: ${machineState.hasMachineIdentity() ? '✓' : '(none yet)'}`);
618
978
 
619
979
  // Check device identity (server-scoped)
620
980
  const { getStoredDevice, getStoredPrivateKey } = require('./enrollmentClient');
@@ -672,6 +1032,8 @@ Commands:
672
1032
  status Show device and connection status
673
1033
  logout Delete local device identity (requires re-authorization)
674
1034
  revoke-local Delete local device identity and credentials
1035
+ machine Machine-wide state: status | adopt | harden
1036
+ service Run the machine-wide broker (Windows Service host; silent)
675
1037
  doctor Run diagnostic checks
676
1038
  version Print version information
677
1039
  help Show this help
@@ -684,6 +1046,7 @@ Examples:
684
1046
  xkwd-agent start
685
1047
  xkwd-agent start --replace
686
1048
  xkwd-agent status
1049
+ xkwd-agent machine status
687
1050
  xkwd-agent doctor
688
1051
 
689
1052
  First run:
@@ -693,10 +1056,14 @@ First run:
693
1056
  To stop:
694
1057
  Press Ctrl+C in the terminal.
695
1058
 
696
- Data location:
697
- Windows: %LOCALAPPDATA%\\XKWDStore\\
698
- macOS: ~/Library/Application Support/XKWDStore/
699
- Linux: ~/.local/share/xkwdstore/
1059
+ Data location (machine-wide, shared by every Windows user on this PC):
1060
+ Windows: %ProgramData%\\XKWDStore\\Agent\\
1061
+ Linux: ${'{XDG_DATA_HOME:-~/.local/share}/xkwdstore/'}
1062
+ macOS: unsupported (fails closed)
1063
+
1064
+ Device identity belongs to the MACHINE. Changing the Windows user or the
1065
+ TW-manager preferred device does NOT create a second device identity.
1066
+ A pre-2.1.0 per-user install is adopted once (copy, never move).
700
1067
 
701
1068
  Requirements:
702
1069
  - Node.js 22 or later