@xkwdstore/agent 2.1.4 → 2.1.5
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/CHANGELOG.md +130 -0
- package/README.md +5 -3
- package/package.json +4 -3
- package/scripts/install-machine-agent.ps1 +2 -2
- package/src/actions/helpers.js +15 -21
- package/src/actions/session.js +142 -16
- package/src/brokerConnectionSupervisor.js +65 -9
- package/src/brokerHealth.js +113 -0
- package/src/brokerWorkerBridge.js +26 -1
- package/src/browserConnectivity.js +1461 -0
- package/src/browserLaunch.js +136 -0
- package/src/cli.js +198 -16
- package/src/cookieInjection.js +255 -0
- package/src/enrollmentClient.js +51 -26
- package/src/index.js +68 -53
- package/src/proxyCapability.js +481 -0
- package/src/sessionAuth.js +439 -0
- package/src/sessionHandler.js +706 -108
- package/src/worker.js +529 -79
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The ONE shared Chromium launch-options builder (2.1.5).
|
|
5
|
+
*
|
|
6
|
+
* Every runtime (machine worker, broker/direct session handler, legacy CLI)
|
|
7
|
+
* must launch the browser through this function so a browser configuration
|
|
8
|
+
* change applies consistently to existing AND newly created profiles:
|
|
9
|
+
*
|
|
10
|
+
* - `resolveChromiumPath()` still chooses the executable (system Chrome first,
|
|
11
|
+
* Playwright's bundled Chromium as fallback) — profiles are untouched.
|
|
12
|
+
* - Playwright silently injects `--disable-extensions` into every launch. For a
|
|
13
|
+
* Google Chrome / Edge executable we drop ONLY that default switch, so the
|
|
14
|
+
* extension subsystem (and the Chrome Web Store) stays available. This does
|
|
15
|
+
* NOT enable unpacked extension loading: branded Google Chrome (verified on
|
|
16
|
+
* 157.0.8103.80) logs
|
|
17
|
+
* "`--load-extension` is not allowed in Google Chrome, ignoring."
|
|
18
|
+
* "`--disable-extensions-except` is not allowed in Google Chrome, ignoring."
|
|
19
|
+
* so unbundled extensions only load on a Chromium/Chrome-for-Testing build.
|
|
20
|
+
* `describeBrowser()` reports that capability explicitly so no feature
|
|
21
|
+
* depends on a silent assumption.
|
|
22
|
+
* - NetLog capture is opt-in (`XKWDSTORE_NETLOG_DIR`) and never written into
|
|
23
|
+
* a profile directory; capture files are sanitized before an operator sees
|
|
24
|
+
* them (see browserConnectivity.sanitizeNetlogFile).
|
|
25
|
+
*
|
|
26
|
+
* This module deliberately contains no secrets and performs no I/O.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
const path = require('path');
|
|
30
|
+
const connectivity = require('./browserConnectivity');
|
|
31
|
+
|
|
32
|
+
/** Playwright default switches that must NOT apply to a managed Chrome. */
|
|
33
|
+
const PLAYWRIGHT_DEFAULT_ARGS_TO_DROP = Object.freeze(['--disable-extensions']);
|
|
34
|
+
|
|
35
|
+
const CHROME_EXECUTABLE_BASENAMES = Object.freeze([
|
|
36
|
+
'chrome.exe',
|
|
37
|
+
'msedge.exe',
|
|
38
|
+
'google-chrome',
|
|
39
|
+
'google-chrome-stable',
|
|
40
|
+
'chrome',
|
|
41
|
+
]);
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Classify the browser distribution from its executable path.
|
|
45
|
+
* @returns {'chrome'|'edge'|'chromium'|'unknown'}
|
|
46
|
+
*/
|
|
47
|
+
function browserFamily(executablePath) {
|
|
48
|
+
if (!executablePath || typeof executablePath !== 'string') return 'unknown';
|
|
49
|
+
const base = path.basename(executablePath).toLowerCase();
|
|
50
|
+
const norm = executablePath.replace(/\\/g, '/').toLowerCase();
|
|
51
|
+
if (base === 'chrome.exe' || base === 'chrome' || base === 'google-chrome' || base === 'google-chrome-stable') {
|
|
52
|
+
// A Playwright-managed Chromium build lives under a ms-playwright folder.
|
|
53
|
+
if (/ms-playwright|playwright[\\/]/i.test(norm)) return 'chromium';
|
|
54
|
+
return 'chrome';
|
|
55
|
+
}
|
|
56
|
+
if (base === 'msedge.exe' || base === 'msedge') return 'edge';
|
|
57
|
+
if (/chromium/.test(base)) return 'chromium';
|
|
58
|
+
return 'unknown';
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** True for a distribution that has a working Chrome Web Store. */
|
|
62
|
+
function supportsChromeWebStore(executablePath) {
|
|
63
|
+
const family = browserFamily(executablePath);
|
|
64
|
+
return family === 'chrome' || family === 'edge';
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Build the Playwright launch options for a managed session.
|
|
69
|
+
*
|
|
70
|
+
* @param {object} o
|
|
71
|
+
* @param {string} [o.chromePath] absolute executable path (system Chrome first)
|
|
72
|
+
* @param {boolean} [o.headless=false]
|
|
73
|
+
* @param {string[]} [o.args] already-sanitized Chromium args
|
|
74
|
+
* @param {object|null} [o.proxy] Playwright proxy option ({server,username,password})
|
|
75
|
+
* @param {string|null} [o.netlogPath] explicit NetLog destination
|
|
76
|
+
* @param {boolean} [o.captureNetlog] resolve the NetLog path from the environment
|
|
77
|
+
* @param {object} [o.viewport]
|
|
78
|
+
* @param {boolean} [o.noDefaultViewport=true]
|
|
79
|
+
* @returns {object} options accepted by chromium.launchPersistentContext
|
|
80
|
+
*/
|
|
81
|
+
function buildChromiumLaunchOptions(o = {}) {
|
|
82
|
+
const args = Array.isArray(o.args) ? o.args.slice() : [];
|
|
83
|
+
const options = {
|
|
84
|
+
executablePath: o.chromePath || undefined,
|
|
85
|
+
headless: o.headless === true,
|
|
86
|
+
args,
|
|
87
|
+
noDefaultViewport: o.noDefaultViewport !== false,
|
|
88
|
+
};
|
|
89
|
+
if (o.viewport) {
|
|
90
|
+
options.viewport = o.viewport;
|
|
91
|
+
options.noDefaultViewport = false;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (supportsChromeWebStore(o.chromePath)) {
|
|
95
|
+
options.ignoreDefaultArgs = PLAYWRIGHT_DEFAULT_ARGS_TO_DROP.slice();
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (o.proxy && o.proxy.server) options.proxy = o.proxy;
|
|
99
|
+
|
|
100
|
+
const netlogPath = o.netlogPath || (o.captureNetlog === true ? connectivity.resolveNetlogPath() : null);
|
|
101
|
+
if (netlogPath) {
|
|
102
|
+
args.push(...connectivity.netlogLaunchArgs(netlogPath));
|
|
103
|
+
options.netlogPath = netlogPath;
|
|
104
|
+
}
|
|
105
|
+
return options;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* A sanitized, non-secret description of the browser distribution for reports
|
|
110
|
+
* and `getStatus` responses.
|
|
111
|
+
*/
|
|
112
|
+
function describeBrowser(executablePath) {
|
|
113
|
+
const family = browserFamily(executablePath);
|
|
114
|
+
const branded = family === 'chrome' || family === 'edge';
|
|
115
|
+
return {
|
|
116
|
+
executablePath: executablePath || null,
|
|
117
|
+
family,
|
|
118
|
+
chromeWebStore: supportsChromeWebStore(executablePath),
|
|
119
|
+
extensionSubsystemEnabled: branded,
|
|
120
|
+
// Unpacked (--load-extension) loading: branded Chrome/Edge IGNORE the switch
|
|
121
|
+
// (verified on Chrome 157 and 158: extension_service.cc "not allowed in Google
|
|
122
|
+
// Chrome, ignoring"). Only a Chromium / Chrome-for-Testing build honours it.
|
|
123
|
+
unpackedExtensionLoading: family === 'chromium',
|
|
124
|
+
webStoreInstall: branded ? 'human-confirmation-required' : 'unsupported',
|
|
125
|
+
droppedPlaywrightDefaults: branded ? PLAYWRIGHT_DEFAULT_ARGS_TO_DROP.slice() : [],
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
module.exports = {
|
|
130
|
+
PLAYWRIGHT_DEFAULT_ARGS_TO_DROP,
|
|
131
|
+
CHROME_EXECUTABLE_BASENAMES,
|
|
132
|
+
browserFamily,
|
|
133
|
+
supportsChromeWebStore,
|
|
134
|
+
buildChromiumLaunchOptions,
|
|
135
|
+
describeBrowser,
|
|
136
|
+
};
|
package/src/cli.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
* Usage:
|
|
12
12
|
* npx --yes @xkwdstore/agent@<PINNED_VERSION> start
|
|
13
13
|
* npx --yes @xkwdstore/agent@<PINNED_VERSION> status
|
|
14
|
+
* npx --yes @xkwdstore/agent@<PINNED_VERSION> recover
|
|
14
15
|
* npx --yes @xkwdstore/agent@<PINNED_VERSION> logout
|
|
15
16
|
* npx --yes @xkwdstore/agent@<PINNED_VERSION> revoke-local
|
|
16
17
|
* npx --yes @xkwdstore/agent@<PINNED_VERSION> doctor
|
|
@@ -24,7 +25,7 @@ const crypto = require('crypto');
|
|
|
24
25
|
const os = require('os');
|
|
25
26
|
const path = require('path');
|
|
26
27
|
|
|
27
|
-
const CLI_VERSION = '2.1.
|
|
28
|
+
const CLI_VERSION = '2.1.5';
|
|
28
29
|
const PROTOCOL_VERSION = 2;
|
|
29
30
|
|
|
30
31
|
// ── Command parsing ──────────────────────────────────────────────────────────
|
|
@@ -60,6 +61,8 @@ function main() {
|
|
|
60
61
|
return start(serverOrigin, flags);
|
|
61
62
|
case 'status':
|
|
62
63
|
return status();
|
|
64
|
+
case 'recover':
|
|
65
|
+
return recover(serverOrigin);
|
|
63
66
|
case 'logout':
|
|
64
67
|
return logout();
|
|
65
68
|
case 'revoke-local':
|
|
@@ -449,15 +452,23 @@ async function start(serverOrigin, flags) {
|
|
|
449
452
|
try { await closeAllSessions(); } catch { }
|
|
450
453
|
},
|
|
451
454
|
onAuthRejected: () => {
|
|
452
|
-
// 4003: the credential is dead.
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
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 */ }
|
|
461
472
|
process.exit(1);
|
|
462
473
|
},
|
|
463
474
|
onExhausted: () => {
|
|
@@ -531,6 +542,21 @@ function status() {
|
|
|
531
542
|
console.log(`Machine root: ${machineState.getMachineRoot()}`);
|
|
532
543
|
console.log(`Machine identity: ${machineState.hasMachineIdentity() ? 'present' : 'not yet adopted'}\n`);
|
|
533
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
|
+
|
|
534
560
|
if (!device) {
|
|
535
561
|
console.log('Status: Not authorized');
|
|
536
562
|
console.log('Run `xkwd-agent start` to authorize this computer.');
|
|
@@ -552,6 +578,78 @@ function status() {
|
|
|
552
578
|
}
|
|
553
579
|
}
|
|
554
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
|
+
|
|
555
653
|
/**
|
|
556
654
|
* `xkwd-agent logout` — delete local device identity (re-enrollment required).
|
|
557
655
|
* Server-scoped: only deletes the identity for the specified server.
|
|
@@ -684,6 +782,45 @@ async function service(serverOrigin, flags) {
|
|
|
684
782
|
|
|
685
783
|
// 2. machine state + identity (broker owns the credential).
|
|
686
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' });
|
|
687
824
|
|
|
688
825
|
console.log(`XKWDStore Agent broker v${CLI_VERSION} (machine-wide)`);
|
|
689
826
|
console.log(`Machine root: ${machineState.getMachineRoot()}`);
|
|
@@ -805,14 +942,36 @@ async function service(serverOrigin, flags) {
|
|
|
805
942
|
connect: () => _brokerConnect(serverOrigin),
|
|
806
943
|
// Rebind the FULL session handler on every (re)connect; the server drives
|
|
807
944
|
// lease reconciliation from our sessions-report (protocol v2).
|
|
808
|
-
onConnected: (socket) => {
|
|
945
|
+
onConnected: (socket) => {
|
|
946
|
+
_clearAuthRecoveryWatch();
|
|
947
|
+
_bindSessionHandler(socket);
|
|
948
|
+
_writeBrokerHealth({ state: 'connected', authBlocked: false, reauthorizationRequired: false, authFailures: 0 });
|
|
949
|
+
},
|
|
809
950
|
// On a REAL disconnect stop accepting remote commands. Durable leases are
|
|
810
951
|
// server-owned and are NOT released locally — the server reconciles them
|
|
811
952
|
// after we reconnect.
|
|
812
953
|
onDisconnected: () => { try { markDisconnected(); } catch { } },
|
|
813
|
-
// Auth/identity rejection:
|
|
814
|
-
//
|
|
815
|
-
|
|
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
|
+
},
|
|
816
975
|
log: (m) => { try { console.log(m); } catch { } },
|
|
817
976
|
});
|
|
818
977
|
console.log(`Broker connecting to ${serverOrigin} ...`);
|
|
@@ -821,9 +980,23 @@ async function service(serverOrigin, flags) {
|
|
|
821
980
|
async function shutdown(signal) {
|
|
822
981
|
console.log(`\n${signal} received. Broker shutting down...`);
|
|
823
982
|
// Stop reconnecting FIRST so no retry can start after shutdown begins.
|
|
983
|
+
_clearAuthRecoveryWatch();
|
|
824
984
|
try { supervisor.stop(); } catch { }
|
|
825
|
-
|
|
826
|
-
|
|
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 { }
|
|
827
1000
|
try { channel.close(); } catch { }
|
|
828
1001
|
try { await closeAllSessions(); } catch { }
|
|
829
1002
|
machineLock.releaseMachineBrokerLock();
|
|
@@ -986,6 +1159,13 @@ async function doctor(serverOrigin) {
|
|
|
986
1159
|
} else {
|
|
987
1160
|
console.log('Device ID: not enrolled for this server');
|
|
988
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
|
+
}
|
|
989
1169
|
|
|
990
1170
|
// Check server connectivity (shared strict validator)
|
|
991
1171
|
try {
|
|
@@ -1030,6 +1210,7 @@ Usage:
|
|
|
1030
1210
|
Commands:
|
|
1031
1211
|
start Start the agent (connects to server, runs browser sessions)
|
|
1032
1212
|
status Show device and connection status
|
|
1213
|
+
recover Re-authorize THIS device after revocation/replacement (owner approval)
|
|
1033
1214
|
logout Delete local device identity (requires re-authorization)
|
|
1034
1215
|
revoke-local Delete local device identity and credentials
|
|
1035
1216
|
machine Machine-wide state: status | adopt | harden
|
|
@@ -1046,6 +1227,7 @@ Examples:
|
|
|
1046
1227
|
xkwd-agent start
|
|
1047
1228
|
xkwd-agent start --replace
|
|
1048
1229
|
xkwd-agent status
|
|
1230
|
+
xkwd-agent recover
|
|
1049
1231
|
xkwd-agent machine status
|
|
1050
1232
|
xkwd-agent doctor
|
|
1051
1233
|
|