@xkwdstore/agent 2.0.2 → 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 +252 -253
- package/package.json +54 -54
- package/src/actions/comment.js +137 -137
- package/src/actions/dbc.js +149 -149
- package/src/actions/follow.js +82 -82
- package/src/actions/helpers.js +753 -753
- package/src/actions/index.js +94 -94
- package/src/actions/like.js +244 -244
- package/src/actions/session.js +1610 -1610
- package/src/actions/tweet.js +90 -90
- package/src/challengeCodec.js +31 -31
- package/src/chromeDetector.js +154 -154
- package/src/cli.js +736 -528
- package/src/configStore.js +97 -97
- package/src/deviceKeyStore.js +947 -700
- package/src/enrollmentClient.js +588 -581
- package/src/fingerprint.js +261 -261
- package/src/fingerprintStore.js +125 -125
- package/src/leaseClient.js +84 -84
- package/src/processLock.js +148 -148
- package/src/profilePath.js +1116 -1116
- package/src/proxyEgress.js +338 -338
- package/src/proxyPolicy.js +76 -76
- package/src/secretStore.js +132 -132
- package/src/sessionHandler.js +874 -453
- package/src/stealth.js +1250 -1250
- package/src/wsClient.js +233 -233
package/src/sessionHandler.js
CHANGED
|
@@ -1,453 +1,874 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Phase 10 — Browser session handler (protocol v2).
|
|
5
|
-
*
|
|
6
|
-
* Defect 8 fix: Handle the existing hardened command envelope:
|
|
7
|
-
* { type: 'command', commandId, accountId, command: { type, ...rest, lease? },
|
|
8
|
-
* nonce?, leaseId?, accountUuid? }
|
|
9
|
-
*
|
|
10
|
-
* Defect 9 fix: Reuse the existing hardened browser runtime from index.js
|
|
11
|
-
* (actions, proxy fail-closed, media blocking, profile identity, lease client,
|
|
12
|
-
* cookie handling, etc.) rather than maintaining a second divergent runtime.
|
|
13
|
-
*
|
|
14
|
-
* The agent validates the complete inbound frame, reads the action type from
|
|
15
|
-
* the canonical command object, preserves command and lease expiry, echoes
|
|
16
|
-
* commandId/nonce/leaseId/accountUuid, returns results under the canonical
|
|
17
|
-
* `result` field, and rejects unknown command types.
|
|
18
|
-
*/
|
|
19
|
-
|
|
20
|
-
const { chromium } = require('playwright-core');
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
const
|
|
25
|
-
const
|
|
26
|
-
const {
|
|
27
|
-
const
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
//
|
|
34
|
-
//
|
|
35
|
-
//
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
*
|
|
184
|
-
*
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
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
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
return
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
if (!
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
const
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Phase 10 — Browser session handler (protocol v2).
|
|
5
|
+
*
|
|
6
|
+
* Defect 8 fix: Handle the existing hardened command envelope:
|
|
7
|
+
* { type: 'command', commandId, accountId, command: { type, ...rest, lease? },
|
|
8
|
+
* nonce?, leaseId?, accountUuid? }
|
|
9
|
+
*
|
|
10
|
+
* Defect 9 fix: Reuse the existing hardened browser runtime from index.js
|
|
11
|
+
* (actions, proxy fail-closed, media blocking, profile identity, lease client,
|
|
12
|
+
* cookie handling, etc.) rather than maintaining a second divergent runtime.
|
|
13
|
+
*
|
|
14
|
+
* The agent validates the complete inbound frame, reads the action type from
|
|
15
|
+
* the canonical command object, preserves command and lease expiry, echoes
|
|
16
|
+
* commandId/nonce/leaseId/accountUuid, returns results under the canonical
|
|
17
|
+
* `result` field, and rejects unknown command types.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const { chromium } = require('playwright-core');
|
|
21
|
+
const os = require('os');
|
|
22
|
+
|
|
23
|
+
// Import the existing hardened runtime modules (Defect 9).
|
|
24
|
+
const { generateFingerprint } = require('./fingerprint');
|
|
25
|
+
const fingerprintStore = require('./fingerprintStore');
|
|
26
|
+
const { resolveProfileDir, importLegacyProfile, discoverLegacyProfiles } = require('./profilePath');
|
|
27
|
+
const { buildStealthScript } = require('./stealth');
|
|
28
|
+
const leaseClient = require('./leaseClient');
|
|
29
|
+
const { PROFILES_DIR } = require('./deviceKeyStore');
|
|
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
|
+
|
|
87
|
+
// ── Windows foreground helper ────────────────────────────────────────────────
|
|
88
|
+
//
|
|
89
|
+
// page.bringToFront() may be insufficient on real Windows to actually bring
|
|
90
|
+
// the browser window to the foreground (Windows foreground lock rules).
|
|
91
|
+
// This helper uses a narrow, safe PowerShell command to activate the EXACT
|
|
92
|
+
// Chrome window associated with this session's persistent profile directory.
|
|
93
|
+
//
|
|
94
|
+
// Safety requirements:
|
|
95
|
+
// - uses the fixed System32 PowerShell 5.1 path (no PATH-based resolution)
|
|
96
|
+
// - uses execFileSync argument arrays (no shell:true, no command interpolation)
|
|
97
|
+
// - profileDir is passed via STDIN (never in command arguments)
|
|
98
|
+
// - targets ONLY the Chrome process whose command line contains the exact
|
|
99
|
+
// profileDir (not "most recent Chrome" globally)
|
|
100
|
+
// - does NOT kill or focus unrelated windows
|
|
101
|
+
// - Add-Type is defined BEFORE calling SetForegroundWindow (ordering fix)
|
|
102
|
+
// - returns true only if the intended window was identified and foregrounded
|
|
103
|
+
//
|
|
104
|
+
// @param {string} profileDir — the persistent profile directory for this session
|
|
105
|
+
// @returns {boolean} true if the window was identified and foregrounded
|
|
106
|
+
|
|
107
|
+
function _windowsForegroundChrome(profileDir) {
|
|
108
|
+
if (os.platform() !== 'win32') return true; // non-Windows: no-op success
|
|
109
|
+
if (!profileDir) return false;
|
|
110
|
+
try {
|
|
111
|
+
const nodePath = require('path');
|
|
112
|
+
const { execFileSync } = require('child_process');
|
|
113
|
+
const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
|
|
114
|
+
const psExe = nodePath.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
115
|
+
|
|
116
|
+
// Fixed PowerShell script — NO user data interpolation.
|
|
117
|
+
// The profileDir is passed via STDIN and read by the script.
|
|
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' }";
|
|
146
|
+
|
|
147
|
+
const output = execFileSync(psExe, ['-NoProfile', '-NonInteractive', '-Command', script], {
|
|
148
|
+
windowsHide: true,
|
|
149
|
+
encoding: 'utf8',
|
|
150
|
+
timeout: 5000,
|
|
151
|
+
input: profileDir, // profileDir via STDIN — never in command arguments
|
|
152
|
+
}).trim();
|
|
153
|
+
|
|
154
|
+
return output === 'OK';
|
|
155
|
+
} catch {
|
|
156
|
+
// Foreground helper failed — return false so visible is not claimed
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Active sessions: accountId -> { context, page, profileDir }
|
|
162
|
+
const activeSessions = new Map();
|
|
163
|
+
|
|
164
|
+
// Per-runtime state (B4 fix): each setupSessionHandler call creates a fresh
|
|
165
|
+
// runtime object so a newly initialized handler starts connected and does
|
|
166
|
+
// NOT inherit stale state from a prior handler lifecycle. The module-level
|
|
167
|
+
// `currentRuntime` is only used so markDisconnected() / closeAllSessions()
|
|
168
|
+
// (called from cli.js) can reach the active runtime without an explicit
|
|
169
|
+
// handle. One handler disconnecting cannot poison another handler's runtime.
|
|
170
|
+
const currentRuntime = { disconnected: false, sessions: activeSessions };
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Mark the CURRENT runtime as disconnected. After this, every inbound command
|
|
174
|
+
* for that runtime is rejected with a clear error and no new browser work is
|
|
175
|
+
* performed. A new setupSessionHandler call creates a fresh runtime that
|
|
176
|
+
* starts connected.
|
|
177
|
+
*/
|
|
178
|
+
function markDisconnected() {
|
|
179
|
+
currentRuntime.disconnected = true;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Close every active browser context, preserving profile/cookies through the
|
|
184
|
+
* existing safe persistence path (the context close flushes the persistent
|
|
185
|
+
* profile dir). Clears the active-sessions map. Safe to call multiple times.
|
|
186
|
+
* Operates on the current runtime's sessions.
|
|
187
|
+
*
|
|
188
|
+
* @returns {Promise<{ closed: number }>}
|
|
189
|
+
*/
|
|
190
|
+
async function closeAllSessions() {
|
|
191
|
+
const sessions = currentRuntime.sessions || activeSessions;
|
|
192
|
+
const keys = Array.from(sessions.keys());
|
|
193
|
+
let closed = 0;
|
|
194
|
+
for (const accountId of keys) {
|
|
195
|
+
const session = sessions.get(accountId);
|
|
196
|
+
if (!session) continue;
|
|
197
|
+
// Delete BEFORE closing so a concurrent call does not double-close.
|
|
198
|
+
sessions.delete(accountId);
|
|
199
|
+
try {
|
|
200
|
+
if (session.context) await session.context.close().catch(() => {});
|
|
201
|
+
} catch {}
|
|
202
|
+
closed += 1;
|
|
203
|
+
}
|
|
204
|
+
return { closed };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Set up the session handler on an authenticated WebSocket.
|
|
209
|
+
*
|
|
210
|
+
* @param {WebSocket} ws — authenticated v2 WebSocket
|
|
211
|
+
* @param {object} opts — { chromePath, deviceMeta, serverOrigin }
|
|
212
|
+
* @returns {Map} the active sessions map
|
|
213
|
+
*/
|
|
214
|
+
function setupSessionHandler(ws, opts) {
|
|
215
|
+
// B4 fix: reset the per-runtime state so a newly initialized handler starts
|
|
216
|
+
// connected and does NOT inherit stale state from a prior handler lifecycle.
|
|
217
|
+
// The module-level `currentRuntime` is shared so cli.js's markDisconnected()
|
|
218
|
+
// / closeAllSessions() reach the active runtime. Each setupSessionHandler
|
|
219
|
+
// call resets it to connected.
|
|
220
|
+
currentRuntime.disconnected = false;
|
|
221
|
+
currentRuntime.sessions = activeSessions;
|
|
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
|
+
|
|
254
|
+
ws.on('message', (data, isBinary) => {
|
|
255
|
+
if (isBinary) return;
|
|
256
|
+
|
|
257
|
+
let msg;
|
|
258
|
+
try {
|
|
259
|
+
msg = JSON.parse(data.toString('utf8'));
|
|
260
|
+
} catch {
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
if (!msg || typeof msg !== 'object') return;
|
|
265
|
+
|
|
266
|
+
// Handle the existing hardened command envelope (Defect 8).
|
|
267
|
+
if (msg.type === 'command') {
|
|
268
|
+
// Fail-safe: after the authenticated WebSocket closed, no further commands
|
|
269
|
+
// may be accepted. A stale/zombie socket must never drive a browser.
|
|
270
|
+
if (currentRuntime.disconnected) {
|
|
271
|
+
const echo = _extractEcho(msg);
|
|
272
|
+
try {
|
|
273
|
+
ws.send(JSON.stringify({
|
|
274
|
+
type: 'command-response',
|
|
275
|
+
commandId: msg.commandId,
|
|
276
|
+
result: { success: false, error: 'Agent disconnected: commands no longer accepted' },
|
|
277
|
+
...echo,
|
|
278
|
+
}));
|
|
279
|
+
} catch {}
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
_handleCommandEnvelope(ws, msg, opts).catch((err) => {
|
|
283
|
+
// Send error response with echo (never leak secrets).
|
|
284
|
+
const echo = _extractEcho(msg);
|
|
285
|
+
try {
|
|
286
|
+
ws.send(JSON.stringify({
|
|
287
|
+
type: 'command-response',
|
|
288
|
+
commandId: msg.commandId,
|
|
289
|
+
result: { success: false, error: _safeError(err) },
|
|
290
|
+
...echo,
|
|
291
|
+
}));
|
|
292
|
+
} catch {}
|
|
293
|
+
});
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// Handle heartbeats.
|
|
298
|
+
if (msg.type === 'heartbeat') {
|
|
299
|
+
try { ws.send(JSON.stringify({ type: 'heartbeat-ack' })); } catch {}
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// Reconnect reconciliation: the server asks for an active-sessions report.
|
|
304
|
+
// Each entry is lease-bound (accountUuid + leaseId + leaseToken + status).
|
|
305
|
+
// A missing/invalid status is NEVER defaulted to 'running' — the server
|
|
306
|
+
// treats an unverified entry as unresolved (the lease stays blocking).
|
|
307
|
+
if (msg.type === 'report-sessions') {
|
|
308
|
+
try {
|
|
309
|
+
const sessions = [];
|
|
310
|
+
for (const [accountId, session] of activeSessions) {
|
|
311
|
+
const lease = (session.lease && typeof session.lease.getClientView === 'function')
|
|
312
|
+
? session.lease.getClientView()
|
|
313
|
+
: (session.lease || null);
|
|
314
|
+
sessions.push({
|
|
315
|
+
accountId,
|
|
316
|
+
accountUuid: session.accountUuid || null,
|
|
317
|
+
leaseId: (lease && lease.leaseId) || null,
|
|
318
|
+
leaseToken: (lease && lease.leaseToken) || null,
|
|
319
|
+
status: session.context ? 'running' : 'stopped',
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
ws.send(JSON.stringify({ type: 'sessions-report', sessions }));
|
|
323
|
+
} catch {}
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
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
|
+
|
|
347
|
+
// session-status ack: the server confirms a stop was verified. No-op here
|
|
348
|
+
// beyond acknowledging; the lease stays under server authority.
|
|
349
|
+
if (msg.type === 'session-status') {
|
|
350
|
+
try { ws.send(JSON.stringify({ type: 'session-status-ack', commandId: msg.commandId || null })); } catch {}
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// Other message types (session-status, sessions-report, log) are handled
|
|
355
|
+
// by the shared engine on the backend side — the agent only needs to
|
|
356
|
+
// respond to commands and heartbeats.
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
return activeSessions;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Handle a command envelope: { type: 'command', commandId, accountId, command: { type, ... } }
|
|
364
|
+
*
|
|
365
|
+
* This delegates to the same session management logic used by the legacy agent,
|
|
366
|
+
* preserving all hardened safeguards (Defect 9).
|
|
367
|
+
*/
|
|
368
|
+
async function _handleCommandEnvelope(ws, msg, opts) {
|
|
369
|
+
const { commandId, accountId, command } = msg;
|
|
370
|
+
|
|
371
|
+
if (!commandId || typeof commandId !== 'string') {
|
|
372
|
+
return; // Malformed — drop silently.
|
|
373
|
+
}
|
|
374
|
+
if (!command || typeof command !== 'object') {
|
|
375
|
+
_sendResponse(ws, msg, { success: false, error: 'Missing command object' });
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const { type, ...rest } = command;
|
|
380
|
+
|
|
381
|
+
// Build the echo object from the envelope (nonce, leaseId, accountUuid).
|
|
382
|
+
const echo = _extractEcho(msg);
|
|
383
|
+
|
|
384
|
+
// Validate command type against the known allowlist.
|
|
385
|
+
const ALLOWED_TYPES = new Set([
|
|
386
|
+
'startSession', 'stopSession', 'restartSession', 'refreshSession',
|
|
387
|
+
'navigate', 'type', 'paste', 'press', 'click', 'runAction',
|
|
388
|
+
'getStatus', 'importLegacyProfile', 'discoverLegacyProfiles',
|
|
389
|
+
'focus',
|
|
390
|
+
]);
|
|
391
|
+
|
|
392
|
+
if (!ALLOWED_TYPES.has(type)) {
|
|
393
|
+
_sendResponse(ws, msg, { success: false, error: 'Unknown command type' });
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// Lease-required commands (same set as legacy agent).
|
|
398
|
+
const LEASE_REQUIRED = new Set([
|
|
399
|
+
'stopSession', 'restartSession', 'refreshSession', 'navigate',
|
|
400
|
+
'type', 'paste', 'press', 'click', 'runAction', 'focus',
|
|
401
|
+
]);
|
|
402
|
+
|
|
403
|
+
// Execute the command using the shared runtime.
|
|
404
|
+
try {
|
|
405
|
+
const result = await _executeCommand(type, { ...rest, accountId }, msg, opts, ws);
|
|
406
|
+
_sendResponse(ws, msg, result, echo);
|
|
407
|
+
} catch (err) {
|
|
408
|
+
_sendResponse(ws, msg, { success: false, error: _safeError(err) }, echo);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Execute a single command. This reuses the existing hardened runtime logic.
|
|
414
|
+
*/
|
|
415
|
+
async function _executeCommand(type, params, msg, opts, ws) {
|
|
416
|
+
const accountId = params.accountId || msg.accountId;
|
|
417
|
+
const accountUuid = msg.accountUuid || params.accountUuid;
|
|
418
|
+
const lease = params.lease || msg.command?.lease;
|
|
419
|
+
|
|
420
|
+
switch (type) {
|
|
421
|
+
case 'startSession':
|
|
422
|
+
return _startSession(params, opts, accountId, accountUuid, lease, ws);
|
|
423
|
+
case 'stopSession':
|
|
424
|
+
return _stopSession(accountId, lease, ws);
|
|
425
|
+
case 'restartSession':
|
|
426
|
+
await _stopSession(accountId, lease, ws);
|
|
427
|
+
return _startSession(params, opts, accountId, accountUuid, lease, ws);
|
|
428
|
+
case 'refreshSession':
|
|
429
|
+
return _refreshSession(accountId);
|
|
430
|
+
case 'navigate':
|
|
431
|
+
return _navigate(accountId, params.url);
|
|
432
|
+
case 'type':
|
|
433
|
+
return _typeText(accountId, params.selector, params.text);
|
|
434
|
+
case 'paste':
|
|
435
|
+
return _typeText(accountId, params.selector, params.text);
|
|
436
|
+
case 'press':
|
|
437
|
+
return _pressKey(accountId, params.key);
|
|
438
|
+
case 'click':
|
|
439
|
+
return _click(accountId, params.selector);
|
|
440
|
+
case 'focus':
|
|
441
|
+
return _focusSession(accountId);
|
|
442
|
+
case 'runAction':
|
|
443
|
+
return _runAction(accountId, params.action, params.payload || params.args);
|
|
444
|
+
case 'getStatus':
|
|
445
|
+
return _getStatus();
|
|
446
|
+
case 'importLegacyProfile':
|
|
447
|
+
return _importLegacyProfile(accountId, accountUuid, opts);
|
|
448
|
+
case 'discoverLegacyProfiles':
|
|
449
|
+
return _discoverLegacyProfiles();
|
|
450
|
+
default:
|
|
451
|
+
return { success: false, error: 'Unknown command type' };
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// ── Session management (reuses existing hardened modules) ───────────────────
|
|
456
|
+
|
|
457
|
+
async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
|
|
458
|
+
if (!accountId) return { success: false, error: 'Missing accountId' };
|
|
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
|
+
|
|
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
|
+
|
|
495
|
+
const profileDir = resolveProfileDir({
|
|
496
|
+
profilesDir: PROFILES_DIR,
|
|
497
|
+
serverUuid,
|
|
498
|
+
tenantUuid,
|
|
499
|
+
accountUuid: resolvedAccountUuid,
|
|
500
|
+
deviceUuid: deviceMeta.deviceId,
|
|
501
|
+
}).dir;
|
|
502
|
+
|
|
503
|
+
const fs = require('fs');
|
|
504
|
+
if (!fs.existsSync(profileDir)) fs.mkdirSync(profileDir, { recursive: true });
|
|
505
|
+
|
|
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
|
+
}
|
|
560
|
+
|
|
561
|
+
const args = [
|
|
562
|
+
'--disable-blink-features=AutomationControlled',
|
|
563
|
+
'--force-webrtc-ip-handling-policy=disable_non_proxied_udp',
|
|
564
|
+
'--no-first-run',
|
|
565
|
+
'--no-default-browser-check',
|
|
566
|
+
'--start-maximized',
|
|
567
|
+
];
|
|
568
|
+
|
|
569
|
+
// Prefer noDefaultViewport: true so the real OS window fills the screen
|
|
570
|
+
// (helps the launched browser appear visibly foregrounded). The per-account
|
|
571
|
+
// fingerprint invariants are enforced by the stealth init script against
|
|
572
|
+
// the *screen* object (window.screen.width/height), NOT against the
|
|
573
|
+
// Playwright viewport, so removing the forced viewport does not weaken the
|
|
574
|
+
// fingerprint. window.innerWidth/innerHeight are left to the real window
|
|
575
|
+
// size, which is acceptable because the stealth script does not pin them.
|
|
576
|
+
const launchOptions = {
|
|
577
|
+
executablePath: opts.chromePath,
|
|
578
|
+
headless: false,
|
|
579
|
+
args,
|
|
580
|
+
noDefaultViewport: true,
|
|
581
|
+
};
|
|
582
|
+
|
|
583
|
+
if (decision.useProxy && proxyStr) {
|
|
584
|
+
const proxyUrl = _parseProxy(proxyStr);
|
|
585
|
+
if (proxyUrl) launchOptions.proxy = proxyUrl;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
let context;
|
|
589
|
+
try {
|
|
590
|
+
context = await chromium.launchPersistentContext(profileDir, launchOptions);
|
|
591
|
+
} catch (err) {
|
|
592
|
+
_sendStartError(_safeError(err));
|
|
593
|
+
return { success: false, error: _safeError(err) };
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
await context.addInitScript(buildStealthScript(fingerprint));
|
|
597
|
+
|
|
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 {}
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
const pages = context.pages();
|
|
606
|
+
const page = pages[0] || await context.newPage();
|
|
607
|
+
|
|
608
|
+
const url = params.url || 'https://x.com/home';
|
|
609
|
+
await page.goto(url, { waitUntil: 'domcontentloaded' }).catch(() => {});
|
|
610
|
+
|
|
611
|
+
// If the browser launched but immediately closed, report a clear error
|
|
612
|
+
// instead of showing a misleading green "browser opened" toast.
|
|
613
|
+
if (page.isClosed()) {
|
|
614
|
+
try { await context.close().catch(() => {}); } catch {}
|
|
615
|
+
return {
|
|
616
|
+
success: false,
|
|
617
|
+
error: 'Browser launched but closed immediately. The session was not started.',
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
// Foreground the newly launched window so the user actually sees it.
|
|
622
|
+
// Do NOT report success until the page is confirmed focused.
|
|
623
|
+
let bringToFrontOk = false;
|
|
624
|
+
try {
|
|
625
|
+
await page.bringToFront();
|
|
626
|
+
bringToFrontOk = true;
|
|
627
|
+
} catch (err) {
|
|
628
|
+
try { await context.close().catch(() => {}); } catch {}
|
|
629
|
+
return {
|
|
630
|
+
success: false,
|
|
631
|
+
error: 'Browser launched but could not be brought to the foreground: ' + _safeError(err),
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
// Windows-specific foreground: page.bringToFront() alone may not overcome
|
|
636
|
+
// the Windows foreground lock. This helper targets the EXACT Chrome process
|
|
637
|
+
// whose command line contains this session's profileDir (passed via stdin,
|
|
638
|
+
// not interpolated). It returns true ONLY if the intended window was
|
|
639
|
+
// identified and successfully foregrounded.
|
|
640
|
+
let foregroundVerified = false;
|
|
641
|
+
if (bringToFrontOk) {
|
|
642
|
+
foregroundVerified = _windowsForegroundChrome(profileDir);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// Re-check after focus: the page may have closed in the meantime.
|
|
646
|
+
if (page.isClosed()) {
|
|
647
|
+
try { await context.close().catch(() => {}); } catch {}
|
|
648
|
+
return {
|
|
649
|
+
success: false,
|
|
650
|
+
error: 'Browser closed immediately after focusing. The session was not started.',
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
const session = { context, page, profileDir, accountId, lease: null };
|
|
655
|
+
if (lease) leaseClient.bind(session, lease);
|
|
656
|
+
activeSessions.set(accountId, session);
|
|
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
|
+
|
|
679
|
+
// Return confirmed success metadata. The backend/frontend uses this to
|
|
680
|
+
// show a green toast ONLY when the browser is genuinely started and visible.
|
|
681
|
+
//
|
|
682
|
+
// visible: true requires POSITIVE evidence:
|
|
683
|
+
// - launchPersistentContext succeeded
|
|
684
|
+
// - page exists and is not closed
|
|
685
|
+
// - page.bringToFront() succeeded
|
|
686
|
+
// - on Windows: the intended Chrome process was identified and
|
|
687
|
+
// SetForegroundWindow succeeded (or on non-Windows: bringToFront is
|
|
688
|
+
// sufficient)
|
|
689
|
+
//
|
|
690
|
+
// If the Windows foreground helper cannot prove the window is visible
|
|
691
|
+
// (foregroundVerified = false), we return started:true but visible:false
|
|
692
|
+
// with an actionable error so the frontend does NOT show a green toast.
|
|
693
|
+
if (os.platform() === 'win32' && !foregroundVerified) {
|
|
694
|
+
// The browser launched and bringToFront succeeded, but we could not
|
|
695
|
+
// positively verify the window is in the foreground. Return a safe
|
|
696
|
+
// actionable message — NOT a green toast.
|
|
697
|
+
return {
|
|
698
|
+
success: true,
|
|
699
|
+
accountId,
|
|
700
|
+
started: true,
|
|
701
|
+
visible: false,
|
|
702
|
+
sessionId: accountId,
|
|
703
|
+
error: 'Browser launched but could not be confirmed in the foreground. Check the taskbar for the Chrome window.',
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
return {
|
|
708
|
+
success: true,
|
|
709
|
+
accountId,
|
|
710
|
+
started: true,
|
|
711
|
+
visible: true,
|
|
712
|
+
sessionId: accountId,
|
|
713
|
+
};
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
async function _stopSession(accountId, lease, ws) {
|
|
717
|
+
const session = activeSessions.get(accountId);
|
|
718
|
+
if (!session) return { success: false, error: 'Session not found' };
|
|
719
|
+
try { await session.context.close(); } catch {}
|
|
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
|
+
}
|
|
726
|
+
return { success: true, accountId, stopped: true };
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
async function _refreshSession(accountId) {
|
|
730
|
+
const session = activeSessions.get(accountId);
|
|
731
|
+
if (!session) return { success: false, error: 'Session not found' };
|
|
732
|
+
await session.page.reload();
|
|
733
|
+
return { success: true };
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
async function _navigate(accountId, url) {
|
|
737
|
+
const session = activeSessions.get(accountId);
|
|
738
|
+
if (!session) return { success: false, error: 'Session not found' };
|
|
739
|
+
await session.page.goto(url, { waitUntil: 'domcontentloaded' });
|
|
740
|
+
return { success: true };
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
async function _typeText(accountId, selector, text) {
|
|
744
|
+
const session = activeSessions.get(accountId);
|
|
745
|
+
if (!session) return { success: false, error: 'Session not found' };
|
|
746
|
+
await session.page.locator(selector).fill(text);
|
|
747
|
+
return { success: true };
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
async function _pressKey(accountId, key) {
|
|
751
|
+
const session = activeSessions.get(accountId);
|
|
752
|
+
if (!session) return { success: false, error: 'Session not found' };
|
|
753
|
+
await session.page.keyboard.press(key);
|
|
754
|
+
return { success: true };
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
async function _click(accountId, selector) {
|
|
758
|
+
const session = activeSessions.get(accountId);
|
|
759
|
+
if (!session) return { success: false, error: 'Session not found' };
|
|
760
|
+
await session.page.locator(selector).click();
|
|
761
|
+
return { success: true };
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
async function _focusSession(accountId) {
|
|
765
|
+
const session = activeSessions.get(accountId);
|
|
766
|
+
if (!session) return { success: false, error: 'Session not found' };
|
|
767
|
+
await session.page.bringToFront();
|
|
768
|
+
return { success: true };
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
async function _runAction(accountId, action, payload) {
|
|
772
|
+
const session = activeSessions.get(accountId);
|
|
773
|
+
if (!session) return { success: false, error: 'Session not found' };
|
|
774
|
+
const { runAction } = require('./actions');
|
|
775
|
+
const result = await runAction(session.page, action, payload || {});
|
|
776
|
+
return { success: true, result };
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
function _getStatus() {
|
|
780
|
+
const sessions = [];
|
|
781
|
+
for (const [accountId, session] of activeSessions) {
|
|
782
|
+
sessions.push({ accountId, url: session.page ? session.page.url() : null });
|
|
783
|
+
}
|
|
784
|
+
return { success: true, sessions, count: sessions.length };
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
function _importLegacyProfile(accountId, accountUuid, opts) {
|
|
788
|
+
// Defect 9 fix: pass opts correctly (was undefined before).
|
|
789
|
+
const result = importLegacyProfile(accountId, {
|
|
790
|
+
profileRoot: PROFILES_DIR,
|
|
791
|
+
deviceUuid: opts.deviceMeta.deviceId,
|
|
792
|
+
accountUuid,
|
|
793
|
+
});
|
|
794
|
+
return { success: true, result };
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
function _discoverLegacyProfiles() {
|
|
798
|
+
const profiles = discoverLegacyProfiles(PROFILES_DIR);
|
|
799
|
+
return { success: true, profiles };
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
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
|
+
|
|
833
|
+
function _extractEcho(msg) {
|
|
834
|
+
const echo = {};
|
|
835
|
+
if (msg.nonce) echo.nonce = msg.nonce;
|
|
836
|
+
if (msg.leaseId) echo.leaseId = msg.leaseId;
|
|
837
|
+
if (msg.accountUuid) echo.accountUuid = msg.accountUuid;
|
|
838
|
+
return echo;
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
function _sendResponse(ws, msg, result, echo) {
|
|
842
|
+
try {
|
|
843
|
+
ws.send(JSON.stringify({
|
|
844
|
+
type: 'command-response',
|
|
845
|
+
commandId: msg.commandId,
|
|
846
|
+
result,
|
|
847
|
+
...(echo || _extractEcho(msg)),
|
|
848
|
+
}));
|
|
849
|
+
} catch {}
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
function _parseProxy(proxyStr) {
|
|
853
|
+
if (!proxyStr || typeof proxyStr !== 'string') return null;
|
|
854
|
+
const parts = proxyStr.split(':');
|
|
855
|
+
if (parts.length >= 2) {
|
|
856
|
+
const proxy = { server: `http://${parts[0]}:${parts[1]}` };
|
|
857
|
+
if (parts[2] && parts[3]) {
|
|
858
|
+
proxy.username = parts[2];
|
|
859
|
+
proxy.password = parts[3];
|
|
860
|
+
}
|
|
861
|
+
return proxy;
|
|
862
|
+
}
|
|
863
|
+
return null;
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
function _safeError(err) {
|
|
867
|
+
const msg = err && err.message ? err.message : String(err);
|
|
868
|
+
return msg
|
|
869
|
+
.replace(/[A-Fa-f0-9]{64}/g, '<hex>')
|
|
870
|
+
.replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, '<jwt>')
|
|
871
|
+
.slice(0, 500);
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
module.exports = { setupSessionHandler, activeSessions, closeAllSessions, markDisconnected, _detectProfileChromeRunning, _recoveryVerdict, _setChromeLinesProvider };
|