@xkwdstore/agent 2.0.1 → 2.0.3
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 +251 -244
- 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 +664 -528
- package/src/configStore.js +97 -97
- package/src/deviceKeyStore.js +947 -700
- package/src/enrollmentClient.js +588 -445
- 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 +618 -452
- package/src/stealth.js +1250 -1250
- package/src/wsClient.js +233 -233
package/src/sessionHandler.js
CHANGED
|
@@ -1,453 +1,619 @@
|
|
|
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
|
-
|
|
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
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
const
|
|
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
|
-
const
|
|
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
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
const
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
const
|
|
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
|
-
|
|
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
|
+
// ── Windows foreground helper ────────────────────────────────────────────────
|
|
32
|
+
//
|
|
33
|
+
// page.bringToFront() may be insufficient on real Windows to actually bring
|
|
34
|
+
// the browser window to the foreground (Windows foreground lock rules).
|
|
35
|
+
// This helper uses a narrow, safe PowerShell command to activate the EXACT
|
|
36
|
+
// Chrome window associated with this session's persistent profile directory.
|
|
37
|
+
//
|
|
38
|
+
// Safety requirements:
|
|
39
|
+
// - uses the fixed System32 PowerShell 5.1 path (no PATH-based resolution)
|
|
40
|
+
// - uses execFileSync argument arrays (no shell:true, no command interpolation)
|
|
41
|
+
// - profileDir is passed via STDIN (never in command arguments)
|
|
42
|
+
// - targets ONLY the Chrome process whose command line contains the exact
|
|
43
|
+
// profileDir (not "most recent Chrome" globally)
|
|
44
|
+
// - does NOT kill or focus unrelated windows
|
|
45
|
+
// - Add-Type is defined BEFORE calling SetForegroundWindow (ordering fix)
|
|
46
|
+
// - returns true only if the intended window was identified and foregrounded
|
|
47
|
+
//
|
|
48
|
+
// @param {string} profileDir — the persistent profile directory for this session
|
|
49
|
+
// @returns {boolean} true if the window was identified and foregrounded
|
|
50
|
+
|
|
51
|
+
function _windowsForegroundChrome(profileDir) {
|
|
52
|
+
if (os.platform() !== 'win32') return true; // non-Windows: no-op success
|
|
53
|
+
if (!profileDir) return false;
|
|
54
|
+
try {
|
|
55
|
+
const nodePath = require('path');
|
|
56
|
+
const { execFileSync } = require('child_process');
|
|
57
|
+
const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
|
|
58
|
+
const psExe = nodePath.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
59
|
+
|
|
60
|
+
// Fixed PowerShell script — NO user data interpolation.
|
|
61
|
+
// The profileDir is passed via STDIN and read by the script.
|
|
62
|
+
// Add-Type is defined BEFORE any call to SetForegroundWindow.
|
|
63
|
+
// The script:
|
|
64
|
+
// 1. Reads the profileDir from stdin
|
|
65
|
+
// 2. Finds chrome.exe processes whose command line contains that exact path
|
|
66
|
+
// 3. Gets the MainWindowHandle of that specific process
|
|
67
|
+
// 4. Uses SetForegroundWindow + ShowWindowAsync to restore+foreground it
|
|
68
|
+
// 5. Outputs "OK" or "FAIL" so the caller knows whether it worked
|
|
69
|
+
const script =
|
|
70
|
+
"$ErrorActionPreference='Stop'; " +
|
|
71
|
+
"Add-Type -Namespace Win32 -Name Native -MemberDefinition '" +
|
|
72
|
+
"[DllImport(\"user32.dll\")] public static extern bool SetForegroundWindow(IntPtr hWnd); " +
|
|
73
|
+
"[DllImport(\"user32.dll\")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); " +
|
|
74
|
+
"[DllImport(\"user32.dll\")] public static extern bool IsIconic(IntPtr hWnd); " +
|
|
75
|
+
"'; " +
|
|
76
|
+
"$profileDir = [Console]::In.ReadToEnd().Trim(); " +
|
|
77
|
+
"if (-not $profileDir) { Write-Output 'FAIL:no_profile'; exit 0 }; " +
|
|
78
|
+
"$procs = Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\" -ErrorAction SilentlyContinue; " +
|
|
79
|
+
"$target = $null; " +
|
|
80
|
+
"foreach ($p in $procs) { " +
|
|
81
|
+
" if ($p.CommandLine -and ($p.CommandLine -like \"*$profileDir*\")) { $target = $p; break } " +
|
|
82
|
+
"}; " +
|
|
83
|
+
"if (-not $target) { Write-Output 'FAIL:no_process'; exit 0 }; " +
|
|
84
|
+
"$proc = Get-Process -Id $target.ProcessId -ErrorAction SilentlyContinue; " +
|
|
85
|
+
"if (-not $proc -or $proc.MainWindowHandle -eq [IntPtr]::Zero) { Write-Output 'FAIL:no_window'; exit 0 }; " +
|
|
86
|
+
"$handle = $proc.MainWindowHandle; " +
|
|
87
|
+
"if ([Win32.Native]::IsIconic($handle)) { [void][Win32.Native]::ShowWindowAsync($handle, 9) }; " +
|
|
88
|
+
"$result = [Win32.Native]::SetForegroundWindow($handle); " +
|
|
89
|
+
"if ($result) { Write-Output 'OK' } else { Write-Output 'FAIL:foreground' }";
|
|
90
|
+
|
|
91
|
+
const output = execFileSync(psExe, ['-NoProfile', '-NonInteractive', '-Command', script], {
|
|
92
|
+
windowsHide: true,
|
|
93
|
+
encoding: 'utf8',
|
|
94
|
+
timeout: 5000,
|
|
95
|
+
input: profileDir, // profileDir via STDIN — never in command arguments
|
|
96
|
+
}).trim();
|
|
97
|
+
|
|
98
|
+
return output === 'OK';
|
|
99
|
+
} catch {
|
|
100
|
+
// Foreground helper failed — return false so visible is not claimed
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Active sessions: accountId -> { context, page, profileDir }
|
|
106
|
+
const activeSessions = new Map();
|
|
107
|
+
|
|
108
|
+
// Per-runtime state (B4 fix): each setupSessionHandler call creates a fresh
|
|
109
|
+
// runtime object so a newly initialized handler starts connected and does
|
|
110
|
+
// NOT inherit stale state from a prior handler lifecycle. The module-level
|
|
111
|
+
// `currentRuntime` is only used so markDisconnected() / closeAllSessions()
|
|
112
|
+
// (called from cli.js) can reach the active runtime without an explicit
|
|
113
|
+
// handle. One handler disconnecting cannot poison another handler's runtime.
|
|
114
|
+
const currentRuntime = { disconnected: false, sessions: activeSessions };
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Mark the CURRENT runtime as disconnected. After this, every inbound command
|
|
118
|
+
* for that runtime is rejected with a clear error and no new browser work is
|
|
119
|
+
* performed. A new setupSessionHandler call creates a fresh runtime that
|
|
120
|
+
* starts connected.
|
|
121
|
+
*/
|
|
122
|
+
function markDisconnected() {
|
|
123
|
+
currentRuntime.disconnected = true;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Close every active browser context, preserving profile/cookies through the
|
|
128
|
+
* existing safe persistence path (the context close flushes the persistent
|
|
129
|
+
* profile dir). Clears the active-sessions map. Safe to call multiple times.
|
|
130
|
+
* Operates on the current runtime's sessions.
|
|
131
|
+
*
|
|
132
|
+
* @returns {Promise<{ closed: number }>}
|
|
133
|
+
*/
|
|
134
|
+
async function closeAllSessions() {
|
|
135
|
+
const sessions = currentRuntime.sessions || activeSessions;
|
|
136
|
+
const keys = Array.from(sessions.keys());
|
|
137
|
+
let closed = 0;
|
|
138
|
+
for (const accountId of keys) {
|
|
139
|
+
const session = sessions.get(accountId);
|
|
140
|
+
if (!session) continue;
|
|
141
|
+
// Delete BEFORE closing so a concurrent call does not double-close.
|
|
142
|
+
sessions.delete(accountId);
|
|
143
|
+
try {
|
|
144
|
+
if (session.context) await session.context.close().catch(() => {});
|
|
145
|
+
} catch {}
|
|
146
|
+
closed += 1;
|
|
147
|
+
}
|
|
148
|
+
return { closed };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Set up the session handler on an authenticated WebSocket.
|
|
153
|
+
*
|
|
154
|
+
* @param {WebSocket} ws — authenticated v2 WebSocket
|
|
155
|
+
* @param {object} opts — { chromePath, deviceMeta, serverOrigin }
|
|
156
|
+
* @returns {Map} the active sessions map
|
|
157
|
+
*/
|
|
158
|
+
function setupSessionHandler(ws, opts) {
|
|
159
|
+
// B4 fix: reset the per-runtime state so a newly initialized handler starts
|
|
160
|
+
// connected and does NOT inherit stale state from a prior handler lifecycle.
|
|
161
|
+
// The module-level `currentRuntime` is shared so cli.js's markDisconnected()
|
|
162
|
+
// / closeAllSessions() reach the active runtime. Each setupSessionHandler
|
|
163
|
+
// call resets it to connected.
|
|
164
|
+
currentRuntime.disconnected = false;
|
|
165
|
+
currentRuntime.sessions = activeSessions;
|
|
166
|
+
|
|
167
|
+
ws.on('message', (data, isBinary) => {
|
|
168
|
+
if (isBinary) return;
|
|
169
|
+
|
|
170
|
+
let msg;
|
|
171
|
+
try {
|
|
172
|
+
msg = JSON.parse(data.toString('utf8'));
|
|
173
|
+
} catch {
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (!msg || typeof msg !== 'object') return;
|
|
178
|
+
|
|
179
|
+
// Handle the existing hardened command envelope (Defect 8).
|
|
180
|
+
if (msg.type === 'command') {
|
|
181
|
+
// Fail-safe: after the authenticated WebSocket closed, no further commands
|
|
182
|
+
// may be accepted. A stale/zombie socket must never drive a browser.
|
|
183
|
+
if (currentRuntime.disconnected) {
|
|
184
|
+
const echo = _extractEcho(msg);
|
|
185
|
+
try {
|
|
186
|
+
ws.send(JSON.stringify({
|
|
187
|
+
type: 'command-response',
|
|
188
|
+
commandId: msg.commandId,
|
|
189
|
+
result: { success: false, error: 'Agent disconnected: commands no longer accepted' },
|
|
190
|
+
...echo,
|
|
191
|
+
}));
|
|
192
|
+
} catch {}
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
_handleCommandEnvelope(ws, msg, opts).catch((err) => {
|
|
196
|
+
// Send error response with echo (never leak secrets).
|
|
197
|
+
const echo = _extractEcho(msg);
|
|
198
|
+
try {
|
|
199
|
+
ws.send(JSON.stringify({
|
|
200
|
+
type: 'command-response',
|
|
201
|
+
commandId: msg.commandId,
|
|
202
|
+
result: { success: false, error: _safeError(err) },
|
|
203
|
+
...echo,
|
|
204
|
+
}));
|
|
205
|
+
} catch {}
|
|
206
|
+
});
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Handle heartbeats.
|
|
211
|
+
if (msg.type === 'heartbeat') {
|
|
212
|
+
try { ws.send(JSON.stringify({ type: 'heartbeat-ack' })); } catch {}
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Reconnect reconciliation: the server asks for an active-sessions report.
|
|
217
|
+
// Each entry is lease-bound (accountUuid + leaseId + leaseToken + status).
|
|
218
|
+
// A missing/invalid status is NEVER defaulted to 'running' — the server
|
|
219
|
+
// treats an unverified entry as unresolved (the lease stays blocking).
|
|
220
|
+
if (msg.type === 'report-sessions') {
|
|
221
|
+
try {
|
|
222
|
+
const sessions = [];
|
|
223
|
+
for (const [accountId, session] of activeSessions) {
|
|
224
|
+
const lease = (session.lease && typeof session.lease.getClientView === 'function')
|
|
225
|
+
? session.lease.getClientView()
|
|
226
|
+
: (session.lease || null);
|
|
227
|
+
sessions.push({
|
|
228
|
+
accountId,
|
|
229
|
+
accountUuid: session.accountUuid || null,
|
|
230
|
+
leaseId: (lease && lease.leaseId) || null,
|
|
231
|
+
leaseToken: (lease && lease.leaseToken) || null,
|
|
232
|
+
status: session.context ? 'running' : 'stopped',
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
ws.send(JSON.stringify({ type: 'sessions-report', sessions }));
|
|
236
|
+
} catch {}
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// session-status ack: the server confirms a stop was verified. No-op here
|
|
241
|
+
// beyond acknowledging; the lease stays under server authority.
|
|
242
|
+
if (msg.type === 'session-status') {
|
|
243
|
+
try { ws.send(JSON.stringify({ type: 'session-status-ack', commandId: msg.commandId || null })); } catch {}
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Other message types (session-status, sessions-report, log) are handled
|
|
248
|
+
// by the shared engine on the backend side — the agent only needs to
|
|
249
|
+
// respond to commands and heartbeats.
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
return activeSessions;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Handle a command envelope: { type: 'command', commandId, accountId, command: { type, ... } }
|
|
257
|
+
*
|
|
258
|
+
* This delegates to the same session management logic used by the legacy agent,
|
|
259
|
+
* preserving all hardened safeguards (Defect 9).
|
|
260
|
+
*/
|
|
261
|
+
async function _handleCommandEnvelope(ws, msg, opts) {
|
|
262
|
+
const { commandId, accountId, command } = msg;
|
|
263
|
+
|
|
264
|
+
if (!commandId || typeof commandId !== 'string') {
|
|
265
|
+
return; // Malformed — drop silently.
|
|
266
|
+
}
|
|
267
|
+
if (!command || typeof command !== 'object') {
|
|
268
|
+
_sendResponse(ws, msg, { success: false, error: 'Missing command object' });
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const { type, ...rest } = command;
|
|
273
|
+
|
|
274
|
+
// Build the echo object from the envelope (nonce, leaseId, accountUuid).
|
|
275
|
+
const echo = _extractEcho(msg);
|
|
276
|
+
|
|
277
|
+
// Validate command type against the known allowlist.
|
|
278
|
+
const ALLOWED_TYPES = new Set([
|
|
279
|
+
'startSession', 'stopSession', 'restartSession', 'refreshSession',
|
|
280
|
+
'navigate', 'type', 'paste', 'press', 'click', 'runAction',
|
|
281
|
+
'getStatus', 'importLegacyProfile', 'discoverLegacyProfiles',
|
|
282
|
+
'focus',
|
|
283
|
+
]);
|
|
284
|
+
|
|
285
|
+
if (!ALLOWED_TYPES.has(type)) {
|
|
286
|
+
_sendResponse(ws, msg, { success: false, error: 'Unknown command type' });
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// Lease-required commands (same set as legacy agent).
|
|
291
|
+
const LEASE_REQUIRED = new Set([
|
|
292
|
+
'stopSession', 'restartSession', 'refreshSession', 'navigate',
|
|
293
|
+
'type', 'paste', 'press', 'click', 'runAction', 'focus',
|
|
294
|
+
]);
|
|
295
|
+
|
|
296
|
+
// Execute the command using the shared runtime.
|
|
297
|
+
try {
|
|
298
|
+
const result = await _executeCommand(type, { ...rest, accountId }, msg, opts, ws);
|
|
299
|
+
_sendResponse(ws, msg, result, echo);
|
|
300
|
+
} catch (err) {
|
|
301
|
+
_sendResponse(ws, msg, { success: false, error: _safeError(err) }, echo);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Execute a single command. This reuses the existing hardened runtime logic.
|
|
307
|
+
*/
|
|
308
|
+
async function _executeCommand(type, params, msg, opts, ws) {
|
|
309
|
+
const accountId = params.accountId || msg.accountId;
|
|
310
|
+
const accountUuid = msg.accountUuid || params.accountUuid;
|
|
311
|
+
const lease = params.lease || msg.command?.lease;
|
|
312
|
+
|
|
313
|
+
switch (type) {
|
|
314
|
+
case 'startSession':
|
|
315
|
+
return _startSession(params, opts, accountId, accountUuid, lease);
|
|
316
|
+
case 'stopSession':
|
|
317
|
+
return _stopSession(accountId, lease);
|
|
318
|
+
case 'restartSession':
|
|
319
|
+
await _stopSession(accountId, lease);
|
|
320
|
+
return _startSession(params, opts, accountId, accountUuid, lease);
|
|
321
|
+
case 'refreshSession':
|
|
322
|
+
return _refreshSession(accountId);
|
|
323
|
+
case 'navigate':
|
|
324
|
+
return _navigate(accountId, params.url);
|
|
325
|
+
case 'type':
|
|
326
|
+
return _typeText(accountId, params.selector, params.text);
|
|
327
|
+
case 'paste':
|
|
328
|
+
return _typeText(accountId, params.selector, params.text);
|
|
329
|
+
case 'press':
|
|
330
|
+
return _pressKey(accountId, params.key);
|
|
331
|
+
case 'click':
|
|
332
|
+
return _click(accountId, params.selector);
|
|
333
|
+
case 'focus':
|
|
334
|
+
return _focusSession(accountId);
|
|
335
|
+
case 'runAction':
|
|
336
|
+
return _runAction(accountId, params.action, params.payload || params.args);
|
|
337
|
+
case 'getStatus':
|
|
338
|
+
return _getStatus();
|
|
339
|
+
case 'importLegacyProfile':
|
|
340
|
+
return _importLegacyProfile(accountId, accountUuid, opts);
|
|
341
|
+
case 'discoverLegacyProfiles':
|
|
342
|
+
return _discoverLegacyProfiles();
|
|
343
|
+
default:
|
|
344
|
+
return { success: false, error: 'Unknown command type' };
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// ── Session management (reuses existing hardened modules) ───────────────────
|
|
349
|
+
|
|
350
|
+
async function _startSession(params, opts, accountId, accountUuid, lease) {
|
|
351
|
+
if (!accountId) return { success: false, error: 'Missing accountId' };
|
|
352
|
+
|
|
353
|
+
const deviceMeta = opts.deviceMeta;
|
|
354
|
+
const profileDir = resolveProfileDir({
|
|
355
|
+
profileRoot: PROFILES_DIR,
|
|
356
|
+
deviceUuid: deviceMeta.deviceId,
|
|
357
|
+
accountUuid: accountUuid || accountId,
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
const fs = require('fs');
|
|
361
|
+
if (!fs.existsSync(profileDir)) fs.mkdirSync(profileDir, { recursive: true });
|
|
362
|
+
|
|
363
|
+
const fingerprint = fingerprintStore.loadOrGenerate(profileDir, () => generateFingerprint());
|
|
364
|
+
|
|
365
|
+
const args = [
|
|
366
|
+
'--disable-blink-features=AutomationControlled',
|
|
367
|
+
'--force-webrtc-ip-handling-policy=disable_non_proxied_udp',
|
|
368
|
+
'--no-first-run',
|
|
369
|
+
'--no-default-browser-check',
|
|
370
|
+
'--start-maximized',
|
|
371
|
+
];
|
|
372
|
+
|
|
373
|
+
// Prefer noDefaultViewport: true so the real OS window fills the screen
|
|
374
|
+
// (helps the launched browser appear visibly foregrounded). The per-account
|
|
375
|
+
// fingerprint invariants are enforced by the stealth init script against
|
|
376
|
+
// the *screen* object (window.screen.width/height), NOT against the
|
|
377
|
+
// Playwright viewport, so removing the forced viewport does not weaken the
|
|
378
|
+
// fingerprint. window.innerWidth/innerHeight are left to the real window
|
|
379
|
+
// size, which is acceptable because the stealth script does not pin them.
|
|
380
|
+
const launchOptions = {
|
|
381
|
+
executablePath: opts.chromePath,
|
|
382
|
+
headless: false,
|
|
383
|
+
args,
|
|
384
|
+
noDefaultViewport: true,
|
|
385
|
+
};
|
|
386
|
+
|
|
387
|
+
if (params.proxy) {
|
|
388
|
+
const proxyUrl = _parseProxy(params.proxy);
|
|
389
|
+
if (proxyUrl) launchOptions.proxy = proxyUrl;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
let context;
|
|
393
|
+
try {
|
|
394
|
+
context = await chromium.launchPersistentContext(profileDir, launchOptions);
|
|
395
|
+
} catch (err) {
|
|
396
|
+
return { success: false, error: _safeError(err) };
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
await context.addInitScript(buildStealthScript(fingerprint));
|
|
400
|
+
|
|
401
|
+
if (params.cookies && Array.isArray(params.cookies)) {
|
|
402
|
+
try { await context.addCookies(params.cookies); } catch {}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const pages = context.pages();
|
|
406
|
+
const page = pages[0] || await context.newPage();
|
|
407
|
+
|
|
408
|
+
const url = params.url || 'https://x.com/home';
|
|
409
|
+
await page.goto(url, { waitUntil: 'domcontentloaded' }).catch(() => {});
|
|
410
|
+
|
|
411
|
+
// If the browser launched but immediately closed, report a clear error
|
|
412
|
+
// instead of showing a misleading green "browser opened" toast.
|
|
413
|
+
if (page.isClosed()) {
|
|
414
|
+
try { await context.close().catch(() => {}); } catch {}
|
|
415
|
+
return {
|
|
416
|
+
success: false,
|
|
417
|
+
error: 'Browser launched but closed immediately. The session was not started.',
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// Foreground the newly launched window so the user actually sees it.
|
|
422
|
+
// Do NOT report success until the page is confirmed focused.
|
|
423
|
+
let bringToFrontOk = false;
|
|
424
|
+
try {
|
|
425
|
+
await page.bringToFront();
|
|
426
|
+
bringToFrontOk = true;
|
|
427
|
+
} catch (err) {
|
|
428
|
+
try { await context.close().catch(() => {}); } catch {}
|
|
429
|
+
return {
|
|
430
|
+
success: false,
|
|
431
|
+
error: 'Browser launched but could not be brought to the foreground: ' + _safeError(err),
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// Windows-specific foreground: page.bringToFront() alone may not overcome
|
|
436
|
+
// the Windows foreground lock. This helper targets the EXACT Chrome process
|
|
437
|
+
// whose command line contains this session's profileDir (passed via stdin,
|
|
438
|
+
// not interpolated). It returns true ONLY if the intended window was
|
|
439
|
+
// identified and successfully foregrounded.
|
|
440
|
+
let foregroundVerified = false;
|
|
441
|
+
if (bringToFrontOk) {
|
|
442
|
+
foregroundVerified = _windowsForegroundChrome(profileDir);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// Re-check after focus: the page may have closed in the meantime.
|
|
446
|
+
if (page.isClosed()) {
|
|
447
|
+
try { await context.close().catch(() => {}); } catch {}
|
|
448
|
+
return {
|
|
449
|
+
success: false,
|
|
450
|
+
error: 'Browser closed immediately after focusing. The session was not started.',
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const session = { context, page, profileDir, accountId, lease: null };
|
|
455
|
+
if (lease) leaseClient.bind(session, lease);
|
|
456
|
+
activeSessions.set(accountId, session);
|
|
457
|
+
|
|
458
|
+
// Return confirmed success metadata. The backend/frontend uses this to
|
|
459
|
+
// show a green toast ONLY when the browser is genuinely started and visible.
|
|
460
|
+
//
|
|
461
|
+
// visible: true requires POSITIVE evidence:
|
|
462
|
+
// - launchPersistentContext succeeded
|
|
463
|
+
// - page exists and is not closed
|
|
464
|
+
// - page.bringToFront() succeeded
|
|
465
|
+
// - on Windows: the intended Chrome process was identified and
|
|
466
|
+
// SetForegroundWindow succeeded (or on non-Windows: bringToFront is
|
|
467
|
+
// sufficient)
|
|
468
|
+
//
|
|
469
|
+
// If the Windows foreground helper cannot prove the window is visible
|
|
470
|
+
// (foregroundVerified = false), we return started:true but visible:false
|
|
471
|
+
// with an actionable error so the frontend does NOT show a green toast.
|
|
472
|
+
if (os.platform() === 'win32' && !foregroundVerified) {
|
|
473
|
+
// The browser launched and bringToFront succeeded, but we could not
|
|
474
|
+
// positively verify the window is in the foreground. Return a safe
|
|
475
|
+
// actionable message — NOT a green toast.
|
|
476
|
+
return {
|
|
477
|
+
success: true,
|
|
478
|
+
accountId,
|
|
479
|
+
started: true,
|
|
480
|
+
visible: false,
|
|
481
|
+
sessionId: accountId,
|
|
482
|
+
error: 'Browser launched but could not be confirmed in the foreground. Check the taskbar for the Chrome window.',
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
return {
|
|
487
|
+
success: true,
|
|
488
|
+
accountId,
|
|
489
|
+
started: true,
|
|
490
|
+
visible: true,
|
|
491
|
+
sessionId: accountId,
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
async function _stopSession(accountId, lease) {
|
|
496
|
+
const session = activeSessions.get(accountId);
|
|
497
|
+
if (!session) return { success: false, error: 'Session not found' };
|
|
498
|
+
try { await session.context.close(); } catch {}
|
|
499
|
+
activeSessions.delete(accountId);
|
|
500
|
+
return { success: true, accountId, stopped: true };
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
async function _refreshSession(accountId) {
|
|
504
|
+
const session = activeSessions.get(accountId);
|
|
505
|
+
if (!session) return { success: false, error: 'Session not found' };
|
|
506
|
+
await session.page.reload();
|
|
507
|
+
return { success: true };
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
async function _navigate(accountId, url) {
|
|
511
|
+
const session = activeSessions.get(accountId);
|
|
512
|
+
if (!session) return { success: false, error: 'Session not found' };
|
|
513
|
+
await session.page.goto(url, { waitUntil: 'domcontentloaded' });
|
|
514
|
+
return { success: true };
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
async function _typeText(accountId, selector, text) {
|
|
518
|
+
const session = activeSessions.get(accountId);
|
|
519
|
+
if (!session) return { success: false, error: 'Session not found' };
|
|
520
|
+
await session.page.locator(selector).fill(text);
|
|
521
|
+
return { success: true };
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
async function _pressKey(accountId, key) {
|
|
525
|
+
const session = activeSessions.get(accountId);
|
|
526
|
+
if (!session) return { success: false, error: 'Session not found' };
|
|
527
|
+
await session.page.keyboard.press(key);
|
|
528
|
+
return { success: true };
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
async function _click(accountId, selector) {
|
|
532
|
+
const session = activeSessions.get(accountId);
|
|
533
|
+
if (!session) return { success: false, error: 'Session not found' };
|
|
534
|
+
await session.page.locator(selector).click();
|
|
535
|
+
return { success: true };
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
async function _focusSession(accountId) {
|
|
539
|
+
const session = activeSessions.get(accountId);
|
|
540
|
+
if (!session) return { success: false, error: 'Session not found' };
|
|
541
|
+
await session.page.bringToFront();
|
|
542
|
+
return { success: true };
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
async function _runAction(accountId, action, payload) {
|
|
546
|
+
const session = activeSessions.get(accountId);
|
|
547
|
+
if (!session) return { success: false, error: 'Session not found' };
|
|
548
|
+
const { runAction } = require('./actions');
|
|
549
|
+
const result = await runAction(session.page, action, payload || {});
|
|
550
|
+
return { success: true, result };
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function _getStatus() {
|
|
554
|
+
const sessions = [];
|
|
555
|
+
for (const [accountId, session] of activeSessions) {
|
|
556
|
+
sessions.push({ accountId, url: session.page ? session.page.url() : null });
|
|
557
|
+
}
|
|
558
|
+
return { success: true, sessions, count: sessions.length };
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function _importLegacyProfile(accountId, accountUuid, opts) {
|
|
562
|
+
// Defect 9 fix: pass opts correctly (was undefined before).
|
|
563
|
+
const result = importLegacyProfile(accountId, {
|
|
564
|
+
profileRoot: PROFILES_DIR,
|
|
565
|
+
deviceUuid: opts.deviceMeta.deviceId,
|
|
566
|
+
accountUuid,
|
|
567
|
+
});
|
|
568
|
+
return { success: true, result };
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
function _discoverLegacyProfiles() {
|
|
572
|
+
const profiles = discoverLegacyProfiles(PROFILES_DIR);
|
|
573
|
+
return { success: true, profiles };
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
577
|
+
|
|
578
|
+
function _extractEcho(msg) {
|
|
579
|
+
const echo = {};
|
|
580
|
+
if (msg.nonce) echo.nonce = msg.nonce;
|
|
581
|
+
if (msg.leaseId) echo.leaseId = msg.leaseId;
|
|
582
|
+
if (msg.accountUuid) echo.accountUuid = msg.accountUuid;
|
|
583
|
+
return echo;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
function _sendResponse(ws, msg, result, echo) {
|
|
587
|
+
try {
|
|
588
|
+
ws.send(JSON.stringify({
|
|
589
|
+
type: 'command-response',
|
|
590
|
+
commandId: msg.commandId,
|
|
591
|
+
result,
|
|
592
|
+
...(echo || _extractEcho(msg)),
|
|
593
|
+
}));
|
|
594
|
+
} catch {}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function _parseProxy(proxyStr) {
|
|
598
|
+
if (!proxyStr || typeof proxyStr !== 'string') return null;
|
|
599
|
+
const parts = proxyStr.split(':');
|
|
600
|
+
if (parts.length >= 2) {
|
|
601
|
+
const proxy = { server: `http://${parts[0]}:${parts[1]}` };
|
|
602
|
+
if (parts[2] && parts[3]) {
|
|
603
|
+
proxy.username = parts[2];
|
|
604
|
+
proxy.password = parts[3];
|
|
605
|
+
}
|
|
606
|
+
return proxy;
|
|
607
|
+
}
|
|
608
|
+
return null;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
function _safeError(err) {
|
|
612
|
+
const msg = err && err.message ? err.message : String(err);
|
|
613
|
+
return msg
|
|
614
|
+
.replace(/[A-Fa-f0-9]{64}/g, '<hex>')
|
|
615
|
+
.replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, '<jwt>')
|
|
616
|
+
.slice(0, 500);
|
|
617
|
+
}
|
|
618
|
+
|
|
453
619
|
module.exports = { setupSessionHandler, activeSessions, closeAllSessions, markDisconnected };
|