@xkwdstore/agent 2.0.5 → 2.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -6
- package/package.json +1 -1
- package/src/actions/comment.js +153 -138
- package/src/actions/confirmation.js +129 -0
- package/src/actions/follow.js +179 -83
- package/src/actions/tweet.js +107 -91
- package/src/cli.js +6 -1
- package/src/enrollmentClient.js +43 -2
- package/src/sessionHandler.js +304 -581
package/src/sessionHandler.js
CHANGED
|
@@ -28,34 +28,6 @@ const { buildStealthScript } = require('./stealth');
|
|
|
28
28
|
const leaseClient = require('./leaseClient');
|
|
29
29
|
const { PROFILES_DIR } = require('./deviceKeyStore');
|
|
30
30
|
|
|
31
|
-
// ── Browser-lifecycle diagnostics ────────────────────────────────────────────
|
|
32
|
-
//
|
|
33
|
-
// A browser session that ends by itself previously left NO local trace: the
|
|
34
|
-
// only signal was the lease being released server-side, so "who closed this
|
|
35
|
-
// browser?" could not be answered from the agent. Every path that can end a
|
|
36
|
-
// session now emits one line with a CAUSE CODE. Records only the cause code,
|
|
37
|
-
// the account id and a monotonic timestamp — never cookie/token/credential
|
|
38
|
-
// values and never the profile directory contents.
|
|
39
|
-
//
|
|
40
|
-
// START_SESSION a session was created and registered
|
|
41
|
-
// STOP_COMMAND an explicit stopSession command closed it
|
|
42
|
-
// STOP_NOT_FOUND a stopSession command arrived with no active session
|
|
43
|
-
// STOP_CLOSE_FAILED a stopSession command could NOT confirm the close
|
|
44
|
-
// (fail-closed: no 'stopped' frame was sent, the session
|
|
45
|
-
// stays registered, the lease stays blocking/recoverable)
|
|
46
|
-
// CONTEXT_CLOSE the Playwright context closed (any cause)
|
|
47
|
-
// CONTEXT_CLOSE_DUP a second close event for an already-removed session
|
|
48
|
-
// PAGE_CLOSE a page closed
|
|
49
|
-
// PAGE_CRASH a page crashed
|
|
50
|
-
// BROWSER_DISCONNECTED the underlying browser disconnected
|
|
51
|
-
// CLOSE_ALL_SESSIONS closeAllSessions() ran (agent shutdown / WS loss)
|
|
52
|
-
function _logLifecycle(cause, accountId, extra) {
|
|
53
|
-
try {
|
|
54
|
-
const detail = extra ? ' ' + JSON.stringify(extra) : '';
|
|
55
|
-
process.stderr.write(`[session-lifecycle] ${new Date().toISOString()} ${cause} account=${accountId}${detail}\n`);
|
|
56
|
-
} catch {}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
31
|
// ── Exact-profile Chrome detection (recovery probe) ──────────────────────────
|
|
60
32
|
//
|
|
61
33
|
// "activeSessions is empty" is NOT proof a browser stopped: an agent-process
|
|
@@ -89,12 +61,6 @@ function _chromeCommandLines() {
|
|
|
89
61
|
let _chromeLinesProvider = _chromeCommandLines;
|
|
90
62
|
function _setChromeLinesProvider(fn) { _chromeLinesProvider = typeof fn === 'function' ? fn : _chromeCommandLines; }
|
|
91
63
|
|
|
92
|
-
// Test-only injectable window-probe provider: tests inject synthetic probe
|
|
93
|
-
// output lines so the multi-process selection + visibility verdict are provable
|
|
94
|
-
// without spawning a real Windows session.
|
|
95
|
-
let _windowProbeProvider = null;
|
|
96
|
-
function _setWindowProbeProvider(fn) { _windowProbeProvider = typeof fn === 'function' ? fn : null; }
|
|
97
|
-
|
|
98
64
|
/**
|
|
99
65
|
* Return 'running' | 'stopped' | 'unknown' for whether a Chrome process still
|
|
100
66
|
* owns the EXACT profile directory. Fails closed to 'unknown' on any error.
|
|
@@ -118,68 +84,29 @@ function _detectProfileChromeRunning(profileDir) {
|
|
|
118
84
|
}
|
|
119
85
|
}
|
|
120
86
|
|
|
121
|
-
// ── Windows
|
|
87
|
+
// ── Windows foreground helper ────────────────────────────────────────────────
|
|
122
88
|
//
|
|
123
89
|
// page.bringToFront() may be insufficient on real Windows to actually bring
|
|
124
90
|
// the browser window to the foreground (Windows foreground lock rules).
|
|
125
|
-
// This helper uses a narrow, safe PowerShell command to
|
|
126
|
-
// Chrome window associated with this session's persistent profile directory
|
|
127
|
-
// un-minimize it, attempt to activate it, and REPORT what it actually observed.
|
|
128
|
-
//
|
|
129
|
-
// Two defects are fixed here (both produced a FALSE `visible: false`):
|
|
130
|
-
//
|
|
131
|
-
// (a) FIRST-MATCH PROCESS SELECTION. The previous script stopped at the
|
|
132
|
-
// FIRST chrome.exe whose command line contained the profile dir
|
|
133
|
-
// (`$target = $p; break`). Chromium is a multi-process tree — one root
|
|
134
|
-
// browser process plus renderer / gpu-process / utility / crashpad-handler
|
|
135
|
-
// children — and EVERY child carries the same `--user-data-dir`.
|
|
136
|
-
// Verified on the real Windows host: 10 processes matched the profile and
|
|
137
|
-
// 9 of them reported `MainWindowHandle = 0`; ONLY the root browser process
|
|
138
|
-
// owns a window. Whether the old code succeeded was therefore decided by
|
|
139
|
-
// CIM enumeration order rather than by window truth.
|
|
140
|
-
//
|
|
141
|
-
// (b) SetForegroundWindow AS THE VISIBILITY VERDICT. The old code derived
|
|
142
|
-
// `visible` from SetForegroundWindow()'s BOOL return value. That API is
|
|
143
|
-
// subject to the Windows foreground lock: it returns FALSE whenever the
|
|
144
|
-
// current foreground process refuses to yield, even though the Chrome
|
|
145
|
-
// window is genuinely present, un-minimized and on screen. The dashboard's
|
|
146
|
-
// `started === true && visible === true` gate then reported "did not
|
|
147
|
-
// appear visibly" for a browser that WAS visible.
|
|
148
|
-
//
|
|
149
|
-
// The fix separates the two questions:
|
|
150
|
-
// * PRESENCE/VISIBILITY — what `visible` now means: a real, non-minimized
|
|
151
|
-
// top-level window exists for THIS profile. Proven with IsWindowVisible()
|
|
152
|
-
// plus a sane window rect. A refused foreground switch no longer makes a
|
|
153
|
-
// genuinely visible browser report as invisible.
|
|
154
|
-
// * FOCUS — still best effort and still attempted (un-minimize via
|
|
155
|
-
// ShowWindowAsync SW_RESTORE, then SetForegroundWindow), but reported
|
|
156
|
-
// separately as `focused` instead of being conflated with visibility.
|
|
91
|
+
// This helper uses a narrow, safe PowerShell command to activate the EXACT
|
|
92
|
+
// Chrome window associated with this session's persistent profile directory.
|
|
157
93
|
//
|
|
158
|
-
// Safety requirements
|
|
94
|
+
// Safety requirements:
|
|
159
95
|
// - uses the fixed System32 PowerShell 5.1 path (no PATH-based resolution)
|
|
160
96
|
// - uses execFileSync argument arrays (no shell:true, no command interpolation)
|
|
161
97
|
// - profileDir is passed via STDIN (never in command arguments)
|
|
162
|
-
// -
|
|
98
|
+
// - targets ONLY the Chrome process whose command line contains the exact
|
|
163
99
|
// profileDir (not "most recent Chrome" globally)
|
|
164
|
-
// - scans EVERY match but only ever selects a process that actually owns a
|
|
165
|
-
// window; it never guesses or fabricates a handle
|
|
166
100
|
// - does NOT kill or focus unrelated windows
|
|
167
|
-
// - Add-Type is defined BEFORE
|
|
101
|
+
// - Add-Type is defined BEFORE calling SetForegroundWindow (ordering fix)
|
|
102
|
+
// - returns true only if the intended window was identified and foregrounded
|
|
168
103
|
//
|
|
169
104
|
// @param {string} profileDir — the persistent profile directory for this session
|
|
170
|
-
// @returns {
|
|
105
|
+
// @returns {boolean} true if the window was identified and foregrounded
|
|
171
106
|
|
|
172
|
-
function
|
|
173
|
-
|
|
174
|
-
if (
|
|
175
|
-
return { visible: true, focused: true, pid: null, hwnd: 0, reason: 'non_windows' };
|
|
176
|
-
}
|
|
177
|
-
if (!profileDir) {
|
|
178
|
-
return { visible: false, focused: false, pid: null, hwnd: 0, reason: 'no_profile' };
|
|
179
|
-
}
|
|
180
|
-
if (typeof _windowProbeProvider === 'function') {
|
|
181
|
-
return _parseWindowProbe(_windowProbeProvider(profileDir));
|
|
182
|
-
}
|
|
107
|
+
function _windowsForegroundChrome(profileDir) {
|
|
108
|
+
if (os.platform() !== 'win32') return true; // non-Windows: no-op success
|
|
109
|
+
if (!profileDir) return false;
|
|
183
110
|
try {
|
|
184
111
|
const nodePath = require('path');
|
|
185
112
|
const { execFileSync } = require('child_process');
|
|
@@ -188,179 +115,65 @@ function _windowsWindowState(profileDir) {
|
|
|
188
115
|
|
|
189
116
|
// Fixed PowerShell script — NO user data interpolation.
|
|
190
117
|
// The profileDir is passed via STDIN and read by the script.
|
|
191
|
-
// Add-Type is defined BEFORE any
|
|
192
|
-
//
|
|
193
|
-
//
|
|
194
|
-
//
|
|
195
|
-
//
|
|
196
|
-
//
|
|
197
|
-
//
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
"$
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
"if (
|
|
219
|
-
"$procs = Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\";",
|
|
220
|
-
'$matched = @();',
|
|
221
|
-
'foreach ($p in $procs) {',
|
|
222
|
-
' if ($p.CommandLine -and ($p.CommandLine -like "*$profileDir*")) { $matched += $p }',
|
|
223
|
-
'};',
|
|
224
|
-
"if ($matched.Count -eq 0) { Write-Output 'no_process|False|'; exit 0 };",
|
|
225
|
-
// Observation pass: describe EVERY candidate, including windowless
|
|
226
|
-
// children (hasWindow=0). Nothing here short-circuits.
|
|
227
|
-
'$rows = @();',
|
|
228
|
-
'foreach ($p in $matched) {',
|
|
229
|
-
' $cand = Get-Process -Id $p.ProcessId;',
|
|
230
|
-
' $isRoot = 0;',
|
|
231
|
-
' if ($p.CommandLine -and ($p.CommandLine -notmatch "--type=")) { $isRoot = 1 };',
|
|
232
|
-
' $hnd = [IntPtr]::Zero;',
|
|
233
|
-
' if ($cand -and $cand.MainWindowHandle) { $hnd = $cand.MainWindowHandle };',
|
|
234
|
-
' $hasWin = 0; $shown = $false; $iconic = $false; $w = 0; $h = 0;',
|
|
235
|
-
' if ($hnd -ne [IntPtr]::Zero) {',
|
|
236
|
-
' $hasWin = 1;',
|
|
237
|
-
' $shown = [bool][Win32.Native]::IsWindowVisible($hnd);',
|
|
238
|
-
' $iconic = [bool][Win32.Native]::IsIconic($hnd);',
|
|
239
|
-
' $r = New-Object Win32.Native+RECT;',
|
|
240
|
-
' if ([Win32.Native]::GetWindowRect($hnd, [ref]$r)) { $w = $r.Right - $r.Left; $h = $r.Bottom - $r.Top };',
|
|
241
|
-
' };',
|
|
242
|
-
" $rows += ('{0}:{1}:{2}:{3}:{4}:{5}:{6}:{7}' -f $p.ProcessId, $hasWin, $isRoot, [int64]$hnd, $shown, $iconic, $w, $h)",
|
|
243
|
-
'};',
|
|
244
|
-
// Focus pass: target the root browser process that owns a window, else
|
|
245
|
-
// any window owner. Best effort — the result is reported, never treated
|
|
246
|
-
// as proof of visibility.
|
|
247
|
-
'$pick = $null;',
|
|
248
|
-
'foreach ($row in $rows) { $f = $row.Split(":"); if ($f[1] -eq "1" -and $f[2] -eq "1") { $pick = $f[3]; break } };',
|
|
249
|
-
'if (-not $pick) { foreach ($row in $rows) { $f = $row.Split(":"); if ($f[1] -eq "1") { $pick = $f[3]; break } } };',
|
|
250
|
-
'$focused = $false;',
|
|
251
|
-
'if ($pick -and $pick -ne "0") {',
|
|
252
|
-
' $h2 = [IntPtr][int64]$pick;',
|
|
253
|
-
' if ([Win32.Native]::IsIconic($h2)) { [void][Win32.Native]::ShowWindowAsync($h2, 9) };',
|
|
254
|
-
' [void][Win32.Native]::SetForegroundWindow($h2);',
|
|
255
|
-
' Start-Sleep -Milliseconds 150;',
|
|
256
|
-
' $focused = [bool]([Win32.Native]::GetForegroundWindow() -eq $h2)',
|
|
257
|
-
'};',
|
|
258
|
-
"Write-Output ('candidates|' + $focused + '|' + ($rows -join ';'))",
|
|
259
|
-
].join(' ');
|
|
118
|
+
// Add-Type is defined BEFORE any call to SetForegroundWindow.
|
|
119
|
+
// The script:
|
|
120
|
+
// 1. Reads the profileDir from stdin
|
|
121
|
+
// 2. Finds chrome.exe processes whose command line contains that exact path
|
|
122
|
+
// 3. Gets the MainWindowHandle of that specific process
|
|
123
|
+
// 4. Uses SetForegroundWindow + ShowWindowAsync to restore+foreground it
|
|
124
|
+
// 5. Outputs "OK" or "FAIL" so the caller knows whether it worked
|
|
125
|
+
const script =
|
|
126
|
+
"$ErrorActionPreference='Stop'; " +
|
|
127
|
+
"Add-Type -Namespace Win32 -Name Native -MemberDefinition '" +
|
|
128
|
+
"[DllImport(\"user32.dll\")] public static extern bool SetForegroundWindow(IntPtr hWnd); " +
|
|
129
|
+
"[DllImport(\"user32.dll\")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); " +
|
|
130
|
+
"[DllImport(\"user32.dll\")] public static extern bool IsIconic(IntPtr hWnd); " +
|
|
131
|
+
"'; " +
|
|
132
|
+
"$profileDir = [Console]::In.ReadToEnd().Trim(); " +
|
|
133
|
+
"if (-not $profileDir) { Write-Output 'FAIL:no_profile'; exit 0 }; " +
|
|
134
|
+
"$procs = Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\" -ErrorAction SilentlyContinue; " +
|
|
135
|
+
"$target = $null; " +
|
|
136
|
+
"foreach ($p in $procs) { " +
|
|
137
|
+
" if ($p.CommandLine -and ($p.CommandLine -like \"*$profileDir*\")) { $target = $p; break } " +
|
|
138
|
+
"}; " +
|
|
139
|
+
"if (-not $target) { Write-Output 'FAIL:no_process'; exit 0 }; " +
|
|
140
|
+
"$proc = Get-Process -Id $target.ProcessId -ErrorAction SilentlyContinue; " +
|
|
141
|
+
"if (-not $proc -or $proc.MainWindowHandle -eq [IntPtr]::Zero) { Write-Output 'FAIL:no_window'; exit 0 }; " +
|
|
142
|
+
"$handle = $proc.MainWindowHandle; " +
|
|
143
|
+
"if ([Win32.Native]::IsIconic($handle)) { [void][Win32.Native]::ShowWindowAsync($handle, 9) }; " +
|
|
144
|
+
"$result = [Win32.Native]::SetForegroundWindow($handle); " +
|
|
145
|
+
"if ($result) { Write-Output 'OK' } else { Write-Output 'FAIL:foreground' }";
|
|
260
146
|
|
|
261
147
|
const output = execFileSync(psExe, ['-NoProfile', '-NonInteractive', '-Command', script], {
|
|
262
148
|
windowsHide: true,
|
|
263
149
|
encoding: 'utf8',
|
|
264
|
-
|
|
265
|
-
// `visible:false`: Add-Type compiles C#, then Get-CimInstance reads the
|
|
266
|
-
// command line of every chrome.exe (a Chromium tree is 40+ processes).
|
|
267
|
-
// A timeout aborted the probe and the bare `catch` turned it into
|
|
268
|
-
// "not visible". The budget is now generous and a timeout is reported
|
|
269
|
-
// explicitly instead of being indistinguishable from a missing window.
|
|
270
|
-
timeout: 20000,
|
|
150
|
+
timeout: 5000,
|
|
271
151
|
input: profileDir, // profileDir via STDIN — never in command arguments
|
|
272
152
|
}).trim();
|
|
273
153
|
|
|
274
|
-
return
|
|
275
|
-
} catch
|
|
276
|
-
//
|
|
277
|
-
|
|
278
|
-
return { visible: false, focused: false, pid: null, hwnd: 0, reason };
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
/**
|
|
283
|
-
* Select WHICH candidate process owns the browser window.
|
|
284
|
-
*
|
|
285
|
-
* A Chromium tree attaches the same `--user-data-dir` to every child process,
|
|
286
|
-
* but only the ROOT browser process owns a top-level window — verified on the
|
|
287
|
-
* real Windows host: of 10 processes matching one profile, 9 reported
|
|
288
|
-
* MainWindowHandle = 0. Selection rule:
|
|
289
|
-
*
|
|
290
|
-
* 1. a ROOT process (no `--type=`) that owns a window — the real browser
|
|
291
|
-
* 2. otherwise any process that owns a window — defensive fallback
|
|
292
|
-
* 3. otherwise nothing — never fabricate a window
|
|
293
|
-
*
|
|
294
|
-
* A windowless child is NEVER selected and never stops the scan.
|
|
295
|
-
*
|
|
296
|
-
* @param {Array<{pid:number,hasWindow:boolean,isRoot:boolean,hwnd:number,shown:boolean,iconic:boolean,w:number,h:number}>} candidates
|
|
297
|
-
* @returns {object|null} the selected candidate, or null when none owns a window
|
|
298
|
-
*/
|
|
299
|
-
function _selectWindowOwner(candidates) {
|
|
300
|
-
if (!Array.isArray(candidates) || candidates.length === 0) return null;
|
|
301
|
-
const withWindow = candidates.filter((c) => c && c.hasWindow && c.hwnd);
|
|
302
|
-
if (withWindow.length === 0) return null;
|
|
303
|
-
return withWindow.find((c) => c.isRoot) || withWindow[0];
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
/**
|
|
307
|
-
* Parse the `|`-delimited window-probe output into a structured verdict.
|
|
308
|
-
*
|
|
309
|
-
* The ONE rule that matters: a window that EXISTS and is SHOWN is visible.
|
|
310
|
-
* SetForegroundWindow's refusal (the Windows foreground lock) is a FOCUS
|
|
311
|
-
* outcome and must never be reported as "the browser is not visible".
|
|
312
|
-
*
|
|
313
|
-
* @param {string} output — raw probe line (or injected test fixture)
|
|
314
|
-
* @returns {{visible:boolean, focused:boolean, pid:number|null, hwnd:number, reason:string}}
|
|
315
|
-
*/
|
|
316
|
-
function _parseWindowProbe(output) {
|
|
317
|
-
const parts = String(output == null ? '' : output).trim().split('|');
|
|
318
|
-
const status = parts[0];
|
|
319
|
-
|
|
320
|
-
if (status !== 'candidates') {
|
|
321
|
-
// Transport-level outcome: no profile, no matching process, timeout, etc.
|
|
322
|
-
return { visible: false, focused: false, pid: null, hwnd: 0, reason: status || 'probe_failed' };
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
const focused = parts[1] === 'True';
|
|
326
|
-
const raw = parts[2] || '';
|
|
327
|
-
const candidates = raw
|
|
328
|
-
.split(';')
|
|
329
|
-
.filter(Boolean)
|
|
330
|
-
.map((row) => {
|
|
331
|
-
const f = row.split(':');
|
|
332
|
-
return {
|
|
333
|
-
pid: parseInt(f[0], 10),
|
|
334
|
-
hasWindow: f[1] === '1',
|
|
335
|
-
isRoot: f[2] === '1',
|
|
336
|
-
hwnd: parseInt(f[3], 10) || 0,
|
|
337
|
-
shown: f[4] === 'True',
|
|
338
|
-
iconic: f[5] === 'True',
|
|
339
|
-
w: parseInt(f[6], 10) || 0,
|
|
340
|
-
h: parseInt(f[7], 10) || 0,
|
|
341
|
-
};
|
|
342
|
-
});
|
|
343
|
-
|
|
344
|
-
const owner = _selectWindowOwner(candidates);
|
|
345
|
-
if (!owner) {
|
|
346
|
-
// Processes matched but none owns a window: a real "not visible" finding.
|
|
347
|
-
return { visible: false, focused, pid: null, hwnd: 0, reason: 'no_window' };
|
|
154
|
+
return output === 'OK';
|
|
155
|
+
} catch {
|
|
156
|
+
// Foreground helper failed — return false so visible is not claimed
|
|
157
|
+
return false;
|
|
348
158
|
}
|
|
349
|
-
|
|
350
|
-
// A real window: shown, not minimized, with a sane on-screen rect.
|
|
351
|
-
const hasRealWindow = owner.hwnd !== 0 && owner.shown && !owner.iconic && owner.w >= 100 && owner.h >= 100;
|
|
352
|
-
return {
|
|
353
|
-
visible: hasRealWindow,
|
|
354
|
-
focused,
|
|
355
|
-
pid: Number.isFinite(owner.pid) ? owner.pid : null,
|
|
356
|
-
hwnd: owner.hwnd,
|
|
357
|
-
reason: hasRealWindow ? 'window_visible' : 'window_not_visible',
|
|
358
|
-
};
|
|
359
159
|
}
|
|
360
160
|
|
|
361
161
|
// Active sessions: accountId -> { context, page, profileDir }
|
|
362
162
|
const activeSessions = new Map();
|
|
363
163
|
|
|
164
|
+
// Accounts currently LAUNCHING on this agent (String(accountId)).
|
|
165
|
+
//
|
|
166
|
+
// WHY: a startSession must never create a SECOND persistent Chrome context for
|
|
167
|
+
// the same profile dir. Two overlapping /start requests for one account (e.g. a
|
|
168
|
+
// retry fired while a slow launch is still in flight) would otherwise both pass
|
|
169
|
+
// the "no active session yet" check and race `launchPersistentContext` on the
|
|
170
|
+
// same profile — producing a profile-lock error for one of them, or two windows
|
|
171
|
+
// where only one is lease-bound. The server serializes start attempts per
|
|
172
|
+
// (account, device) in browserProviderFactory, but that guard is per-process
|
|
173
|
+
// state on the server and does not cover two distinct server-side attempts
|
|
174
|
+
// reaching the agent; the invariant belongs on the device that owns the profile.
|
|
175
|
+
const _startInProgress = new Set();
|
|
176
|
+
|
|
364
177
|
// Per-runtime state (B4 fix): each setupSessionHandler call creates a fresh
|
|
365
178
|
// runtime object so a newly initialized handler starts connected and does
|
|
366
179
|
// NOT inherit stale state from a prior handler lifecycle. The module-level
|
|
@@ -396,10 +209,6 @@ async function closeAllSessions() {
|
|
|
396
209
|
if (!session) continue;
|
|
397
210
|
// Delete BEFORE closing so a concurrent call does not double-close.
|
|
398
211
|
sessions.delete(accountId);
|
|
399
|
-
// Deliberate close: the context close listener must not send its own
|
|
400
|
-
// 'stopped' frame for an agent-initiated shutdown.
|
|
401
|
-
session.stopping = true;
|
|
402
|
-
_logLifecycle('CLOSE_ALL_SESSIONS', accountId);
|
|
403
212
|
try {
|
|
404
213
|
if (session.context) await session.context.close().catch(() => {});
|
|
405
214
|
} catch {}
|
|
@@ -582,6 +391,22 @@ async function _handleCommandEnvelope(ws, msg, opts) {
|
|
|
582
391
|
|
|
583
392
|
const { type, ...rest } = command;
|
|
584
393
|
|
|
394
|
+
// CONTRACT: `options` must ALWAYS be a real object on the params we hand to
|
|
395
|
+
// the executors. It is the ONLY carrier of the immutable profile-identity
|
|
396
|
+
// tuple (serverUuid/tenantUuid/accountUuid/deviceUuid) and of the proxy
|
|
397
|
+
// policy, so a command that simply OMITS `options` must not silently degrade
|
|
398
|
+
// into "no options at all". Previously the executors fell back to the params
|
|
399
|
+
// object itself (`params.options || params`), and because `rest` spreads the
|
|
400
|
+
// command MINUS `type`, that fallback object can never contain serverUuid —
|
|
401
|
+
// so such a command failed closed with PROFILE_IDENTITY_INCOMPLETE and no
|
|
402
|
+
// browser ever opened, with no diagnostic pointing at the envelope. Making the
|
|
403
|
+
// shape unconditional keeps every executor's contract identical and makes the
|
|
404
|
+
// failure explicit instead of accidental. Identity is still validated
|
|
405
|
+
// downstream and NEVER defaulted here.
|
|
406
|
+
if (!rest.options || typeof rest.options !== 'object' || Array.isArray(rest.options)) {
|
|
407
|
+
rest.options = {};
|
|
408
|
+
}
|
|
409
|
+
|
|
585
410
|
// Build the echo object from the envelope (nonce, leaseId, accountUuid).
|
|
586
411
|
const echo = _extractEcho(msg);
|
|
587
412
|
|
|
@@ -646,7 +471,11 @@ async function _executeCommand(type, params, msg, opts, ws) {
|
|
|
646
471
|
case 'runAction':
|
|
647
472
|
return _runAction(accountId, params.action, params.payload || params.args);
|
|
648
473
|
case 'getStatus':
|
|
649
|
-
|
|
474
|
+
// Account-scoped status contract (parity with the hardened index.js path).
|
|
475
|
+
// Job readiness on the server uses getSessionStatus (registry), but any
|
|
476
|
+
// caller of the getStatus command must receive a truthful per-account
|
|
477
|
+
// { status:'running'|'stopped' } — never a bare sessions list.
|
|
478
|
+
return _getStatus(accountId);
|
|
650
479
|
case 'importLegacyProfile':
|
|
651
480
|
return _importLegacyProfile(accountId, accountUuid, opts);
|
|
652
481
|
case 'discoverLegacyProfiles':
|
|
@@ -660,6 +489,7 @@ async function _executeCommand(type, params, msg, opts, ws) {
|
|
|
660
489
|
|
|
661
490
|
async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
|
|
662
491
|
if (!accountId) return { success: false, error: 'Missing accountId' };
|
|
492
|
+
const accountKey = String(accountId);
|
|
663
493
|
|
|
664
494
|
// Lease-bound error reporter: a FAILED start sends a lease-bound
|
|
665
495
|
// session-status 'error' so the server releases the lease it acquired for
|
|
@@ -674,46 +504,144 @@ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
|
|
|
674
504
|
} catch {}
|
|
675
505
|
};
|
|
676
506
|
|
|
507
|
+
// ── ONE launch per account/profile ─────────────────────────────────────────
|
|
508
|
+
// A launch is already in flight for this account → refuse a SECOND concurrent
|
|
509
|
+
// launch (no duplicate context, no profile-lock race). Placed BEFORE any
|
|
510
|
+
// identity work because it mutates nothing and can answer immediately; the
|
|
511
|
+
// "already running" case below is checked AFTER the identity contract so a
|
|
512
|
+
// malformed envelope still fails closed.
|
|
513
|
+
//
|
|
514
|
+
// CRITICAL: do NOT emit a lease-bound `session-status: error` here. The server
|
|
515
|
+
// treats a verified lease-bound error frame as a STOP ACK and RELEASES the
|
|
516
|
+
// durable lease — but two server-side start attempts for one account SHARE a
|
|
517
|
+
// single reservation (same leaseId + credential, by design). Releasing on this
|
|
518
|
+
// refusal would free the reservation the FIRST, still-launching attempt owns;
|
|
519
|
+
// that attempt then positively starts a browser whose lease can no longer be
|
|
520
|
+
// activated, which is exactly the SESSION_START_LEASE_LOST inconsistency. The
|
|
521
|
+
// refusal is reported ONLY through the command response, leaving the durable
|
|
522
|
+
// lease to the attempt that owns it (its own failure path releases it, under
|
|
523
|
+
// the server's lifecycle-ownership guard).
|
|
524
|
+
if (_startInProgress.has(accountKey)) {
|
|
525
|
+
return {
|
|
526
|
+
success: false,
|
|
527
|
+
code: 'START_ALREADY_IN_PROGRESS',
|
|
528
|
+
error: 'A browser launch for this account is already in progress on this device; a second launch was not started.',
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
_startInProgress.add(accountKey);
|
|
532
|
+
try {
|
|
533
|
+
return await _startSessionLocked(params, opts, accountKey, accountId, accountUuid, lease, ws);
|
|
534
|
+
} finally {
|
|
535
|
+
_startInProgress.delete(accountKey);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* The actual launch. Called only while this account holds the per-agent launch
|
|
541
|
+
* guard (see _startSession), so exactly one persistent context can be created
|
|
542
|
+
* for the account/profile at a time.
|
|
543
|
+
*/
|
|
544
|
+
async function _startSessionLocked(params, opts, accountKey, accountId, accountUuid, lease, ws) {
|
|
545
|
+
// Lease-bound error reporter (see _startSession).
|
|
546
|
+
const _sendStartError = (error) => {
|
|
547
|
+
if (!ws || !lease) return;
|
|
548
|
+
try {
|
|
549
|
+
const tmp = {};
|
|
550
|
+
leaseClient.bind(tmp, lease);
|
|
551
|
+
ws.send(JSON.stringify(leaseClient.boundStatusMessage(tmp, accountId, 'error', { error })));
|
|
552
|
+
} catch {}
|
|
553
|
+
};
|
|
554
|
+
|
|
677
555
|
const deviceMeta = opts.deviceMeta;
|
|
678
556
|
// Phase 14 / schema-4: the profile identity requires ALL FOUR UUIDs
|
|
679
557
|
// (server/tenant/account/device). The command's options carry the
|
|
680
558
|
// server-assigned serverUuid + tenantUuid; the device UUID comes from this
|
|
681
559
|
// device's metadata. Without all four, resolveProfileDir throws
|
|
682
560
|
// PROFILE_IDENTITY_INCOMPLETE and no browser can ever launch.
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
561
|
+
//
|
|
562
|
+
// The identity is read from `params.options` ONLY (the envelope guarantees it
|
|
563
|
+
// is an object). The previous `|| params` fallback was a silent trap: `params`
|
|
564
|
+
// spreads the command MINUS `type`, so it can never hold serverUuid, and a
|
|
565
|
+
// command missing `options` therefore failed closed with an error that pointed
|
|
566
|
+
// at the identity instead of at the malformed envelope. There is still NO
|
|
567
|
+
// identity fallback: absent UUIDs fail closed exactly as before.
|
|
568
|
+
const launchParams = (params.options && typeof params.options === 'object') ? params.options : {};
|
|
569
|
+
const serverUuid = launchParams.serverUuid || null;
|
|
570
|
+
const tenantUuid = launchParams.tenantUuid || null;
|
|
571
|
+
const resolvedAccountUuid = launchParams.accountUuid || accountUuid || null;
|
|
687
572
|
|
|
688
573
|
// Fail closed with a clear, actionable error if the server did not send the
|
|
689
574
|
// complete immutable tuple (a profile is never opened with a partial
|
|
690
|
-
// identity).
|
|
575
|
+
// identity). The error carries the TYPED code so the server/UI can classify it
|
|
576
|
+
// as an identity-contract failure (never as a lease conflict).
|
|
691
577
|
if (!serverUuid || !tenantUuid || !resolvedAccountUuid || !deviceMeta.deviceId) {
|
|
692
578
|
_sendStartError('PROFILE_IDENTITY_INCOMPLETE');
|
|
693
579
|
return {
|
|
694
580
|
success: false,
|
|
581
|
+
code: 'PROFILE_IDENTITY_INCOMPLETE',
|
|
695
582
|
error: 'PROFILE_IDENTITY_INCOMPLETE: the server did not provide the full profile identity (serverUuid/tenantUuid/accountUuid). Cannot open a browser profile.',
|
|
696
583
|
};
|
|
697
584
|
}
|
|
698
585
|
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
586
|
+
// Phase 14 / schema-4: resolve the device-bound profile slot. The resolver is
|
|
587
|
+
// FAIL-CLOSED and also enforces UUID SHAPE, path containment, marker integrity
|
|
588
|
+
// and quarantine — so its rejection must be classified as an identity problem
|
|
589
|
+
// too. Previously the raw throw escaped to the generic error handler, so a
|
|
590
|
+
// malformed UUID surfaced as a bare message with no typed code and the server
|
|
591
|
+
// could not tell it apart from an ordinary failure.
|
|
592
|
+
let profileDir;
|
|
593
|
+
try {
|
|
594
|
+
profileDir = resolveProfileDir({
|
|
595
|
+
profilesDir: PROFILES_DIR,
|
|
596
|
+
serverUuid,
|
|
597
|
+
tenantUuid,
|
|
598
|
+
accountUuid: resolvedAccountUuid,
|
|
599
|
+
deviceUuid: deviceMeta.deviceId,
|
|
600
|
+
}).dir;
|
|
601
|
+
} catch (err) {
|
|
602
|
+
const isIdentity = err && err.code === 'PROFILE_IDENTITY_INCOMPLETE';
|
|
603
|
+
if (!isIdentity) throw err; // containment/marker/quarantine failures keep their own handling
|
|
604
|
+
_sendStartError('PROFILE_IDENTITY_INCOMPLETE');
|
|
605
|
+
return {
|
|
606
|
+
success: false,
|
|
607
|
+
code: 'PROFILE_IDENTITY_INCOMPLETE',
|
|
608
|
+
error: `PROFILE_IDENTITY_INCOMPLETE: ${(_safeError(err))}`,
|
|
609
|
+
};
|
|
610
|
+
}
|
|
707
611
|
const fs = require('fs');
|
|
708
612
|
if (!fs.existsSync(profileDir)) fs.mkdirSync(profileDir, { recursive: true });
|
|
709
613
|
|
|
614
|
+
// ── Already RUNNING for this exact account/profile → adopt, do not relaunch ─
|
|
615
|
+
// A second `launchPersistentContext` on the same profile dir cannot succeed
|
|
616
|
+
// (Chrome locks it) and would race the live window. The identity contract has
|
|
617
|
+
// been satisfied above, so this is a well-formed start for a profile that is
|
|
618
|
+
// ALREADY open: report the live session truthfully and REBIND it to the lease
|
|
619
|
+
// this start carries, so every subsequent command/status for the account is
|
|
620
|
+
// verified against the CURRENT authoritative credential rather than a stale
|
|
621
|
+
// in-memory one from a previous reservation.
|
|
622
|
+
const existingSession = activeSessions.get(accountKey);
|
|
623
|
+
if (existingSession && existingSession.context) {
|
|
624
|
+
if (lease) leaseClient.bind(existingSession, lease);
|
|
625
|
+
// (The in-flight guard is released by _startSession's finally on return.)
|
|
626
|
+
try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(existingSession, accountId, 'running'))); } catch {}
|
|
627
|
+
return {
|
|
628
|
+
success: true,
|
|
629
|
+
accountId,
|
|
630
|
+
started: true,
|
|
631
|
+
visible: true,
|
|
632
|
+
sessionId: accountKey,
|
|
633
|
+
alreadyRunning: true,
|
|
634
|
+
status: 'running',
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
|
|
710
638
|
// fingerprintStore.loadOrGenerate takes an OBJECT ({ profileDir, accountId,
|
|
711
639
|
// options, generator }) — matching the hardened v1 runtime call. The
|
|
712
640
|
// positional form threw "paths[0] must be of type string" and aborted every
|
|
713
641
|
// launch. Live operator options (mobileView/locale/userAgent/timezone) are
|
|
714
642
|
// re-applied on every launch; the randomized hardware identity is persisted
|
|
715
643
|
// inside the profile dir and stays stable across launches.
|
|
716
|
-
const launchOpts =
|
|
644
|
+
const launchOpts = launchParams;
|
|
717
645
|
const fingerprint = fingerprintStore.loadOrGenerate({
|
|
718
646
|
profileDir,
|
|
719
647
|
accountId: String(accountId),
|
|
@@ -800,13 +728,11 @@ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
|
|
|
800
728
|
await context.addInitScript(buildStealthScript(fingerprint));
|
|
801
729
|
|
|
802
730
|
// The server sends cookies in options (options.cookies); accept the flat
|
|
803
|
-
// params form too for robustness.
|
|
804
|
-
// cookie array, so it MUST be normalized before injection — the previous
|
|
805
|
-
// `Array.isArray()` guard silently dropped every string payload and left the
|
|
806
|
-
// browser unauthenticated. Injection happens BEFORE the first navigation so
|
|
807
|
-
// the initial request already carries the account session.
|
|
731
|
+
// params form too for robustness.
|
|
808
732
|
const cookiesToInject = launchOpts.cookies || params.cookies;
|
|
809
|
-
|
|
733
|
+
if (cookiesToInject && Array.isArray(cookiesToInject)) {
|
|
734
|
+
try { await context.addCookies(cookiesToInject); } catch {}
|
|
735
|
+
}
|
|
810
736
|
|
|
811
737
|
const pages = context.pages();
|
|
812
738
|
const page = pages[0] || await context.newPage();
|
|
@@ -838,15 +764,14 @@ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
|
|
|
838
764
|
};
|
|
839
765
|
}
|
|
840
766
|
|
|
841
|
-
// Windows-specific
|
|
842
|
-
//
|
|
843
|
-
//
|
|
844
|
-
//
|
|
845
|
-
//
|
|
846
|
-
|
|
847
|
-
let windowState = { visible: bringToFrontOk, focused: bringToFrontOk, pid: null, hwnd: 0, reason: 'not_probed' };
|
|
767
|
+
// Windows-specific foreground: page.bringToFront() alone may not overcome
|
|
768
|
+
// the Windows foreground lock. This helper targets the EXACT Chrome process
|
|
769
|
+
// whose command line contains this session's profileDir (passed via stdin,
|
|
770
|
+
// not interpolated). It returns true ONLY if the intended window was
|
|
771
|
+
// identified and successfully foregrounded.
|
|
772
|
+
let foregroundVerified = false;
|
|
848
773
|
if (bringToFrontOk) {
|
|
849
|
-
|
|
774
|
+
foregroundVerified = _windowsForegroundChrome(profileDir);
|
|
850
775
|
}
|
|
851
776
|
|
|
852
777
|
// Re-check after focus: the page may have closed in the meantime.
|
|
@@ -858,10 +783,9 @@ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
|
|
|
858
783
|
};
|
|
859
784
|
}
|
|
860
785
|
|
|
861
|
-
const session = { context, page, profileDir, accountId, lease: null
|
|
786
|
+
const session = { context, page, profileDir, accountId: accountKey, lease: null };
|
|
862
787
|
if (lease) leaseClient.bind(session, lease);
|
|
863
|
-
activeSessions.set(
|
|
864
|
-
_logLifecycle('START_SESSION', accountId, { visible: windowState.visible, focused: windowState.focused, reason: windowState.reason });
|
|
788
|
+
activeSessions.set(accountKey, session);
|
|
865
789
|
|
|
866
790
|
// ── Lease-bound session-status reporting (Phase 3 parity with v1) ──────────
|
|
867
791
|
// The server's session cache (`agent.sessions`) and the durable lease TTL
|
|
@@ -877,41 +801,10 @@ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
|
|
|
877
801
|
|
|
878
802
|
// A browser context closed outside our control (user closed the window,
|
|
879
803
|
// crash): report the verified stop so the server releases the lease — a
|
|
880
|
-
// dead local browser must not keep the account locked.
|
|
881
|
-
//
|
|
882
|
-
//
|
|
883
|
-
|
|
884
|
-
// and two identical lease-bound stops for one stop were a duplicate.
|
|
885
|
-
context.on('close', () => {
|
|
886
|
-
const closed = activeSessions.get(accountId);
|
|
887
|
-
if (session.stopping) {
|
|
888
|
-
_logLifecycle('CONTEXT_CLOSE', accountId, { duplicate: true, reason: 'command_initiated' });
|
|
889
|
-
return;
|
|
890
|
-
}
|
|
891
|
-
if (closed !== session) {
|
|
892
|
-
// The session was already replaced/removed — never report a stop for a
|
|
893
|
-
// session that is no longer the active one.
|
|
894
|
-
_logLifecycle('CONTEXT_CLOSE_DUP', accountId);
|
|
895
|
-
return;
|
|
896
|
-
}
|
|
897
|
-
_logLifecycle('CONTEXT_CLOSE', accountId);
|
|
898
|
-
activeSessions.delete(accountId);
|
|
899
|
-
try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(closed || session, accountId, 'stopped'))); } catch {}
|
|
900
|
-
});
|
|
901
|
-
|
|
902
|
-
// Page-level causes: a closed/crashed page is the leading hypothesis for a
|
|
903
|
-
// browser that appears to quit on its own (closing the LAST page ends a
|
|
904
|
-
// persistent context). Recorded so the next occurrence is identifiable.
|
|
905
|
-
try {
|
|
906
|
-
page.on('close', () => _logLifecycle('PAGE_CLOSE', accountId, { pagesLeft: context.pages().length }));
|
|
907
|
-
page.on('crash', () => _logLifecycle('PAGE_CRASH', accountId));
|
|
908
|
-
} catch {}
|
|
909
|
-
try {
|
|
910
|
-
const browser = typeof context.browser === 'function' ? context.browser() : null;
|
|
911
|
-
if (browser && typeof browser.on === 'function') {
|
|
912
|
-
browser.on('disconnected', () => _logLifecycle('BROWSER_DISCONNECTED', accountId));
|
|
913
|
-
}
|
|
914
|
-
} catch {}
|
|
804
|
+
// dead local browser must not keep the account locked. Wired through the
|
|
805
|
+
// shared reporter so the API stop and the context close collapse to ONE
|
|
806
|
+
// authoritative report per session.
|
|
807
|
+
_attachContextCloseReporter(context, session, accountKey, accountId, ws);
|
|
915
808
|
|
|
916
809
|
// Return confirmed success metadata. The backend/frontend uses this to
|
|
917
810
|
// show a green toast ONLY when the browser is genuinely started and visible.
|
|
@@ -920,147 +813,170 @@ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
|
|
|
920
813
|
// - launchPersistentContext succeeded
|
|
921
814
|
// - page exists and is not closed
|
|
922
815
|
// - page.bringToFront() succeeded
|
|
923
|
-
// - on Windows:
|
|
924
|
-
//
|
|
925
|
-
//
|
|
926
|
-
// reporting it as visible:false was the false negative fixed here.
|
|
927
|
-
// (on non-Windows: bringToFront is sufficient)
|
|
816
|
+
// - on Windows: the intended Chrome process was identified and
|
|
817
|
+
// SetForegroundWindow succeeded (or on non-Windows: bringToFront is
|
|
818
|
+
// sufficient)
|
|
928
819
|
//
|
|
929
|
-
// If
|
|
820
|
+
// If the Windows foreground helper cannot prove the window is visible
|
|
821
|
+
// (foregroundVerified = false), we return started:true but visible:false
|
|
930
822
|
// with an actionable error so the frontend does NOT show a green toast.
|
|
931
|
-
if (os.platform() === 'win32' && !
|
|
932
|
-
// The browser launched and bringToFront succeeded, but we could not
|
|
933
|
-
//
|
|
934
|
-
// — NOT a green toast.
|
|
823
|
+
if (os.platform() === 'win32' && !foregroundVerified) {
|
|
824
|
+
// The browser launched and bringToFront succeeded, but we could not
|
|
825
|
+
// positively verify the window is in the foreground. Return a safe
|
|
826
|
+
// actionable message — NOT a green toast.
|
|
935
827
|
return {
|
|
936
828
|
success: true,
|
|
937
829
|
accountId,
|
|
938
830
|
started: true,
|
|
939
831
|
visible: false,
|
|
940
832
|
sessionId: accountId,
|
|
941
|
-
|
|
942
|
-
error: 'Browser launched but no visible window could be confirmed. Check the taskbar for the Chrome window.',
|
|
943
|
-
cookieDiagnostics: cookieDiag,
|
|
833
|
+
error: 'Browser launched but could not be confirmed in the foreground. Check the taskbar for the Chrome window.',
|
|
944
834
|
};
|
|
945
835
|
}
|
|
946
836
|
|
|
947
|
-
// The window is proven present. `focused` is reported for diagnostics only —
|
|
948
|
-
// a window that exists on screen is visible whether or not it holds focus.
|
|
949
837
|
return {
|
|
950
838
|
success: true,
|
|
951
839
|
accountId,
|
|
952
840
|
started: true,
|
|
953
841
|
visible: true,
|
|
954
842
|
sessionId: accountId,
|
|
955
|
-
cookieDiagnostics: cookieDiag,
|
|
956
843
|
};
|
|
957
844
|
}
|
|
958
845
|
|
|
846
|
+
/**
|
|
847
|
+
* Wire the single authoritative stop reporter onto a browser context.
|
|
848
|
+
*
|
|
849
|
+
* A context 'close' happens for a manual Chrome X close, a crash, and for the
|
|
850
|
+
* context.close() issued by _stopSession. This listener is the ONLY report path
|
|
851
|
+
* for those events; _stopSession also calls _reportStoppedOnce directly so an
|
|
852
|
+
* API close reports even if no 'close' event arrives. Both converge on the same
|
|
853
|
+
* idempotent reporter, so one stop is always exactly one frame.
|
|
854
|
+
*
|
|
855
|
+
* The slot-ownership check is what makes a LATE frame safe: if the account was
|
|
856
|
+
* closed and reopened, the old context must not report a stop carrying the NEW
|
|
857
|
+
* session's credential (that would release a lease still protecting a live
|
|
858
|
+
* browser).
|
|
859
|
+
*/
|
|
860
|
+
function _attachContextCloseReporter(context, session, accountKey, accountId, ws) {
|
|
861
|
+
context.on('close', () => {
|
|
862
|
+
const closed = activeSessions.get(accountKey);
|
|
863
|
+
if (closed && closed !== session) return;
|
|
864
|
+
if (closed === session) activeSessions.delete(accountKey);
|
|
865
|
+
_reportStoppedOnce(session, accountId, ws);
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
/**
|
|
870
|
+
* Report ONE verified, lease-bound `stopped` frame for a session.
|
|
871
|
+
*
|
|
872
|
+
* Both stop paths converge here: the context's own 'close' event (a manual
|
|
873
|
+
* Chrome X close, a crash, or the context.close() issued by _stopSession) and
|
|
874
|
+
* the explicit API stop. Without this guard the API path emitted TWO frames for
|
|
875
|
+
* one stop (the close event plus the explicit send), doubling the lifecycle
|
|
876
|
+
* event — and a late duplicate could land AFTER the account was reopened and
|
|
877
|
+
* release the NEW lease that protects a running browser.
|
|
878
|
+
*
|
|
879
|
+
* The credential is whatever the session was bound to at launch; the server
|
|
880
|
+
* verifies it in constant time and releases only the matching durable lease.
|
|
881
|
+
* Idempotent by construction: the flag lives on the session object itself, so a
|
|
882
|
+
* NEW session for the same account is never suppressed by a previous stop.
|
|
883
|
+
*/
|
|
884
|
+
function _reportStoppedOnce(session, accountId, ws) {
|
|
885
|
+
if (!session || session._stopReported) return false;
|
|
886
|
+
session._stopReported = true;
|
|
887
|
+
try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(session, accountId, 'stopped'))); } catch {}
|
|
888
|
+
return true;
|
|
889
|
+
}
|
|
890
|
+
|
|
959
891
|
async function _stopSession(accountId, lease, ws) {
|
|
960
|
-
|
|
892
|
+
// Account keys are stored as String(accountId) — normalize every lookup so a
|
|
893
|
+
// number/string mismatch can never make a LIVE session invisible (which would
|
|
894
|
+
// make a stop silently no-op and leave the browser running past its lease).
|
|
895
|
+
const accountKey = String(accountId);
|
|
896
|
+
const session = activeSessions.get(accountKey);
|
|
961
897
|
if (!session) return { success: false, error: 'Session not found' };
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
// identical lease-bound stops for one stop command (a duplicate ack the
|
|
965
|
-
// server had to absorb). The explicit ack below is now the single one.
|
|
966
|
-
session.stopping = true;
|
|
967
|
-
_logLifecycle('STOP_COMMAND', accountId);
|
|
968
|
-
|
|
969
|
-
// ── FAIL-CLOSED stop ───────────────────────────────────────────────────────
|
|
970
|
-
// A lease-bound `status: 'stopped'` means, and must ONLY ever mean, that the
|
|
971
|
-
// local browser context close was POSITIVELY CONFIRMED. The previous shape
|
|
972
|
-
// swallowed a close failure (`catch {}`) and then sent `stopped` anyway, so a
|
|
973
|
-
// failed close could make the backend release the durable lease while the
|
|
974
|
-
// browser was still alive — fail-OPEN, and the account could then be acquired
|
|
975
|
-
// by another device while two live browsers existed for it.
|
|
976
|
-
//
|
|
977
|
-
// Now: if the close cannot be confirmed we send NO stopped frame, keep the
|
|
978
|
-
// session registered, and report an explicit failure. The lease stays
|
|
979
|
-
// blocking/recoverable (a human/operator or recovery path resolves it), which
|
|
980
|
-
// is strictly safer than claiming a stop we did not observe.
|
|
981
|
-
try {
|
|
982
|
-
await session.context.close();
|
|
983
|
-
} catch {
|
|
984
|
-
// Close was NOT confirmed. Revert the deliberate-close marking so a later
|
|
985
|
-
// real context close (user closes the window, crash, browser disconnect) is
|
|
986
|
-
// reported normally by the context close listener instead of being
|
|
987
|
-
// suppressed as a duplicate.
|
|
988
|
-
session.stopping = false;
|
|
989
|
-
// NEVER delete an entry here. If this session is still the registered one it
|
|
990
|
-
// must stay (it may still be live — never erase evidence). If the map has
|
|
991
|
-
// been REPLACED by a newer session for this account, that replacement must
|
|
992
|
-
// not be evicted either. A failed close therefore touches no map state.
|
|
993
|
-
_logLifecycle('STOP_CLOSE_FAILED', accountId);
|
|
994
|
-
// Safe, generic failure: no credentials, no token, no raw driver text.
|
|
995
|
-
return { success: false, accountId, error: 'Browser close could not be confirmed' };
|
|
996
|
-
}
|
|
997
|
-
|
|
998
|
-
// Only after a confirmed close.
|
|
999
|
-
if (activeSessions.get(accountId) === session) activeSessions.delete(accountId);
|
|
898
|
+
try { await session.context.close(); } catch {}
|
|
899
|
+
activeSessions.delete(accountKey);
|
|
1000
900
|
// Lease-bound stop ack: the server verifies the credential and releases the
|
|
1001
901
|
// durable lease. This is the only thing that completes a takeover.
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
902
|
+
//
|
|
903
|
+
// EXACTLY ONE logically effective stop report per session. `context.close()`
|
|
904
|
+
// fires the context's own 'close' handler above, and this path used to send a
|
|
905
|
+
// SECOND stopped frame. Both carry the same credential, and the server's
|
|
906
|
+
// `releaseLeaseByNumericId` is idempotent for an already-released lease — but
|
|
907
|
+
// two frames are two lifecycle events for one stop (and, ordered against a
|
|
908
|
+
// reopen, the late duplicate would hit the NEW lease). `_reportStoppedOnce`
|
|
909
|
+
// makes the pair collapse to exactly one authoritative report while keeping
|
|
910
|
+
// BOTH paths intact: a manual Chrome X close (handler above) and an API close
|
|
911
|
+
// both still report their stop.
|
|
912
|
+
if (ws) _reportStoppedOnce(session, accountId, ws);
|
|
1005
913
|
return { success: true, accountId, stopped: true };
|
|
1006
914
|
}
|
|
1007
915
|
|
|
1008
916
|
async function _refreshSession(accountId) {
|
|
1009
|
-
const session = activeSessions.get(accountId);
|
|
917
|
+
const session = activeSessions.get(String(accountId));
|
|
1010
918
|
if (!session) return { success: false, error: 'Session not found' };
|
|
1011
919
|
await session.page.reload();
|
|
1012
920
|
return { success: true };
|
|
1013
921
|
}
|
|
1014
922
|
|
|
1015
923
|
async function _navigate(accountId, url) {
|
|
1016
|
-
const session = activeSessions.get(accountId);
|
|
924
|
+
const session = activeSessions.get(String(accountId));
|
|
1017
925
|
if (!session) return { success: false, error: 'Session not found' };
|
|
1018
926
|
await session.page.goto(url, { waitUntil: 'domcontentloaded' });
|
|
1019
927
|
return { success: true };
|
|
1020
928
|
}
|
|
1021
929
|
|
|
1022
930
|
async function _typeText(accountId, selector, text) {
|
|
1023
|
-
const session = activeSessions.get(accountId);
|
|
931
|
+
const session = activeSessions.get(String(accountId));
|
|
1024
932
|
if (!session) return { success: false, error: 'Session not found' };
|
|
1025
933
|
await session.page.locator(selector).fill(text);
|
|
1026
934
|
return { success: true };
|
|
1027
935
|
}
|
|
1028
936
|
|
|
1029
937
|
async function _pressKey(accountId, key) {
|
|
1030
|
-
const session = activeSessions.get(accountId);
|
|
938
|
+
const session = activeSessions.get(String(accountId));
|
|
1031
939
|
if (!session) return { success: false, error: 'Session not found' };
|
|
1032
940
|
await session.page.keyboard.press(key);
|
|
1033
941
|
return { success: true };
|
|
1034
942
|
}
|
|
1035
943
|
|
|
1036
944
|
async function _click(accountId, selector) {
|
|
1037
|
-
const session = activeSessions.get(accountId);
|
|
945
|
+
const session = activeSessions.get(String(accountId));
|
|
1038
946
|
if (!session) return { success: false, error: 'Session not found' };
|
|
1039
947
|
await session.page.locator(selector).click();
|
|
1040
948
|
return { success: true };
|
|
1041
949
|
}
|
|
1042
950
|
|
|
1043
951
|
async function _focusSession(accountId) {
|
|
1044
|
-
const session = activeSessions.get(accountId);
|
|
952
|
+
const session = activeSessions.get(String(accountId));
|
|
1045
953
|
if (!session) return { success: false, error: 'Session not found' };
|
|
1046
954
|
await session.page.bringToFront();
|
|
1047
955
|
return { success: true };
|
|
1048
956
|
}
|
|
1049
957
|
|
|
1050
958
|
async function _runAction(accountId, action, payload) {
|
|
1051
|
-
const session = activeSessions.get(accountId);
|
|
959
|
+
const session = activeSessions.get(String(accountId));
|
|
1052
960
|
if (!session) return { success: false, error: 'Session not found' };
|
|
1053
961
|
const { runAction } = require('./actions');
|
|
1054
|
-
|
|
1055
|
-
|
|
962
|
+
// Return the ACTION result at the TOP level. The server places this value in
|
|
963
|
+
// the command-response `result` field and reads success/code/outcome/
|
|
964
|
+
// failureStage there (JobRuntime, browserProviderFactory, browser.js). Wrapping
|
|
965
|
+
// it as { success: true, result } made a RETURNED typed failure (notably the
|
|
966
|
+
// non-idempotent tweet/comment/follow UNKNOWN_OUTCOME) look like a clean
|
|
967
|
+
// success, because the outer `success` shadowed the inner one. Do NOT re-wrap.
|
|
968
|
+
return await runAction(session.page, action, payload || {});
|
|
1056
969
|
}
|
|
1057
970
|
|
|
1058
|
-
function _getStatus() {
|
|
1059
|
-
const
|
|
1060
|
-
|
|
1061
|
-
|
|
971
|
+
function _getStatus(accountId) {
|
|
972
|
+
const key = String(accountId || '');
|
|
973
|
+
const session = key ? activeSessions.get(key) : null;
|
|
974
|
+
if (session && session.context) {
|
|
975
|
+
let url = null;
|
|
976
|
+
try { url = session.page && !session.page.isClosed() ? session.page.url() : null; } catch { url = null; }
|
|
977
|
+
return { success: true, status: 'running', accountId: key, url };
|
|
1062
978
|
}
|
|
1063
|
-
return { success: true,
|
|
979
|
+
return { success: true, status: 'stopped', accountId: key || null, url: null };
|
|
1064
980
|
}
|
|
1065
981
|
|
|
1066
982
|
function _importLegacyProfile(accountId, accountUuid, opts) {
|
|
@@ -1078,199 +994,6 @@ function _discoverLegacyProfiles() {
|
|
|
1078
994
|
return { success: true, profiles };
|
|
1079
995
|
}
|
|
1080
996
|
|
|
1081
|
-
// ── Account cookie restoration ───────────────────────────────────────────────
|
|
1082
|
-
//
|
|
1083
|
-
// The backend stores an account's cookies as the JSON TEXT of a Playwright
|
|
1084
|
-
// cookie array (accounts.db.json `cookies`) and forwards that value verbatim in
|
|
1085
|
-
// the startSession command options — so it arrives here as a STRING.
|
|
1086
|
-
//
|
|
1087
|
-
// The original hardened runtime (index.js) parsed BOTH shapes: a JSON string
|
|
1088
|
-
// (with a base64-wrapped fallback) and an already-parsed array. This runtime
|
|
1089
|
-
// only accepted an array (`Array.isArray`) and swallowed everything else in a
|
|
1090
|
-
// bare `catch {}`, so every string payload was dropped silently: the browser
|
|
1091
|
-
// opened with no account session at all (X saw an anonymous visitor even though
|
|
1092
|
-
// auth_token/ct0/twid were present in the account record). Restoring the
|
|
1093
|
-
// hardened runtime's normalization makes both runtimes accept the same
|
|
1094
|
-
// payloads.
|
|
1095
|
-
//
|
|
1096
|
-
// Payloads are normalized EXACTLY as stored — domain, sameSite and every other
|
|
1097
|
-
// stored field are never rewritten; only fields Playwright requires are filled
|
|
1098
|
-
// in when absent. Injection happens BEFORE the first navigation so the very
|
|
1099
|
-
// first request is already authenticated.
|
|
1100
|
-
|
|
1101
|
-
/**
|
|
1102
|
-
* Canonicalize a sameSite value. Returns 'Strict' | 'Lax' | 'None' when the
|
|
1103
|
-
* value is recognized (case-insensitively), otherwise null so the caller can
|
|
1104
|
-
* OMIT it. Returning 'None' for an unknown value would silently relax the
|
|
1105
|
-
* cookie's cross-site posture AND is rejected by Playwright, whose `sameSite`
|
|
1106
|
-
* is an optional enum of exactly those three values.
|
|
1107
|
-
*/
|
|
1108
|
-
function _canonSameSite(value) {
|
|
1109
|
-
if (value == null) return null;
|
|
1110
|
-
switch (String(value).trim().toLowerCase()) {
|
|
1111
|
-
case 'strict': return 'Strict';
|
|
1112
|
-
case 'lax': return 'Lax';
|
|
1113
|
-
case 'none': return 'None';
|
|
1114
|
-
default: return null;
|
|
1115
|
-
}
|
|
1116
|
-
}
|
|
1117
|
-
|
|
1118
|
-
// Playwright: only -1 or a positive unix timestamp up to this bound is allowed.
|
|
1119
|
-
const MAX_COOKIE_EXPIRES_SECONDS = 253402300799;
|
|
1120
|
-
|
|
1121
|
-
/** Playwright's expires constraint: -1, or a positive value within its bound. */
|
|
1122
|
-
function _validExpires(value) {
|
|
1123
|
-
if (value == null || value === '') return null;
|
|
1124
|
-
const n = Number(value);
|
|
1125
|
-
if (!Number.isFinite(n)) return null;
|
|
1126
|
-
if (n === -1) return -1;
|
|
1127
|
-
if (n <= 0 || n > MAX_COOKIE_EXPIRES_SECONDS) return null;
|
|
1128
|
-
return n;
|
|
1129
|
-
}
|
|
1130
|
-
|
|
1131
|
-
/** A `url` scope Playwright will accept (not about:blank, not a data: URL). */
|
|
1132
|
-
function _usableUrl(value) {
|
|
1133
|
-
if (typeof value !== 'string' || !value) return null;
|
|
1134
|
-
if (value === 'about:blank' || value.startsWith('data:')) return null;
|
|
1135
|
-
try {
|
|
1136
|
-
const u = new URL(value);
|
|
1137
|
-
if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;
|
|
1138
|
-
return value;
|
|
1139
|
-
} catch {
|
|
1140
|
-
return null;
|
|
1141
|
-
}
|
|
1142
|
-
}
|
|
1143
|
-
|
|
1144
|
-
/**
|
|
1145
|
-
* Normalize any supported cookie payload into a Playwright cookie array.
|
|
1146
|
-
* Supported (pre-existing) formats: a JS array, or a string containing a JSON
|
|
1147
|
-
* array either directly or base64-wrapped. Returns { cookies, source }.
|
|
1148
|
-
*/
|
|
1149
|
-
function _normalizeCookiePayload(cookiesData) {
|
|
1150
|
-
let raw = null;
|
|
1151
|
-
let source = null;
|
|
1152
|
-
|
|
1153
|
-
if (Array.isArray(cookiesData)) {
|
|
1154
|
-
raw = cookiesData;
|
|
1155
|
-
source = 'array';
|
|
1156
|
-
} else if (typeof cookiesData === 'string') {
|
|
1157
|
-
const text = cookiesData.trim();
|
|
1158
|
-
if (!text) return { cookies: [], source: 'empty_string' };
|
|
1159
|
-
try {
|
|
1160
|
-
raw = JSON.parse(text);
|
|
1161
|
-
source = 'json_string';
|
|
1162
|
-
} catch {
|
|
1163
|
-
try {
|
|
1164
|
-
raw = JSON.parse(Buffer.from(text, 'base64').toString());
|
|
1165
|
-
source = 'base64_json';
|
|
1166
|
-
} catch { raw = null; }
|
|
1167
|
-
}
|
|
1168
|
-
} else if (cookiesData && typeof cookiesData === 'object') {
|
|
1169
|
-
// A wrapper object is NOT itself a cookie. Only an explicit `cookies`
|
|
1170
|
-
// array is accepted, so arbitrary objects can never become cookies.
|
|
1171
|
-
if (Array.isArray(cookiesData.cookies)) {
|
|
1172
|
-
raw = cookiesData.cookies;
|
|
1173
|
-
source = 'object.cookies';
|
|
1174
|
-
}
|
|
1175
|
-
}
|
|
1176
|
-
|
|
1177
|
-
if (!Array.isArray(raw)) return { cookies: [], source: source || 'unsupported' };
|
|
1178
|
-
|
|
1179
|
-
const cookies = [];
|
|
1180
|
-
let unrecognizedSameSite = 0;
|
|
1181
|
-
for (const c of raw) {
|
|
1182
|
-
if (!c || typeof c !== 'object') continue;
|
|
1183
|
-
if (typeof c.name !== 'string' || !c.name) continue;
|
|
1184
|
-
if (c.value == null) continue;
|
|
1185
|
-
const out = { name: c.name, value: String(c.value) };
|
|
1186
|
-
|
|
1187
|
-
// ── Scope: Playwright requires url XOR (domain + path) ──
|
|
1188
|
-
// The explicit domain/path pair wins when a record carries both (a shape
|
|
1189
|
-
// Playwright rejects outright).
|
|
1190
|
-
const hasDomain = typeof c.domain === 'string' && c.domain;
|
|
1191
|
-
if (hasDomain) {
|
|
1192
|
-
out.domain = c.domain;
|
|
1193
|
-
// The ONLY field this normalizer defaults, because Playwright mandates a
|
|
1194
|
-
// path whenever a domain is used.
|
|
1195
|
-
out.path = (typeof c.path === 'string' && c.path) ? c.path : '/';
|
|
1196
|
-
} else {
|
|
1197
|
-
const url = _usableUrl(c.url);
|
|
1198
|
-
if (!url) continue;
|
|
1199
|
-
out.url = url;
|
|
1200
|
-
}
|
|
1201
|
-
|
|
1202
|
-
// ── Optional fields: included ONLY when the stored record supplied them ──
|
|
1203
|
-
// Inventing secure/sameSite/httpOnly/expires would silently change how the
|
|
1204
|
-
// browser treats the cookie.
|
|
1205
|
-
const expires = _validExpires(c.expires);
|
|
1206
|
-
if (expires !== null) out.expires = expires;
|
|
1207
|
-
if (typeof c.httpOnly === 'boolean') out.httpOnly = c.httpOnly;
|
|
1208
|
-
if (typeof c.secure === 'boolean') out.secure = c.secure;
|
|
1209
|
-
if (c.sameSite != null) {
|
|
1210
|
-
const raw = String(c.sameSite).trim();
|
|
1211
|
-
if (raw) {
|
|
1212
|
-
const sameSite = _canonSameSite(raw);
|
|
1213
|
-
if (sameSite) out.sameSite = sameSite;
|
|
1214
|
-
else unrecognizedSameSite += 1; // omitted, never reinterpreted
|
|
1215
|
-
}
|
|
1216
|
-
}
|
|
1217
|
-
|
|
1218
|
-
cookies.push(out);
|
|
1219
|
-
}
|
|
1220
|
-
return { cookies, source: source || 'array', unrecognizedSameSite };
|
|
1221
|
-
}
|
|
1222
|
-
|
|
1223
|
-
/**
|
|
1224
|
-
* Restore account cookies into the persistent context. Never throws (a cookie
|
|
1225
|
-
* problem must not abort a launch), and NEVER fails silently: counts and any
|
|
1226
|
-
* error are returned for diagnostics and logged. Cookie VALUES are never
|
|
1227
|
-
* logged — only names/counts.
|
|
1228
|
-
*/
|
|
1229
|
-
async function _injectCookies(context, cookiesData) {
|
|
1230
|
-
const diag = {
|
|
1231
|
-
cookiesProvided: false,
|
|
1232
|
-
cookieSource: null,
|
|
1233
|
-
cookiesParsed: 0,
|
|
1234
|
-
cookiesInjected: 0,
|
|
1235
|
-
cookieError: null,
|
|
1236
|
-
};
|
|
1237
|
-
if (cookiesData == null || cookiesData === '') return diag;
|
|
1238
|
-
diag.cookiesProvided = true;
|
|
1239
|
-
|
|
1240
|
-
const { cookies, source } = _normalizeCookiePayload(cookiesData);
|
|
1241
|
-
diag.cookieSource = source;
|
|
1242
|
-
diag.cookiesParsed = cookies.length;
|
|
1243
|
-
|
|
1244
|
-
if (cookies.length === 0) {
|
|
1245
|
-
console.log(`[session] No cookies to inject (source=${source})`);
|
|
1246
|
-
return diag;
|
|
1247
|
-
}
|
|
1248
|
-
|
|
1249
|
-
const names = cookies.map((c) => c.name);
|
|
1250
|
-
const authCookiePresent = names.includes('auth_token');
|
|
1251
|
-
const csrfCookiePresent = names.includes('ct0');
|
|
1252
|
-
|
|
1253
|
-
try {
|
|
1254
|
-
await context.addCookies(cookies);
|
|
1255
|
-
diag.cookiesInjected = cookies.length;
|
|
1256
|
-
console.log(`[session] Injected ${cookies.length} cookies (source=${source}) authCookiePresent=${authCookiePresent} csrfCookiePresent=${csrfCookiePresent}`);
|
|
1257
|
-
return diag;
|
|
1258
|
-
} catch (err) {
|
|
1259
|
-
diag.cookieError = _safeError(err);
|
|
1260
|
-
console.error(`[session] Cookie injection failed for ${cookies.length} cookies: ${diag.cookieError}`);
|
|
1261
|
-
// One malformed entry must not discard the whole set: retry individually
|
|
1262
|
-
// and keep every cookie Playwright does accept.
|
|
1263
|
-
for (const c of cookies) {
|
|
1264
|
-
try {
|
|
1265
|
-
await context.addCookies([c]);
|
|
1266
|
-
diag.cookiesInjected += 1;
|
|
1267
|
-
} catch { /* this single entry is unusable — the rest are kept */ }
|
|
1268
|
-
}
|
|
1269
|
-
console.log(`[session] Injected ${diag.cookiesInjected}/${cookies.length} cookies after per-cookie retry (authCookiePresent=${authCookiePresent})`);
|
|
1270
|
-
return diag;
|
|
1271
|
-
}
|
|
1272
|
-
}
|
|
1273
|
-
|
|
1274
997
|
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
1275
998
|
|
|
1276
999
|
/**
|
|
@@ -1343,4 +1066,4 @@ function _safeError(err) {
|
|
|
1343
1066
|
.slice(0, 500);
|
|
1344
1067
|
}
|
|
1345
1068
|
|
|
1346
|
-
module.exports = { setupSessionHandler, activeSessions, closeAllSessions, markDisconnected, _detectProfileChromeRunning, _recoveryVerdict, _setChromeLinesProvider,
|
|
1069
|
+
module.exports = { setupSessionHandler, activeSessions, closeAllSessions, markDisconnected, _detectProfileChromeRunning, _recoveryVerdict, _setChromeLinesProvider, _attachContextCloseReporter };
|