@xkwdstore/agent 2.0.3 → 2.0.4
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/README.md +9 -8
- package/package.json +1 -1
- package/src/cli.js +118 -46
- package/src/sessionHandler.js +270 -15
package/README.md
CHANGED
|
@@ -4,10 +4,11 @@ Terminal-only, cryptographically authenticated CLI for XKWDStore browser automat
|
|
|
4
4
|
|
|
5
5
|
## Installation
|
|
6
6
|
|
|
7
|
-
> **@xkwdstore/agent 2.0.
|
|
7
|
+
> **@xkwdstore/agent 2.0.3 is the last version published on npm.**
|
|
8
8
|
>
|
|
9
|
-
>
|
|
10
|
-
> published
|
|
9
|
+
> The current source version is **2.0.4** (lease same-device recovery fix). It is
|
|
10
|
+
> NOT claimed to be published unless the release workflow has published it — see
|
|
11
|
+
> `reports/` for the authoritative publication state.
|
|
11
12
|
|
|
12
13
|
End users install by downloading the installer file first, then running it
|
|
13
14
|
(the installer explicitly forbids piping a remote script directly into
|
|
@@ -28,7 +29,7 @@ curl -L -o "%TEMP%\xkwdstore-install.ps1" https://raw.githubusercontent.com/Essa
|
|
|
28
29
|
The generated launcher runs the pinned command:
|
|
29
30
|
|
|
30
31
|
```powershell
|
|
31
|
-
npx --yes @xkwdstore/agent@2.0.
|
|
32
|
+
npx --yes @xkwdstore/agent@2.0.4 start
|
|
32
33
|
```
|
|
33
34
|
|
|
34
35
|
Automated installer tests use `-NoLaunch` or a mocked `npx` command so the
|
|
@@ -173,14 +174,14 @@ Windows runner (pending CI billing restoration).
|
|
|
173
174
|
## Version Management
|
|
174
175
|
|
|
175
176
|
The agent does NOT update itself. To use a newer version, change the version
|
|
176
|
-
number in the command. The pinned
|
|
177
|
+
number in the command. The pinned command for this release is:
|
|
177
178
|
|
|
178
179
|
```powershell
|
|
179
|
-
npx --yes @xkwdstore/agent@2.0.
|
|
180
|
+
npx --yes @xkwdstore/agent@2.0.4 start
|
|
180
181
|
```
|
|
181
182
|
|
|
182
|
-
>
|
|
183
|
-
>
|
|
183
|
+
> 2.0.4 is the current local agent version (same-device lease recovery fix).
|
|
184
|
+
> 2.0.3 was the previous release.
|
|
184
185
|
>
|
|
185
186
|
> The server checks compatibility at startup and displays a clear message if
|
|
186
187
|
> the agent version is no longer supported.
|
package/package.json
CHANGED
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.
|
|
27
|
+
const CLI_VERSION = '2.0.4';
|
|
28
28
|
const PROTOCOL_VERSION = 2;
|
|
29
29
|
|
|
30
30
|
// ── Command parsing ──────────────────────────────────────────────────────────
|
|
@@ -319,63 +319,135 @@ async function start(serverOrigin, flags) {
|
|
|
319
319
|
const { setupSessionHandler, closeAllSessions, markDisconnected } = require('./sessionHandler');
|
|
320
320
|
const sessions = setupSessionHandler(ws, { chromePath, deviceMeta, serverOrigin });
|
|
321
321
|
|
|
322
|
-
// 8a.
|
|
323
|
-
//
|
|
324
|
-
//
|
|
325
|
-
//
|
|
326
|
-
//
|
|
327
|
-
//
|
|
328
|
-
//
|
|
329
|
-
//
|
|
322
|
+
// 8a. Disconnect handling with bounded auto-reconnect.
|
|
323
|
+
//
|
|
324
|
+
// The server deliberately closes the WS in two situations where the agent is
|
|
325
|
+
// EXPECTED to reconnect (the dashboard's Restart Agent button promises "the
|
|
326
|
+
// agent will reconnect in a few seconds"):
|
|
327
|
+
// - graceful 'agent-restart' message → code 1000 'agent-restart'
|
|
328
|
+
// - fallback restart → code 4002 'Server-initiated restart'
|
|
329
|
+
// In BOTH cases the local browser sessions are meant to STAY OPEN (only the
|
|
330
|
+
// WS is re-established) — see localAgentServer.restartAgent. On reconnect the
|
|
331
|
+
// server requests a sessions-report and reconciles every lease-bound session
|
|
332
|
+
// itself, so lease reconciliation is server-driven and authoritative.
|
|
333
|
+
//
|
|
334
|
+
// Any OTHER close (heartbeat timeout 4002 'Heartbeat timeout', network 1006,
|
|
335
|
+
// protocol error) is a genuine disconnect: the agent marks itself
|
|
336
|
+
// disconnected, closes every browser context (preserving profiles/cookies),
|
|
337
|
+
// and retries with exponential backoff. After MAX_WS_RECONNECTS consecutive
|
|
338
|
+
// failures the agent exits non-zero with a clear message (the original
|
|
339
|
+
// fail-safe).
|
|
330
340
|
//
|
|
331
341
|
// Race guard: `shuttingDown` is set by the deliberate Ctrl+C/SIGTERM path
|
|
332
342
|
// BEFORE ws.close() is called, so the close event emitted during a
|
|
333
|
-
// deliberate shutdown does NOT run
|
|
334
|
-
// This prevents closeAllSessions() from being executed concurrently twice
|
|
335
|
-
// and processLock.releaseLock() from being called twice.
|
|
336
|
-
let disconnected = false;
|
|
343
|
+
// deliberate shutdown does NOT run this handler.
|
|
337
344
|
let shuttingDown = false;
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
345
|
+
let reconnectAttempts = 0;
|
|
346
|
+
const MAX_WS_RECONNECTS = 10;
|
|
347
|
+
const RECONNECT_BASE_MS = 1000;
|
|
348
|
+
const RECONNECT_MAX_MS = 60000;
|
|
349
|
+
|
|
350
|
+
const _connectOpts = () => ({
|
|
351
|
+
serverOrigin,
|
|
352
|
+
deviceId: deviceMeta.deviceId,
|
|
353
|
+
publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
|
|
354
|
+
privateKeyB64Url,
|
|
355
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
const _isRestartClose = (code, reasonStr) =>
|
|
359
|
+
(code === 1000 && /agent-restart/i.test(reasonStr))
|
|
360
|
+
|| (code === 4002 && /server-initiated restart/i.test(reasonStr));
|
|
361
|
+
|
|
362
|
+
const _delayMs = () => Math.min(RECONNECT_BASE_MS * Math.pow(2, reconnectAttempts), RECONNECT_MAX_MS)
|
|
363
|
+
+ Math.floor(Math.random() * 1000);
|
|
364
|
+
|
|
365
|
+
async function _handleWsClose(code, reason) {
|
|
341
366
|
if (shuttingDown) return;
|
|
342
|
-
if (disconnected) return;
|
|
343
|
-
disconnected = true;
|
|
344
|
-
markDisconnected();
|
|
345
367
|
const reasonStr = reason ? reason.toString() : '';
|
|
346
|
-
console.error(`\n✗ Connection to server lost (code ${code}${reasonStr ? ': ' + reasonStr : ''}).`);
|
|
347
|
-
console.error(' Closing all browser sessions and shutting down safely...');
|
|
348
368
|
|
|
349
|
-
//
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
369
|
+
// Deliberate server-initiated restart: rebind WITHOUT touching sessions.
|
|
370
|
+
if (_isRestartClose(code, reasonStr)) {
|
|
371
|
+
console.log('\nℹ️ Server requested a connection restart. Reconnecting (browser sessions stay open)...');
|
|
372
|
+
// Do NOT markDisconnected / closeAllSessions here — the local browsers
|
|
373
|
+
// remain valid; the server reconciles their leases from our
|
|
374
|
+
// sessions-report after we reconnect.
|
|
375
|
+
try { ws.removeAllListeners('close'); } catch {}
|
|
376
|
+
} else {
|
|
377
|
+
// Genuine disconnect: fail-safe. No further commands may run, and every
|
|
378
|
+
// browser context is closed (profiles persist on close).
|
|
379
|
+
console.error(`\n✗ Connection to server lost (code ${code}${reasonStr ? ': ' + reasonStr : ''}).`);
|
|
380
|
+
console.error(' Closing all browser sessions and shutting down safely...');
|
|
381
|
+
markDisconnected();
|
|
382
|
+
const { closed } = await closeAllSessions().catch(() => ({ closed: 0 }));
|
|
357
383
|
if (closed > 0) console.error(` Closed ${closed} browser session(s).`);
|
|
358
|
-
|
|
359
|
-
|
|
384
|
+
try { ws.removeAllListeners('close'); } catch {}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// 4003 = revoked mid-session: the credential is dead — re-enroll requires
|
|
388
|
+
// user interaction, so exit with a clear message (no auto-retry loop).
|
|
389
|
+
if (code === 4003) {
|
|
390
|
+
console.error('\n❌ Authentication failed — this device was revoked during the session.');
|
|
391
|
+
console.error(' The server-scoped identity for ' + serverOrigin + ' has been cleared.');
|
|
392
|
+
console.error(' Run `xkwd-agent start` again to re-authorize this computer.');
|
|
393
|
+
try {
|
|
394
|
+
const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
|
|
395
|
+
deletePrivateKey({ serverOrigin });
|
|
396
|
+
deleteMetadata({ serverOrigin });
|
|
397
|
+
} catch {}
|
|
360
398
|
processLock.releaseLock();
|
|
399
|
+
console.error('Agent stopped.');
|
|
400
|
+
process.exit(1);
|
|
401
|
+
}
|
|
361
402
|
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
deletePrivateKey({ serverOrigin });
|
|
370
|
-
deleteMetadata({ serverOrigin });
|
|
371
|
-
} catch {}
|
|
372
|
-
} else {
|
|
373
|
-
console.error('\nTo reconnect, run `xkwd-agent start` again.');
|
|
374
|
-
}
|
|
403
|
+
// Bounded reconnect with backoff + jitter (a fresh challenge every time —
|
|
404
|
+
// network loss never re-enrolls; only a 4003 does, handled above).
|
|
405
|
+
reconnectAttempts += 1;
|
|
406
|
+
if (reconnectAttempts > MAX_WS_RECONNECTS) {
|
|
407
|
+
console.error(`\n❌ Could not reconnect after ${MAX_WS_RECONNECTS} attempts.`);
|
|
408
|
+
console.error(' Run `xkwd-agent start` again.');
|
|
409
|
+
processLock.releaseLock();
|
|
375
410
|
console.error('Agent stopped.');
|
|
376
411
|
process.exit(1);
|
|
377
|
-
}
|
|
378
|
-
|
|
412
|
+
}
|
|
413
|
+
const delay = _delayMs();
|
|
414
|
+
console.log(` Reconnecting in ${Math.round(delay / 1000)}s (attempt ${reconnectAttempts}/${MAX_WS_RECONNECTS})...`);
|
|
415
|
+
setTimeout(() => { _reconnect().catch(() => {}); }, delay);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
async function _reconnect() {
|
|
419
|
+
try {
|
|
420
|
+
ws = await connectWebSocket(_connectOpts());
|
|
421
|
+
reconnectAttempts = 0; // reset on a successful re-establish
|
|
422
|
+
// Rebind the FULL session handler on the new socket (fresh runtime
|
|
423
|
+
// state: connected, heartbeat timer, command envelope handling).
|
|
424
|
+
setupSessionHandler(ws, { chromePath, deviceMeta, serverOrigin });
|
|
425
|
+
// A sessions-report request arrives from the server right after
|
|
426
|
+
// authentication; the handler answers it from the live sessions map,
|
|
427
|
+
// which lets the server reconcile/restore every lease.
|
|
428
|
+
console.log('✓ Reconnected.');
|
|
429
|
+
ws.on('close', (code, reason) => { _handleWsClose(code, reason).catch(() => {}); });
|
|
430
|
+
} catch (err) {
|
|
431
|
+
if (_is4003Error(err)) {
|
|
432
|
+
// Fall into the 4003 exit path via the same handler logic.
|
|
433
|
+
await _handleWsClose(4003, Buffer.from('revoked during reconnect'));
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
reconnectAttempts += 1;
|
|
437
|
+
if (reconnectAttempts > MAX_WS_RECONNECTS) {
|
|
438
|
+
console.error(`\n❌ Could not reconnect after ${MAX_WS_RECONNECTS} attempts: ${err.message}`);
|
|
439
|
+
console.error(' Run `xkwd-agent start` again.');
|
|
440
|
+
processLock.releaseLock();
|
|
441
|
+
console.error('Agent stopped.');
|
|
442
|
+
process.exit(1);
|
|
443
|
+
}
|
|
444
|
+
const delay = _delayMs();
|
|
445
|
+
console.log(` Reconnect failed (${err.message}). Retrying in ${Math.round(delay / 1000)}s (attempt ${reconnectAttempts}/${MAX_WS_RECONNECTS})...`);
|
|
446
|
+
setTimeout(() => { _reconnect().catch(() => {}); }, delay);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
ws.on('close', (code, reason) => { _handleWsClose(code, reason).catch(() => {}); });
|
|
379
451
|
|
|
380
452
|
// 9. Clean shutdown on Ctrl+C
|
|
381
453
|
async function shutdown(signal) {
|
package/src/sessionHandler.js
CHANGED
|
@@ -28,6 +28,62 @@ const { buildStealthScript } = require('./stealth');
|
|
|
28
28
|
const leaseClient = require('./leaseClient');
|
|
29
29
|
const { PROFILES_DIR } = require('./deviceKeyStore');
|
|
30
30
|
|
|
31
|
+
// ── Exact-profile Chrome detection (recovery probe) ──────────────────────────
|
|
32
|
+
//
|
|
33
|
+
// "activeSessions is empty" is NOT proof a browser stopped: an agent-process
|
|
34
|
+
// restart clears that map while Chrome may still be running. Recovery must use
|
|
35
|
+
// EXACT profile/process verification. We enumerate chrome.exe command lines and
|
|
36
|
+
// match the EXACT --user-data-dir against this account's resolved profile dir —
|
|
37
|
+
// never "newest Chrome", "any chrome.exe", window titles, or a global count.
|
|
38
|
+
function _chromeCommandLines() {
|
|
39
|
+
const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
|
|
40
|
+
const nodePath = require('path');
|
|
41
|
+
const { execFileSync } = require('child_process');
|
|
42
|
+
const psExe = nodePath.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
43
|
+
const script =
|
|
44
|
+
"$ErrorActionPreference='SilentlyContinue'; " +
|
|
45
|
+
"$procs = Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\"; " +
|
|
46
|
+
"$lines = @(); foreach ($p in $procs) { if ($p.CommandLine) { $lines += [string]$p.CommandLine } }; " +
|
|
47
|
+
"Write-Output (ConvertTo-Json -Compress @{ lines = @($lines) })";
|
|
48
|
+
const out = execFileSync(psExe, ['-NoProfile', '-NonInteractive', '-Command', script], {
|
|
49
|
+
windowsHide: true,
|
|
50
|
+
encoding: 'utf8',
|
|
51
|
+
timeout: 8000,
|
|
52
|
+
}).trim();
|
|
53
|
+
const parsed = JSON.parse(out);
|
|
54
|
+
const lines = parsed && parsed.lines != null ? parsed.lines : [];
|
|
55
|
+
return Array.isArray(lines) ? lines : [lines];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Test-only injectable Chrome-command-line provider (mirrors the atomicWrite
|
|
59
|
+
// directory-fsync hook). Tests inject synthetic command lines so exact-profile
|
|
60
|
+
// matching is provable without spawning real processes.
|
|
61
|
+
let _chromeLinesProvider = _chromeCommandLines;
|
|
62
|
+
function _setChromeLinesProvider(fn) { _chromeLinesProvider = typeof fn === 'function' ? fn : _chromeCommandLines; }
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Return 'running' | 'stopped' | 'unknown' for whether a Chrome process still
|
|
66
|
+
* owns the EXACT profile directory. Fails closed to 'unknown' on any error.
|
|
67
|
+
*/
|
|
68
|
+
function _detectProfileChromeRunning(profileDir) {
|
|
69
|
+
if (!profileDir) return 'unknown';
|
|
70
|
+
if (os.platform() !== 'win32') return 'unknown'; // no exact-profile inspection here
|
|
71
|
+
const nodePath = require('path');
|
|
72
|
+
try {
|
|
73
|
+
const target = nodePath.resolve(profileDir).replace(/[\\/]+$/, '').toLowerCase();
|
|
74
|
+
const lines = _chromeLinesProvider();
|
|
75
|
+
for (const line of lines) {
|
|
76
|
+
const m = /--user-data-dir=(?:"([^"]+)"|(\S+))/.exec(String(line));
|
|
77
|
+
if (!m) continue;
|
|
78
|
+
const got = (m[1] || m[2] || '').replace(/[\\/]+$/, '').toLowerCase();
|
|
79
|
+
if (got && nodePath.resolve(got) === target) return 'running';
|
|
80
|
+
}
|
|
81
|
+
return 'stopped';
|
|
82
|
+
} catch {
|
|
83
|
+
return 'unknown';
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
31
87
|
// ── Windows foreground helper ────────────────────────────────────────────────
|
|
32
88
|
//
|
|
33
89
|
// page.bringToFront() may be insufficient on real Windows to actually bring
|
|
@@ -164,6 +220,37 @@ function setupSessionHandler(ws, opts) {
|
|
|
164
220
|
currentRuntime.disconnected = false;
|
|
165
221
|
currentRuntime.sessions = activeSessions;
|
|
166
222
|
|
|
223
|
+
// ── Agent → server heartbeat (protocol v2) ────────────────────────────────
|
|
224
|
+
// The server closes the WS with 4002 "Heartbeat timeout" when no inbound
|
|
225
|
+
// frame refreshes lastHeartbeat for 3× HEARTBEAT_SECONDS (20s → 60s). The
|
|
226
|
+
// server never sends its own heartbeat frames, so a v2 agent that only
|
|
227
|
+
// RESPONDS to (never-sent) heartbeats is disconnected after ~60s. This
|
|
228
|
+
// mirrors the v1 agent: send an application-level {type:'heartbeat'} frame
|
|
229
|
+
// every 10s (well within the 60s budget and the server's per-type rate
|
|
230
|
+
// limit) plus a WS protocol ping to keep proxies from idling out.
|
|
231
|
+
let heartbeatTimer = null;
|
|
232
|
+
const HEARTBEAT_INTERVAL_MS = parseInt(process.env.AGENT_HEARTBEAT_INTERVAL_MS || '10000', 10);
|
|
233
|
+
|
|
234
|
+
function _stopAgentHeartbeat() {
|
|
235
|
+
if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = null; }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function _startAgentHeartbeat() {
|
|
239
|
+
_stopAgentHeartbeat();
|
|
240
|
+
heartbeatTimer = setInterval(() => {
|
|
241
|
+
if (ws.readyState !== 1 /* OPEN */) return; // server handles reconnect/close
|
|
242
|
+
try {
|
|
243
|
+
ws.send(JSON.stringify({ type: 'heartbeat' }));
|
|
244
|
+
} catch {}
|
|
245
|
+
try { ws.ping(); } catch {}
|
|
246
|
+
}, HEARTBEAT_INTERVAL_MS);
|
|
247
|
+
// Do not let the heartbeat timer keep the process alive on its own.
|
|
248
|
+
if (typeof heartbeatTimer.unref === 'function') heartbeatTimer.unref();
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
_startAgentHeartbeat();
|
|
252
|
+
ws.on('close', _stopAgentHeartbeat);
|
|
253
|
+
|
|
167
254
|
ws.on('message', (data, isBinary) => {
|
|
168
255
|
if (isBinary) return;
|
|
169
256
|
|
|
@@ -237,6 +324,26 @@ function setupSessionHandler(ws, opts) {
|
|
|
237
324
|
return;
|
|
238
325
|
}
|
|
239
326
|
|
|
327
|
+
// Reconnect reconciliation: the server asks for the exact-profile liveness
|
|
328
|
+
// verdict for a stale lease this device owns (recovery probe). This lets a
|
|
329
|
+
// restarted agent process resolve its own stale recovery_required lease
|
|
330
|
+
// WITHOUT the lost in-memory token — the reply is nonce-bound and carries
|
|
331
|
+
// only the liveness verdict (never a token).
|
|
332
|
+
if (msg.type === 'recovery-probe') {
|
|
333
|
+
try {
|
|
334
|
+
const verdict = _recoveryVerdict(msg, opts);
|
|
335
|
+
ws.send(JSON.stringify({
|
|
336
|
+
type: 'recovery-probe-response',
|
|
337
|
+
probeId: msg.probeId,
|
|
338
|
+
nonce: msg.nonce,
|
|
339
|
+
accountUuid: msg.accountUuid,
|
|
340
|
+
leaseId: msg.leaseId || null,
|
|
341
|
+
verdict,
|
|
342
|
+
}));
|
|
343
|
+
} catch {}
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
|
|
240
347
|
// session-status ack: the server confirms a stop was verified. No-op here
|
|
241
348
|
// beyond acknowledging; the lease stays under server authority.
|
|
242
349
|
if (msg.type === 'session-status') {
|
|
@@ -312,12 +419,12 @@ async function _executeCommand(type, params, msg, opts, ws) {
|
|
|
312
419
|
|
|
313
420
|
switch (type) {
|
|
314
421
|
case 'startSession':
|
|
315
|
-
return _startSession(params, opts, accountId, accountUuid, lease);
|
|
422
|
+
return _startSession(params, opts, accountId, accountUuid, lease, ws);
|
|
316
423
|
case 'stopSession':
|
|
317
|
-
return _stopSession(accountId, lease);
|
|
424
|
+
return _stopSession(accountId, lease, ws);
|
|
318
425
|
case 'restartSession':
|
|
319
|
-
await _stopSession(accountId, lease);
|
|
320
|
-
return _startSession(params, opts, accountId, accountUuid, lease);
|
|
426
|
+
await _stopSession(accountId, lease, ws);
|
|
427
|
+
return _startSession(params, opts, accountId, accountUuid, lease, ws);
|
|
321
428
|
case 'refreshSession':
|
|
322
429
|
return _refreshSession(accountId);
|
|
323
430
|
case 'navigate':
|
|
@@ -347,20 +454,109 @@ async function _executeCommand(type, params, msg, opts, ws) {
|
|
|
347
454
|
|
|
348
455
|
// ── Session management (reuses existing hardened modules) ───────────────────
|
|
349
456
|
|
|
350
|
-
async function _startSession(params, opts, accountId, accountUuid, lease) {
|
|
457
|
+
async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
|
|
351
458
|
if (!accountId) return { success: false, error: 'Missing accountId' };
|
|
352
459
|
|
|
460
|
+
// Lease-bound error reporter: a FAILED start sends a lease-bound
|
|
461
|
+
// session-status 'error' so the server releases the lease it acquired for
|
|
462
|
+
// this attempt (parity with the hardened v1 runtime). Without it the lease
|
|
463
|
+
// stays 'acquiring' and blocks the account until it expires.
|
|
464
|
+
const _sendStartError = (error) => {
|
|
465
|
+
if (!ws || !lease) return;
|
|
466
|
+
try {
|
|
467
|
+
const tmp = {};
|
|
468
|
+
leaseClient.bind(tmp, lease);
|
|
469
|
+
ws.send(JSON.stringify(leaseClient.boundStatusMessage(tmp, accountId, 'error', { error })));
|
|
470
|
+
} catch {}
|
|
471
|
+
};
|
|
472
|
+
|
|
353
473
|
const deviceMeta = opts.deviceMeta;
|
|
474
|
+
// Phase 14 / schema-4: the profile identity requires ALL FOUR UUIDs
|
|
475
|
+
// (server/tenant/account/device). The command's options carry the
|
|
476
|
+
// server-assigned serverUuid + tenantUuid; the device UUID comes from this
|
|
477
|
+
// device's metadata. Without all four, resolveProfileDir throws
|
|
478
|
+
// PROFILE_IDENTITY_INCOMPLETE and no browser can ever launch.
|
|
479
|
+
const identity = params.options || params;
|
|
480
|
+
const serverUuid = identity.serverUuid || null;
|
|
481
|
+
const tenantUuid = identity.tenantUuid || null;
|
|
482
|
+
const resolvedAccountUuid = identity.accountUuid || accountUuid || null;
|
|
483
|
+
|
|
484
|
+
// Fail closed with a clear, actionable error if the server did not send the
|
|
485
|
+
// complete immutable tuple (a profile is never opened with a partial
|
|
486
|
+
// identity).
|
|
487
|
+
if (!serverUuid || !tenantUuid || !resolvedAccountUuid || !deviceMeta.deviceId) {
|
|
488
|
+
_sendStartError('PROFILE_IDENTITY_INCOMPLETE');
|
|
489
|
+
return {
|
|
490
|
+
success: false,
|
|
491
|
+
error: 'PROFILE_IDENTITY_INCOMPLETE: the server did not provide the full profile identity (serverUuid/tenantUuid/accountUuid). Cannot open a browser profile.',
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
|
|
354
495
|
const profileDir = resolveProfileDir({
|
|
355
|
-
|
|
496
|
+
profilesDir: PROFILES_DIR,
|
|
497
|
+
serverUuid,
|
|
498
|
+
tenantUuid,
|
|
499
|
+
accountUuid: resolvedAccountUuid,
|
|
356
500
|
deviceUuid: deviceMeta.deviceId,
|
|
357
|
-
|
|
358
|
-
});
|
|
501
|
+
}).dir;
|
|
359
502
|
|
|
360
503
|
const fs = require('fs');
|
|
361
504
|
if (!fs.existsSync(profileDir)) fs.mkdirSync(profileDir, { recursive: true });
|
|
362
505
|
|
|
363
|
-
|
|
506
|
+
// fingerprintStore.loadOrGenerate takes an OBJECT ({ profileDir, accountId,
|
|
507
|
+
// options, generator }) — matching the hardened v1 runtime call. The
|
|
508
|
+
// positional form threw "paths[0] must be of type string" and aborted every
|
|
509
|
+
// launch. Live operator options (mobileView/locale/userAgent/timezone) are
|
|
510
|
+
// re-applied on every launch; the randomized hardware identity is persisted
|
|
511
|
+
// inside the profile dir and stays stable across launches.
|
|
512
|
+
const launchOpts = params.options || {};
|
|
513
|
+
const fingerprint = fingerprintStore.loadOrGenerate({
|
|
514
|
+
profileDir,
|
|
515
|
+
accountId: String(accountId),
|
|
516
|
+
options: {
|
|
517
|
+
mobileView: launchOpts.mobileView || false,
|
|
518
|
+
locale: launchOpts.locale || null,
|
|
519
|
+
userAgent: launchOpts.userAgent || null,
|
|
520
|
+
timezone: launchOpts.timezone || null,
|
|
521
|
+
},
|
|
522
|
+
generator: generateFingerprint,
|
|
523
|
+
});
|
|
524
|
+
|
|
525
|
+
// ── Phase 16 fail-closed proxy policy (parity with the hardened v1 runtime) ──
|
|
526
|
+
// A missing/unknown networkMode ABORTS; no proxy + proxy_required ABORTS
|
|
527
|
+
// (never silently open a direct browser that leaks the real IP); a configured
|
|
528
|
+
// proxy must be reachable AND egress from a different IP (isolation), or the
|
|
529
|
+
// launch aborts. We never fall open to direct.
|
|
530
|
+
const proxyStr = launchOpts.proxy || null;
|
|
531
|
+
const networkMode = launchOpts.networkMode || null;
|
|
532
|
+
|
|
533
|
+
// Health-check the proxy only when one was configured. verifyProxyIsolation
|
|
534
|
+
// does the full fail-closed verification (CONNECT + TLS + GET through the
|
|
535
|
+
// proxy, plus an independent direct public-IP fetch and comparison) — a
|
|
536
|
+
// superset of the v1 TCP pre-check. A proxy that accepts TCP but egresses
|
|
537
|
+
// from the device's own IP (transparent/misconfigured) is refused.
|
|
538
|
+
let health = null;
|
|
539
|
+
if (proxyStr) {
|
|
540
|
+
const parsedProxy = _parseProxy(proxyStr);
|
|
541
|
+
if (!parsedProxy) {
|
|
542
|
+
health = { ok: false, reason: 'proxy_unreachable', code: 'PROXY_MALFORMED' };
|
|
543
|
+
} else {
|
|
544
|
+
const isolation = await require('./proxyEgress').verifyProxyIsolation(parsedProxy, {}).catch(() => ({ ok: false, code: 'PROXY_ISOLATION_ERROR' }));
|
|
545
|
+
health = isolation && isolation.ok
|
|
546
|
+
? { ok: true, reason: 'proxy_ok', egressIp: isolation.egressIp, directIp: isolation.directIp }
|
|
547
|
+
: { ok: false, reason: 'proxy_isolation_failed: ' + ((isolation && (isolation.code || isolation.reason)) || 'unknown'), code: isolation && isolation.code };
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
const decision = require('./proxyPolicy').decideProxyLaunch({
|
|
552
|
+
proxyStr,
|
|
553
|
+
networkMode,
|
|
554
|
+
health,
|
|
555
|
+
});
|
|
556
|
+
if (decision.action === 'abort') {
|
|
557
|
+
_sendStartError(decision.error);
|
|
558
|
+
return { success: false, error: decision.error, code: decision.reason.toUpperCase() };
|
|
559
|
+
}
|
|
364
560
|
|
|
365
561
|
const args = [
|
|
366
562
|
'--disable-blink-features=AutomationControlled',
|
|
@@ -384,8 +580,8 @@ async function _startSession(params, opts, accountId, accountUuid, lease) {
|
|
|
384
580
|
noDefaultViewport: true,
|
|
385
581
|
};
|
|
386
582
|
|
|
387
|
-
if (
|
|
388
|
-
const proxyUrl = _parseProxy(
|
|
583
|
+
if (decision.useProxy && proxyStr) {
|
|
584
|
+
const proxyUrl = _parseProxy(proxyStr);
|
|
389
585
|
if (proxyUrl) launchOptions.proxy = proxyUrl;
|
|
390
586
|
}
|
|
391
587
|
|
|
@@ -393,13 +589,17 @@ async function _startSession(params, opts, accountId, accountUuid, lease) {
|
|
|
393
589
|
try {
|
|
394
590
|
context = await chromium.launchPersistentContext(profileDir, launchOptions);
|
|
395
591
|
} catch (err) {
|
|
592
|
+
_sendStartError(_safeError(err));
|
|
396
593
|
return { success: false, error: _safeError(err) };
|
|
397
594
|
}
|
|
398
595
|
|
|
399
596
|
await context.addInitScript(buildStealthScript(fingerprint));
|
|
400
597
|
|
|
401
|
-
|
|
402
|
-
|
|
598
|
+
// The server sends cookies in options (options.cookies); accept the flat
|
|
599
|
+
// params form too for robustness.
|
|
600
|
+
const cookiesToInject = launchOpts.cookies || params.cookies;
|
|
601
|
+
if (cookiesToInject && Array.isArray(cookiesToInject)) {
|
|
602
|
+
try { await context.addCookies(cookiesToInject); } catch {}
|
|
403
603
|
}
|
|
404
604
|
|
|
405
605
|
const pages = context.pages();
|
|
@@ -455,6 +655,27 @@ async function _startSession(params, opts, accountId, accountUuid, lease) {
|
|
|
455
655
|
if (lease) leaseClient.bind(session, lease);
|
|
456
656
|
activeSessions.set(accountId, session);
|
|
457
657
|
|
|
658
|
+
// ── Lease-bound session-status reporting (Phase 3 parity with v1) ──────────
|
|
659
|
+
// The server's session cache (`agent.sessions`) and the durable lease TTL
|
|
660
|
+
// are ONLY updated by lease-bound `session-status` frames — never by the
|
|
661
|
+
// command-response alone. Without this frame the server reports the session
|
|
662
|
+
// 'stopped' even though the local browser is running, and the lease never
|
|
663
|
+
// activates. The credential (leaseId + leaseToken) is echoed so the server
|
|
664
|
+
// can verify the holder; it is never logged, never persisted to disk.
|
|
665
|
+
const _sendStatus = (status, extra) => {
|
|
666
|
+
try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(session, accountId, status, extra))); } catch {}
|
|
667
|
+
};
|
|
668
|
+
_sendStatus('running');
|
|
669
|
+
|
|
670
|
+
// A browser context closed outside our control (user closed the window,
|
|
671
|
+
// crash): report the verified stop so the server releases the lease — a
|
|
672
|
+
// dead local browser must not keep the account locked.
|
|
673
|
+
context.on('close', () => {
|
|
674
|
+
const closed = activeSessions.get(accountId);
|
|
675
|
+
if (closed === session) activeSessions.delete(accountId);
|
|
676
|
+
try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(closed || session, accountId, 'stopped'))); } catch {}
|
|
677
|
+
});
|
|
678
|
+
|
|
458
679
|
// Return confirmed success metadata. The backend/frontend uses this to
|
|
459
680
|
// show a green toast ONLY when the browser is genuinely started and visible.
|
|
460
681
|
//
|
|
@@ -492,11 +713,16 @@ async function _startSession(params, opts, accountId, accountUuid, lease) {
|
|
|
492
713
|
};
|
|
493
714
|
}
|
|
494
715
|
|
|
495
|
-
async function _stopSession(accountId, lease) {
|
|
716
|
+
async function _stopSession(accountId, lease, ws) {
|
|
496
717
|
const session = activeSessions.get(accountId);
|
|
497
718
|
if (!session) return { success: false, error: 'Session not found' };
|
|
498
719
|
try { await session.context.close(); } catch {}
|
|
499
720
|
activeSessions.delete(accountId);
|
|
721
|
+
// Lease-bound stop ack: the server verifies the credential and releases the
|
|
722
|
+
// durable lease. This is the only thing that completes a takeover.
|
|
723
|
+
if (ws) {
|
|
724
|
+
try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(session, accountId, 'stopped'))); } catch {}
|
|
725
|
+
}
|
|
500
726
|
return { success: true, accountId, stopped: true };
|
|
501
727
|
}
|
|
502
728
|
|
|
@@ -575,6 +801,35 @@ function _discoverLegacyProfiles() {
|
|
|
575
801
|
|
|
576
802
|
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
577
803
|
|
|
804
|
+
/**
|
|
805
|
+
* Compute the exact-profile liveness verdict for a recovery probe. Resolves the
|
|
806
|
+
* EXACT profile dir from the server-supplied immutable identity tuple (using the
|
|
807
|
+
* same hardened profile-path logic as launch) and matches it against live Chrome
|
|
808
|
+
* command lines. Returns 'running' | 'stopped' | 'unknown' (fail closed to
|
|
809
|
+
* 'unknown' whenever the profile cannot be resolved or inspected).
|
|
810
|
+
*/
|
|
811
|
+
function _recoveryVerdict(msg, opts) {
|
|
812
|
+
const deviceMeta = (opts && opts.deviceMeta) || {};
|
|
813
|
+
const accountUuid = msg.accountUuid || null;
|
|
814
|
+
const serverUuid = msg.serverUuid || null;
|
|
815
|
+
const tenantUuid = msg.tenantUuid || null;
|
|
816
|
+
const deviceUuid = msg.deviceUuid || deviceMeta.deviceId || null;
|
|
817
|
+
if (!accountUuid || !serverUuid || !tenantUuid || !deviceUuid) return 'unknown';
|
|
818
|
+
let dir;
|
|
819
|
+
try {
|
|
820
|
+
dir = resolveProfileDir({
|
|
821
|
+
profilesDir: PROFILES_DIR,
|
|
822
|
+
serverUuid,
|
|
823
|
+
tenantUuid,
|
|
824
|
+
accountUuid,
|
|
825
|
+
deviceUuid,
|
|
826
|
+
}).dir;
|
|
827
|
+
} catch {
|
|
828
|
+
return 'unknown';
|
|
829
|
+
}
|
|
830
|
+
return _detectProfileChromeRunning(dir);
|
|
831
|
+
}
|
|
832
|
+
|
|
578
833
|
function _extractEcho(msg) {
|
|
579
834
|
const echo = {};
|
|
580
835
|
if (msg.nonce) echo.nonce = msg.nonce;
|
|
@@ -616,4 +871,4 @@ function _safeError(err) {
|
|
|
616
871
|
.slice(0, 500);
|
|
617
872
|
}
|
|
618
873
|
|
|
619
|
-
module.exports = { setupSessionHandler, activeSessions, closeAllSessions, markDisconnected };
|
|
874
|
+
module.exports = { setupSessionHandler, activeSessions, closeAllSessions, markDisconnected, _detectProfileChromeRunning, _recoveryVerdict, _setChromeLinesProvider };
|