@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.
@@ -1,754 +1,754 @@
1
- 'use strict';
2
-
3
- /**
4
- * Shared helpers for Local Agent actions.
5
- * Ported from src/helpers.js + src/stageDetector.js + src/totp.js
6
- */
7
-
8
- // ── Sleep / delay ────────────────────────────────────────────────────────────
9
- function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
10
- function humanDelay(min = 80, max = 180) { return sleep(Math.floor(min + Math.random() * (max - min))); }
11
- function randDelay(min, max) { return sleep(Math.floor(min + Math.random() * (max - min))); }
12
-
13
- // ── Locator helpers ─────────────────────────────────────────────────────────
14
- async function isLocatorVisible(locator, timeout = 1000) {
15
- try { return await locator.first().isVisible({ timeout }); } catch { return false; }
16
- }
17
-
18
- async function safeFill(page, locator, value, options = {}) {
19
- const delayMin = options.delayMin || 50;
20
- const delayMax = options.delayMax || 150;
21
- const el = typeof locator === 'string' ? page.locator(locator).first() : locator;
22
- await el.waitFor({ state: 'visible', timeout: 10000 });
23
- await el.click();
24
- await page.keyboard.press('Control+a');
25
- await page.keyboard.press('Backspace');
26
- await humanDelay(delayMin, delayMax);
27
- // Humanized typing instead of instant fill()
28
- await humanType(page, value, { delayMin, delayMax });
29
- await humanDelay(delayMin, delayMax);
30
- }
31
-
32
- /**
33
- * Humanized typing — types character by character with randomized delays,
34
- * occasional pauses (thinking), and rare typos+corrections.
35
- */
36
- async function humanType(page, text, options = {}) {
37
- const delayMin = options.delayMin || 50;
38
- const delayMax = options.delayMax || 150;
39
- const pauseChance = options.pauseChance || 0.05;
40
- const typoChance = options.typoChance || 0.01;
41
-
42
- // Typing burst model: real users type in bursts of 3-8 chars fast, then pause
43
- const commonWords = ['the', 'and', 'you', 'http', 'https', 'com', 'www', 'this', 'that', 'with', 'have', 'from', 'they', 'will', 'your', 'what', 'some', 'them', 'then', 'than', 'look',
44
- // Arabic common words
45
- 'في', 'من', 'على', 'إلى', 'عن', 'مع', 'هذا', 'هذه', 'التي', 'الذي', 'كان', 'قد', 'ما', 'لا', 'إن', 'أو', 'ثم', 'بل', 'لكن'
46
- ];
47
- let burstRemaining = 0;
48
- let burstSpeed = 1;
49
- let lastMouseMoveTime = 0;
50
-
51
- for (let i = 0; i < text.length; i++) {
52
- const ch = text[i];
53
-
54
- // Check if we're starting a new word
55
- if (ch === ' ' || ch === '.' || ch === ',' || ch === '/' || ch === ':' || ch === '|' || ch === '،' || ch === '؛') {
56
- const upcoming = text.slice(i + 1, i + 8).toLowerCase();
57
- const isCommon = commonWords.some(w => upcoming.startsWith(w));
58
- burstRemaining = isCommon ? 5 + Math.floor(Math.random() * 4) : 2 + Math.floor(Math.random() * 4);
59
- burstSpeed = isCommon ? 0.5 + Math.random() * 0.3 : 0.8 + Math.random() * 0.6;
60
- }
61
-
62
- // Rare typo: type wrong char, wait, delete, type correct
63
- if (Math.random() < typoChance && ch.match(/[a-z]/i)) {
64
- const wrongChar = String.fromCharCode(ch.charCodeAt(0) + (Math.random() < 0.5 ? 1 : -1));
65
- await page.keyboard.type(wrongChar, { delay: delayMin });
66
- await sleep(100 + Math.random() * 300);
67
- await page.keyboard.press('Backspace');
68
- await sleep(50 + Math.random() * 100);
69
- }
70
-
71
- // Burst typing: faster delay when in a burst
72
- const charDelay = burstRemaining > 0
73
- ? (delayMin + Math.random() * (delayMax - delayMin)) * burstSpeed
74
- : delayMin + Math.random() * (delayMax - delayMin);
75
- await page.keyboard.type(ch, { delay: charDelay });
76
- if (burstRemaining > 0) burstRemaining--;
77
-
78
- // Occasional longer pause (simulating thinking/reading)
79
- if (Math.random() < pauseChance) {
80
- await sleep(500 + Math.random() * 1500);
81
- }
82
-
83
- // Occasional mid-word pause (hesitation)
84
- if (Math.random() < 0.02 && ch.match(/[a-z]/i)) {
85
- await sleep(200 + Math.random() * 400);
86
- }
87
-
88
- // Occasional mouse movement while typing (real users sometimes move mouse while typing)
89
- if (Date.now() - lastMouseMoveTime > 5000 && Math.random() < 0.1) {
90
- try {
91
- const vp = page.viewportSize();
92
- if (vp) {
93
- await page.mouse.move(vp.width * (0.3 + Math.random() * 0.4), vp.height * (0.3 + Math.random() * 0.4), { steps: 3 });
94
- lastMouseMoveTime = Date.now();
95
- }
96
- } catch {}
97
- }
98
-
99
- // Occasional backspace + retype (user corrects themselves)
100
- if (Math.random() < 0.005 && i > 0 && ch.match(/[a-z]/i)) {
101
- await page.keyboard.press('Backspace');
102
- await sleep(100 + Math.random() * 200);
103
- await page.keyboard.type(ch, { delay: charDelay });
104
- }
105
- }
106
- }
107
-
108
- /**
109
- * Humanized click — moves mouse in a bezier curve to the element before clicking.
110
- * Click position has wide variance (not always center) to look natural.
111
- */
112
- async function humanClick(page, locator) {
113
- const el = typeof locator === 'string' ? page.locator(locator).first() : locator;
114
- await el.waitFor({ state: 'visible', timeout: 10000 });
115
- await el.scrollIntoViewIfNeeded();
116
- await humanDelay(100, 300);
117
-
118
- try {
119
- const box = await el.boundingBox();
120
- if (box) {
121
- // Start from a random nearby position (not always from same area)
122
- const startX = box.x + box.width * (0.1 + Math.random() * 0.8);
123
- const startY = box.y + box.height * (0.1 + Math.random() * 0.8);
124
- // Wider click variance — real users don't always click dead center
125
- const endX = box.x + box.width * (0.15 + Math.random() * 0.7);
126
- const endY = box.y + box.height * (0.15 + Math.random() * 0.7);
127
-
128
- // Pre-click: hover over the element first (real users hover before clicking)
129
- await page.mouse.move(startX, startY, { steps: 3 + Math.floor(Math.random() * 4) });
130
- await humanDelay(100, 400); // Hover delay — reading the button
131
-
132
- // Move in 4-7 steps with slight curve (bezier-like) — more steps = smoother
133
- const steps = 4 + Math.floor(Math.random() * 4);
134
- for (let i = 1; i <= steps; i++) {
135
- const t = i / steps;
136
- const ctrlX = (startX + endX) / 2 + (Math.random() - 0.5) * 60;
137
- const ctrlY = (startY + endY) / 2 + (Math.random() - 0.5) * 60;
138
- const x = (1 - t) * (1 - t) * startX + 2 * (1 - t) * t * ctrlX + t * t * endX;
139
- const y = (1 - t) * (1 - t) * startY + 2 * (1 - t) * t * ctrlY + t * t * endY;
140
- await page.mouse.move(x, y, { steps: 1 });
141
- await sleep(15 + Math.random() * 35);
142
- }
143
-
144
- // Brief pause at target before clicking (mouse settles)
145
- await humanDelay(50, 200);
146
-
147
- // Click with button press/release timing (real clicks have duration)
148
- await page.mouse.click(endX, endY);
149
-
150
- // Post-click: sometimes move mouse away immediately, sometimes linger
151
- if (Math.random() < 0.3) {
152
- await humanDelay(200, 600); // Linger on the clicked element
153
- } else {
154
- // Move away slowly
155
- await page.mouse.move(endX + (Math.random() - 0.5) * 100, endY + (Math.random() - 0.5) * 100, { steps: 3 });
156
- }
157
-
158
- // Rare double-click (real users sometimes double-click by accident)
159
- if (Math.random() < 0.02) {
160
- await humanDelay(100, 300);
161
- await page.mouse.click(endX, endY);
162
- }
163
-
164
- return;
165
- }
166
- } catch {}
167
-
168
- // Fallback: use page.mouse.click at element center (still produces trusted events)
169
- // Never use element.click() — it produces isTrusted:false events that Twitter detects
170
- try {
171
- const box = await el.boundingBox();
172
- if (box) {
173
- await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
174
- return;
175
- }
176
- } catch {}
177
- // Last resort: use Playwright's click (dispatches real mouse events, trusted)
178
- await humanDelay(50, 150);
179
- await el.click({ timeout: 5000 }).catch(() => {});
180
- }
181
-
182
- async function safeClick(page, locator) {
183
- return humanClick(page, locator);
184
- }
185
-
186
- async function getBodyText(page) {
187
- try { return (await page.evaluate(() => document.body.innerText)).toLowerCase(); }
188
- catch { return ''; }
189
- }
190
-
191
- /**
192
- * Log-normal random delay — models real human dwell time better than uniform.
193
- * Most pauses are short (2-5s), but occasionally a user reads for 20-30s.
194
- * @param {number} median - median delay in ms (default 3000)
195
- * @returns {Promise} sleep promise
196
- */
197
- function logNormalDelay(median = 3000) {
198
- // Log-normal distribution: median * exp(sigma * N(0,1))
199
- const sigma = 0.8;
200
- const u1 = Math.random();
201
- const u2 = Math.random();
202
- const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
203
- const delay = median * Math.exp(sigma * z);
204
- // Clamp to reasonable bounds
205
- return sleep(Math.min(Math.max(delay, 500), 60000));
206
- }
207
-
208
- /**
209
- * Session warm-up — simulates what a real user does when they first open X:
210
- * scroll the feed, hover over tweets, maybe click a profile, read content.
211
- * This should run after browser start, before the first action.
212
- */
213
- async function sessionWarmup(page, durationMs = 8000) {
214
- const startTime = Date.now();
215
- const viewport = page.viewportSize();
216
-
217
- // 1. Initial pause — user just opened the app, looking at feed
218
- await logNormalDelay(2000);
219
-
220
- // 2. Check notifications (real users check notifications first)
221
- await humanCheckNotifications(page);
222
-
223
- while (Date.now() - startTime < durationMs) {
224
- const action = Math.random();
225
-
226
- if (action < 0.25) {
227
- // Scroll down the feed with variable speed
228
- try {
229
- const scrollAmt = 100 + Math.floor(Math.random() * 500);
230
- await humanScroll(page, scrollAmt);
231
- } catch {}
232
- await logNormalDelay(2000);
233
- } else if (action < 0.40) {
234
- // Hover over a tweet and read it
235
- try {
236
- if (viewport) {
237
- const x = viewport.width * (0.2 + Math.random() * 0.6);
238
- const y = viewport.height * (0.2 + Math.random() * 0.5);
239
- await page.mouse.move(x, y, { steps: 5 + Math.floor(Math.random() * 8) });
240
- await logNormalDelay(2000);
241
- }
242
- } catch {}
243
- } else if (action < 0.50) {
244
- // Read a tweet in detail (longer hover + micro-scroll)
245
- await humanReadTweet(page, 4000 + Math.random() * 4000);
246
- } else if (action < 0.60) {
247
- // Scroll back up using mouse wheel
248
- try {
249
- await humanScroll(page, -(100 + Math.random() * 300));
250
- } catch {}
251
- await logNormalDelay(1800);
252
- } else if (action < 0.68) {
253
- // Keyboard scroll (Space / PageDown / ArrowDown)
254
- const keyChoice = Math.random();
255
- if (keyChoice < 0.5) await keyboardScroll(page, 'down');
256
- else {
257
- await page.keyboard.press('ArrowDown');
258
- await sleep(100 + Math.random() * 200);
259
- await page.keyboard.press('ArrowDown');
260
- }
261
- await logNormalDelay(1500);
262
- } else if (action < 0.75) {
263
- // Idle mouse jitter (reading) with micro-tremor
264
- await idleMouseJitter(page, 2000 + Math.random() * 2000);
265
- } else if (action < 0.80) {
266
- // Occasional Tab navigation
267
- await occasionalTabNavigation(page);
268
- await logNormalDelay(1000);
269
- } else if (action < 0.84) {
270
- // Rare window resize
271
- await occasionalResize(page);
272
- await logNormalDelay(1500);
273
- } else if (action < 0.90) {
274
- // Check notifications again
275
- await humanCheckNotifications(page);
276
- await logNormalDelay(1000);
277
- } else if (action < 0.95) {
278
- // Hover over sidebar items (Home, Explore, etc.)
279
- try {
280
- const sidebarItems = page.locator('nav a, nav [role="link"]').first();
281
- if (await sidebarItems.isVisible({ timeout: 1000 }).catch(() => false)) {
282
- await humanHover(page, sidebarItems);
283
- }
284
- } catch {}
285
- await logNormalDelay(800);
286
- } else {
287
- // Brief pause (thinking / distracted)
288
- await logNormalDelay(3000);
289
- }
290
- }
291
- }
292
-
293
- /**
294
- * Human-like hover over an element — moves mouse to it, hovers, then moves away.
295
- * Real users hover over tweets/links before clicking them.
296
- */
297
- async function humanHover(page, locator) {
298
- try {
299
- const el = typeof locator === 'string' ? page.locator(locator).first() : locator;
300
- const box = await el.boundingBox();
301
- if (!box) return;
302
- const x = box.x + box.width * (0.2 + Math.random() * 0.6);
303
- const y = box.y + box.height * (0.2 + Math.random() * 0.6);
304
- // Move to the element with a curve
305
- const steps = 3 + Math.floor(Math.random() * 4);
306
- await page.mouse.move(x, y, { steps });
307
- // Hover for a realistic duration (reading the content)
308
- await logNormalDelay(800);
309
- // Sometimes move away
310
- if (Math.random() < 0.5) {
311
- await page.mouse.move(x + (Math.random() - 0.5) * 80, y + (Math.random() - 0.5) * 80, { steps: 3 });
312
- }
313
- } catch {}
314
- }
315
-
316
- /**
317
- * Human-like reading of a tweet — hover over it, scroll slightly, pause.
318
- * Simulates a user reading the content before acting.
319
- */
320
- async function humanReadTweet(page, durationMs = 5000) {
321
- const viewport = page.viewportSize();
322
- if (!viewport) return;
323
- // Hover over the middle of the viewport (where tweets usually are)
324
- const tweetX = viewport.width * (0.3 + Math.random() * 0.4);
325
- const tweetY = viewport.height * (0.3 + Math.random() * 0.3);
326
- await page.mouse.move(tweetX, tweetY, { steps: 5 + Math.floor(Math.random() * 5) });
327
- // Read for a while (log-normal: usually 3-8s, sometimes 15-20s)
328
- await logNormalDelay(durationMs * 0.6);
329
- // Slight scroll while reading
330
- if (Math.random() < 0.4) {
331
- await humanScroll(page, 30 + Math.random() * 80);
332
- await logNormalDelay(durationMs * 0.3);
333
- }
334
- // Mouse micro-movements while reading
335
- await idleMouseJitter(page, durationMs * 0.2);
336
- }
337
-
338
- /**
339
- * Check notifications — real users check their notifications bell.
340
- */
341
- async function humanCheckNotifications(page) {
342
- try {
343
- // Look for the notifications bell/link
344
- const notifLink = page.locator('a[href*="/notifications"], a[aria-label*="Notification"], a[data-testid="AppTabBar_Notifications_Link"]').first();
345
- if (await notifLink.isVisible({ timeout: 2000 }).catch(() => false)) {
346
- await humanHover(page, notifLink);
347
- await logNormalDelay(1500);
348
- // Don't actually click — just hover (less suspicious)
349
- }
350
- } catch {}
351
- }
352
-
353
- // ── Navigation ──────────────────────────────────────────────────────────────
354
- async function naturalNavigate(page, targetUrl, options = {}) {
355
- const currentUrl = page.url();
356
- // Normalize for comparison (strip trailing slashes and query params)
357
- const normCurrent = currentUrl.split('?')[0].replace(/\/+$/, '');
358
- const normTarget = targetUrl.split('?')[0].replace(/\/+$/, '');
359
- if (normCurrent === normTarget || normCurrent.includes(normTarget) || normTarget.includes(normCurrent)) {
360
- await humanDelay(500, 1200);
361
- return;
362
- }
363
-
364
- // ── Referrer chain: simulate arriving from the feed, not direct navigation ─
365
- // Real users click tweets from their feed — they don't paste URLs directly.
366
- // If we're on x.com already, the referrer will be natural.
367
- // If we're on a blank page or non-x.com page, navigate to home first.
368
- const isOnX = currentUrl.includes('x.com') || currentUrl.includes('twitter.com');
369
- if (!isOnX) {
370
- try {
371
- await page.goto('https://x.com/home', { waitUntil: 'domcontentloaded', timeout: 30000 });
372
- await page.waitForLoadState('networkidle', { timeout: 8000 }).catch(() => {});
373
- await logNormalDelay(2000);
374
- } catch {}
375
- }
376
-
377
- const waitUntil = options.waitUntil || 'domcontentloaded';
378
- const timeout = options.timeout || 45000;
379
- try {
380
- await page.goto(targetUrl, { waitUntil, timeout, referer: isOnX ? currentUrl : 'https://x.com/home' });
381
- } catch (e) {
382
- // If it's a timeout but page might still be loading content, don't crash
383
- console.log(`[naturalNavigate] goto warning: ${e.message}`);
384
- }
385
- // Wait for network to settle (X is a SPA — content loads after DOMContentLoaded)
386
- try {
387
- await page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {});
388
- } catch {}
389
- await randDelay(1500, 3000);
390
- }
391
-
392
- async function humanPreAction(page, accountId = 0) {
393
- // Random scroll + delay to simulate human behavior
394
- // Use mouse wheel event (produces real wheel events, not just JS scroll)
395
- try {
396
- await humanScroll(page, 100 + Math.random() * 200);
397
- } catch {}
398
- await randDelay(800, 1800);
399
- }
400
-
401
- /**
402
- * Human-like scroll using mouse wheel events (fires real 'wheel' events).
403
- * Real users scroll with the mouse wheel, not JS scrollBy().
404
- * @param {number} deltaY - pixels to scroll (positive = down, negative = up)
405
- */
406
- async function humanScroll(page, deltaY = 300) {
407
- try {
408
- // Variable speed scrolling — real users scroll at different speeds
409
- // Sometimes fast flick, sometimes slow drag
410
- const isFastFlick = Math.random() < 0.3;
411
- const stepDelay = isFastFlick ? 10 + Math.random() * 15 : 25 + Math.random() * 50;
412
- const steps = Math.ceil(Math.abs(deltaY) / (isFastFlick ? 200 : 120));
413
- const stepSize = deltaY / steps;
414
-
415
- // Momentum scrolling — start slow, speed up, slow down (like a real flick)
416
- for (let i = 0; i < steps; i++) {
417
- const progress = i / steps;
418
- // Ease-in-out: slow at start and end, fast in middle
419
- const momentum = 0.5 + 0.5 * Math.sin(progress * Math.PI);
420
- const adjustedStep = stepSize * (0.3 + momentum * 0.7);
421
- await page.mouse.wheel(0, adjustedStep);
422
- await sleep(stepDelay * (1 - momentum * 0.5)); // Faster in the middle
423
- }
424
-
425
- // Sometimes overshoot and scroll back slightly (real users overshoot)
426
- if (Math.random() < 0.15 && Math.abs(deltaY) > 200) {
427
- await sleep(100 + Math.random() * 200);
428
- await page.mouse.wheel(0, -deltaY * 0.05);
429
- }
430
- } catch {
431
- try { await page.evaluate((dy) => window.scrollBy(0, dy), deltaY); } catch {}
432
- }
433
- }
434
-
435
- /**
436
- * Keyboard-based scrolling — real users use Space, Page Down, arrow keys.
437
- */
438
- async function keyboardScroll(page, direction = 'down') {
439
- try {
440
- const key = direction === 'down' ? 'Space' : 'PageUp';
441
- await page.keyboard.press(key);
442
- await sleep(100 + Math.random() * 200);
443
- } catch {}
444
- }
445
-
446
- /**
447
- * Occasional Tab key navigation — real users sometimes Tab through elements.
448
- */
449
- async function occasionalTabNavigation(page) {
450
- try {
451
- const tabCount = 1 + Math.floor(Math.random() * 3);
452
- for (let i = 0; i < tabCount; i++) {
453
- await page.keyboard.press('Tab');
454
- await sleep(50 + Math.random() * 150);
455
- }
456
- // Shift+Tab back
457
- if (Math.random() < 0.5) {
458
- await page.keyboard.press('Shift+Tab');
459
- await sleep(50 + Math.random() * 100);
460
- }
461
- } catch {}
462
- }
463
-
464
- /**
465
- * Rare window resize — real users occasionally resize their browser.
466
- */
467
- async function occasionalResize(page) {
468
- try {
469
- const viewport = page.viewportSize();
470
- if (!viewport) return;
471
- // Small resize (±50px) — not dramatic
472
- const newWidth = viewport.width + Math.floor((Math.random() - 0.5) * 100);
473
- const newHeight = viewport.height + Math.floor((Math.random() - 0.5) * 100);
474
- await page.setViewportSize({ width: newWidth, height: newHeight });
475
- await sleep(500 + Math.random() * 1000);
476
- // Resize back
477
- await page.setViewportSize({ width: viewport.width, height: viewport.height });
478
- } catch {}
479
- }
480
-
481
- /**
482
- * Idle mouse jitter — simulates micro-movements a real user makes
483
- * while reading/looking at the screen (not perfectly still).
484
- * Call during waits to keep the session looking alive.
485
- */
486
- async function idleMouseJitter(page, durationMs = 2000) {
487
- const startTime = Date.now();
488
- const viewport = page.viewportSize();
489
- if (!viewport) return;
490
- // Track last position for micro-tremor simulation
491
- let lastX = viewport.width / 2;
492
- let lastY = viewport.height / 2;
493
- while (Date.now() - startTime < durationMs) {
494
- try {
495
- // Micro-tremor: small movements near last position (like a hand holding a mouse)
496
- if (Math.random() < 0.6) {
497
- const tremorX = lastX + (Math.random() - 0.5) * 30;
498
- const tremorY = lastY + (Math.random() - 0.5) * 30;
499
- await page.mouse.move(tremorX, tremorY, { steps: 1 });
500
- lastX = tremorX;
501
- lastY = tremorY;
502
- await sleep(200 + Math.random() * 500);
503
- } else {
504
- // Occasional larger movement to a new area
505
- lastX = viewport.width * (0.2 + Math.random() * 0.6);
506
- lastY = viewport.height * (0.2 + Math.random() * 0.6);
507
- await page.mouse.move(lastX, lastY, { steps: 3 + Math.floor(Math.random() * 5) });
508
- await sleep(300 + Math.random() * 800);
509
- }
510
- } catch { break; }
511
- }
512
- }
513
-
514
- /**
515
- * Human-like post-action behavior — simulates what a real user does after
516
- * performing an action: pause, scroll, maybe move mouse, browse a bit.
517
- * This runs BEFORE the browser closes so the session doesn't look robotic
518
- * (action → instant close).
519
- */
520
- async function humanPostAction(page) {
521
- // 1. Brief pause — user reads the result of their action (with idle mouse jitter + micro-tremor)
522
- await idleMouseJitter(page, 1500 + Math.random() * 2500);
523
-
524
- // 2. Random scroll down (reading the timeline) — use mouse wheel with momentum
525
- try {
526
- const scrollAmount = 100 + Math.floor(Math.random() * 400);
527
- await humanScroll(page, scrollAmount);
528
- } catch {}
529
- await idleMouseJitter(page, 1000 + Math.random() * 1500);
530
-
531
- // 3. Sometimes read a tweet in detail
532
- if (Math.random() < 0.3) {
533
- await humanReadTweet(page, 3000 + Math.random() * 5000);
534
- }
535
-
536
- // 4. Sometimes scroll back up
537
- if (Math.random() < 0.4) {
538
- try {
539
- await humanScroll(page, -(150 + Math.random() * 300));
540
- } catch {}
541
- await idleMouseJitter(page, 800 + Math.random() * 1200);
542
- }
543
-
544
- // 5. Random mouse movement (like user is looking around)
545
- try {
546
- const viewport = page.viewportSize();
547
- if (viewport) {
548
- const steps = 2 + Math.floor(Math.random() * 3);
549
- for (let i = 0; i < steps; i++) {
550
- const x = Math.random() * viewport.width;
551
- const y = Math.random() * viewport.height;
552
- await page.mouse.move(x, y, { steps: 3 + Math.floor(Math.random() * 5) });
553
- await sleep(200 + Math.random() * 500);
554
- }
555
- }
556
- } catch {}
557
-
558
- // 6. Sometimes check notifications (real users check after posting)
559
- if (Math.random() < 0.25) {
560
- await humanCheckNotifications(page);
561
- await logNormalDelay(1500);
562
- }
563
-
564
- // 7. Sometimes navigate to home page (like user checking their feed after posting)
565
- if (Math.random() < 0.3) {
566
- try {
567
- await page.goto('https://x.com/home', { waitUntil: 'domcontentloaded', timeout: 15000 }).catch(() => {});
568
- await page.waitForLoadState('networkidle', { timeout: 8000 }).catch(() => {});
569
- await idleMouseJitter(page, 2000 + Math.random() * 3000);
570
- // Scroll the feed using mouse wheel with momentum
571
- await humanScroll(page, 200 + Math.random() * 300);
572
- await idleMouseJitter(page, 1000 + Math.random() * 1500);
573
- // Maybe read a tweet
574
- if (Math.random() < 0.4) {
575
- await humanReadTweet(page, 3000 + Math.random() * 3000);
576
- }
577
- } catch {}
578
- }
579
-
580
- // 8. Sometimes visit own profile (like user checking how their profile looks)
581
- if (Math.random() < 0.15) {
582
- try {
583
- // Click on the profile link in the sidebar
584
- const profileLink = page.locator('a[href*="/profile"], [data-testid="AppTabBar_Profile_Link"]').first();
585
- if (await profileLink.isVisible({ timeout: 2000 }).catch(() => false)) {
586
- await humanHover(page, profileLink);
587
- await logNormalDelay(1000);
588
- }
589
- } catch {}
590
- }
591
-
592
- // 9. Final pause before closing — log-normal: usually 2-5s, occasionally 15-30s
593
- await logNormalDelay(3000);
594
- }
595
-
596
- // ── TOTP ───────────────────────────────────────────────────────────────────
597
- function generateTOTP(secret) {
598
- const OTPAuth = require('otpauth');
599
- const normalized = String(secret || '').replace(/\s+/g, '').toUpperCase();
600
- if (!normalized) throw new Error('Missing TOTP secret');
601
- const totp = new OTPAuth.TOTP({
602
- algorithm: 'SHA1', digits: 6, period: 30,
603
- secret: OTPAuth.Secret.fromBase32(normalized),
604
- });
605
- return totp.generate();
606
- }
607
-
608
- // ── Stage detection (simplified from src/stageDetector.js) ──────────────────
609
- const SELECTORS = {
610
- usernameInput: 'input[autocomplete="username"]',
611
- passwordInput: 'input[type="password"]',
612
- nextButton: 'button:has-text("Next")',
613
- loginButton: 'button[data-testid="LoginForm_Login_Button"]',
614
- twoFactorInput: 'input[name="text"]',
615
- homeIndicator: '[data-testid="SideNav_NewTweet_Button"]',
616
- tweetButton: '[data-testid="tweetButton"]',
617
- primaryColumn: '[data-testid="primaryColumn"]',
618
- };
619
-
620
- async function detectStage(page) {
621
- try {
622
- const url = page.url();
623
- if (url.includes('/login') || url.includes('/i/flow/login')) {
624
- // Check if username or password step
625
- const hasUsername = await isLocatorVisible(page.locator(SELECTORS.usernameInput));
626
- const hasPassword = await isLocatorVisible(page.locator(SELECTORS.passwordInput));
627
- if (hasPassword) return 'login_password_step';
628
- if (hasUsername) return 'login_username_step';
629
- return 'login_required';
630
- }
631
- // Check if logged in
632
- const hasHome = await isLocatorVisible(page.locator(SELECTORS.homeIndicator), 3000);
633
- const hasPrimary = await isLocatorVisible(page.locator(SELECTORS.primaryColumn), 3000);
634
- if (hasHome || hasPrimary) return 'home_logged_in';
635
- return 'unknown';
636
- } catch { return 'unknown'; }
637
- }
638
-
639
- async function waitForLoggedIn(page, options = {}) {
640
- const timeoutMs = options.timeoutMs || 22000;
641
- const intervalMs = options.intervalMs || 1000;
642
- const start = Date.now();
643
- while (Date.now() - start < timeoutMs) {
644
- const stage = await detectStage(page);
645
- if (stage === 'home_logged_in') return true;
646
- if (stage === 'checkpoint' || stage === 'login_username_step' || stage === 'login_password_step') return false;
647
- await sleep(intervalMs);
648
- }
649
- return false;
650
- }
651
-
652
- // ── Cookie helpers ──────────────────────────────────────────────────────────
653
- async function injectCookies(context, cookiesData) {
654
- if (!cookiesData) return;
655
- try {
656
- let cookies = [];
657
- if (typeof cookiesData === 'string') {
658
- try { cookies = JSON.parse(cookiesData); }
659
- catch { try { cookies = JSON.parse(Buffer.from(cookiesData, 'base64').toString()); } catch {} }
660
- } else if (Array.isArray(cookiesData)) {
661
- cookies = cookiesData;
662
- }
663
- if (!cookies.length) return;
664
- const normalized = cookies.map(c => ({
665
- name: c.name, value: c.value,
666
- domain: c.domain || '.x.com', path: c.path || '/',
667
- expires: c.expires || -1, httpOnly: c.httpOnly !== false,
668
- secure: c.secure !== false, sameSite: c.sameSite || 'Lax',
669
- }));
670
- await context.addCookies(normalized);
671
- } catch {}
672
- }
673
-
674
- async function saveCookies(context) {
675
- try { return await context.cookies(); } catch { return []; }
676
- }
677
-
678
- // ── Proxy parsing ───────────────────────────────────────────────────────────
679
- function parseProxy(proxyStr) {
680
- if (!proxyStr || !proxyStr.trim()) return undefined;
681
- const parts = proxyStr.trim().split(':');
682
- if (parts.length >= 4) {
683
- const [host, port, user, ...passParts] = parts;
684
- return { server: `http://${host}:${port}`, username: user, password: passParts.join(':') };
685
- } else if (parts.length === 2) {
686
- return { server: `http://${host}:${port}` };
687
- }
688
- return undefined;
689
- }
690
-
691
- module.exports = {
692
- sleep, humanDelay, randDelay,
693
- isLocatorVisible, safeFill, safeClick, humanClick, humanType, getBodyText,
694
- naturalNavigate, humanPreAction, humanPostAction, idleMouseJitter,
695
- logNormalDelay, sessionWarmup,
696
- humanScroll, keyboardScroll, occasionalTabNavigation, occasionalResize,
697
- humanHover, humanReadTweet, humanCheckNotifications,
698
- generateTOTP,
699
- detectStage, waitForLoggedIn, SELECTORS,
700
- injectCookies, saveCookies,
701
- parseProxy,
702
- highlightElement,
703
- };
704
-
705
- /**
706
- * Draw a colored outline around an element so the user can visually see
707
- * what the agent is doing. The outline stays for 2 seconds then fades.
708
- */
709
- async function highlightElement(page, locator, color = 'red', label = '') {
710
- try {
711
- const el = typeof locator === 'string' ? page.locator(locator).first() : locator;
712
- const box = await el.boundingBox();
713
- if (!box) return;
714
- await page.evaluate(({ box, color, label }) => {
715
- const div = document.createElement('div');
716
- div.style.cssText = `
717
- position: fixed;
718
- left: ${box.x - 4}px;
719
- top: ${box.y - 4}px;
720
- width: ${box.width + 8}px;
721
- height: ${box.height + 8}px;
722
- border: 3px solid ${color};
723
- border-radius: 4px;
724
- z-index: 999999;
725
- pointer-events: none;
726
- transition: opacity 0.5s;
727
- box-shadow: 0 0 8px ${color};
728
- `;
729
- if (label) {
730
- const lbl = document.createElement('div');
731
- lbl.textContent = label;
732
- lbl.style.cssText = `
733
- position: fixed;
734
- left: ${box.x - 4}px;
735
- top: ${box.y - 20}px;
736
- background: ${color};
737
- color: white;
738
- padding: 2px 8px;
739
- font-size: 12px;
740
- font-family: sans-serif;
741
- border-radius: 3px;
742
- z-index: 999999;
743
- pointer-events: none;
744
- `;
745
- document.body.appendChild(lbl);
746
- setTimeout(() => { lbl.style.opacity = '0'; }, 2000);
747
- setTimeout(() => lbl.remove(), 3000);
748
- }
749
- document.body.appendChild(div);
750
- setTimeout(() => { div.style.opacity = '0'; }, 2000);
751
- setTimeout(() => div.remove(), 3000);
752
- }, { box, color, label });
753
- } catch {}
1
+ 'use strict';
2
+
3
+ /**
4
+ * Shared helpers for Local Agent actions.
5
+ * Ported from src/helpers.js + src/stageDetector.js + src/totp.js
6
+ */
7
+
8
+ // ── Sleep / delay ────────────────────────────────────────────────────────────
9
+ function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
10
+ function humanDelay(min = 80, max = 180) { return sleep(Math.floor(min + Math.random() * (max - min))); }
11
+ function randDelay(min, max) { return sleep(Math.floor(min + Math.random() * (max - min))); }
12
+
13
+ // ── Locator helpers ─────────────────────────────────────────────────────────
14
+ async function isLocatorVisible(locator, timeout = 1000) {
15
+ try { return await locator.first().isVisible({ timeout }); } catch { return false; }
16
+ }
17
+
18
+ async function safeFill(page, locator, value, options = {}) {
19
+ const delayMin = options.delayMin || 50;
20
+ const delayMax = options.delayMax || 150;
21
+ const el = typeof locator === 'string' ? page.locator(locator).first() : locator;
22
+ await el.waitFor({ state: 'visible', timeout: 10000 });
23
+ await el.click();
24
+ await page.keyboard.press('Control+a');
25
+ await page.keyboard.press('Backspace');
26
+ await humanDelay(delayMin, delayMax);
27
+ // Humanized typing instead of instant fill()
28
+ await humanType(page, value, { delayMin, delayMax });
29
+ await humanDelay(delayMin, delayMax);
30
+ }
31
+
32
+ /**
33
+ * Humanized typing — types character by character with randomized delays,
34
+ * occasional pauses (thinking), and rare typos+corrections.
35
+ */
36
+ async function humanType(page, text, options = {}) {
37
+ const delayMin = options.delayMin || 50;
38
+ const delayMax = options.delayMax || 150;
39
+ const pauseChance = options.pauseChance || 0.05;
40
+ const typoChance = options.typoChance || 0.01;
41
+
42
+ // Typing burst model: real users type in bursts of 3-8 chars fast, then pause
43
+ const commonWords = ['the', 'and', 'you', 'http', 'https', 'com', 'www', 'this', 'that', 'with', 'have', 'from', 'they', 'will', 'your', 'what', 'some', 'them', 'then', 'than', 'look',
44
+ // Arabic common words
45
+ 'في', 'من', 'على', 'إلى', 'عن', 'مع', 'هذا', 'هذه', 'التي', 'الذي', 'كان', 'قد', 'ما', 'لا', 'إن', 'أو', 'ثم', 'بل', 'لكن'
46
+ ];
47
+ let burstRemaining = 0;
48
+ let burstSpeed = 1;
49
+ let lastMouseMoveTime = 0;
50
+
51
+ for (let i = 0; i < text.length; i++) {
52
+ const ch = text[i];
53
+
54
+ // Check if we're starting a new word
55
+ if (ch === ' ' || ch === '.' || ch === ',' || ch === '/' || ch === ':' || ch === '|' || ch === '،' || ch === '؛') {
56
+ const upcoming = text.slice(i + 1, i + 8).toLowerCase();
57
+ const isCommon = commonWords.some(w => upcoming.startsWith(w));
58
+ burstRemaining = isCommon ? 5 + Math.floor(Math.random() * 4) : 2 + Math.floor(Math.random() * 4);
59
+ burstSpeed = isCommon ? 0.5 + Math.random() * 0.3 : 0.8 + Math.random() * 0.6;
60
+ }
61
+
62
+ // Rare typo: type wrong char, wait, delete, type correct
63
+ if (Math.random() < typoChance && ch.match(/[a-z]/i)) {
64
+ const wrongChar = String.fromCharCode(ch.charCodeAt(0) + (Math.random() < 0.5 ? 1 : -1));
65
+ await page.keyboard.type(wrongChar, { delay: delayMin });
66
+ await sleep(100 + Math.random() * 300);
67
+ await page.keyboard.press('Backspace');
68
+ await sleep(50 + Math.random() * 100);
69
+ }
70
+
71
+ // Burst typing: faster delay when in a burst
72
+ const charDelay = burstRemaining > 0
73
+ ? (delayMin + Math.random() * (delayMax - delayMin)) * burstSpeed
74
+ : delayMin + Math.random() * (delayMax - delayMin);
75
+ await page.keyboard.type(ch, { delay: charDelay });
76
+ if (burstRemaining > 0) burstRemaining--;
77
+
78
+ // Occasional longer pause (simulating thinking/reading)
79
+ if (Math.random() < pauseChance) {
80
+ await sleep(500 + Math.random() * 1500);
81
+ }
82
+
83
+ // Occasional mid-word pause (hesitation)
84
+ if (Math.random() < 0.02 && ch.match(/[a-z]/i)) {
85
+ await sleep(200 + Math.random() * 400);
86
+ }
87
+
88
+ // Occasional mouse movement while typing (real users sometimes move mouse while typing)
89
+ if (Date.now() - lastMouseMoveTime > 5000 && Math.random() < 0.1) {
90
+ try {
91
+ const vp = page.viewportSize();
92
+ if (vp) {
93
+ await page.mouse.move(vp.width * (0.3 + Math.random() * 0.4), vp.height * (0.3 + Math.random() * 0.4), { steps: 3 });
94
+ lastMouseMoveTime = Date.now();
95
+ }
96
+ } catch {}
97
+ }
98
+
99
+ // Occasional backspace + retype (user corrects themselves)
100
+ if (Math.random() < 0.005 && i > 0 && ch.match(/[a-z]/i)) {
101
+ await page.keyboard.press('Backspace');
102
+ await sleep(100 + Math.random() * 200);
103
+ await page.keyboard.type(ch, { delay: charDelay });
104
+ }
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Humanized click — moves mouse in a bezier curve to the element before clicking.
110
+ * Click position has wide variance (not always center) to look natural.
111
+ */
112
+ async function humanClick(page, locator) {
113
+ const el = typeof locator === 'string' ? page.locator(locator).first() : locator;
114
+ await el.waitFor({ state: 'visible', timeout: 10000 });
115
+ await el.scrollIntoViewIfNeeded();
116
+ await humanDelay(100, 300);
117
+
118
+ try {
119
+ const box = await el.boundingBox();
120
+ if (box) {
121
+ // Start from a random nearby position (not always from same area)
122
+ const startX = box.x + box.width * (0.1 + Math.random() * 0.8);
123
+ const startY = box.y + box.height * (0.1 + Math.random() * 0.8);
124
+ // Wider click variance — real users don't always click dead center
125
+ const endX = box.x + box.width * (0.15 + Math.random() * 0.7);
126
+ const endY = box.y + box.height * (0.15 + Math.random() * 0.7);
127
+
128
+ // Pre-click: hover over the element first (real users hover before clicking)
129
+ await page.mouse.move(startX, startY, { steps: 3 + Math.floor(Math.random() * 4) });
130
+ await humanDelay(100, 400); // Hover delay — reading the button
131
+
132
+ // Move in 4-7 steps with slight curve (bezier-like) — more steps = smoother
133
+ const steps = 4 + Math.floor(Math.random() * 4);
134
+ for (let i = 1; i <= steps; i++) {
135
+ const t = i / steps;
136
+ const ctrlX = (startX + endX) / 2 + (Math.random() - 0.5) * 60;
137
+ const ctrlY = (startY + endY) / 2 + (Math.random() - 0.5) * 60;
138
+ const x = (1 - t) * (1 - t) * startX + 2 * (1 - t) * t * ctrlX + t * t * endX;
139
+ const y = (1 - t) * (1 - t) * startY + 2 * (1 - t) * t * ctrlY + t * t * endY;
140
+ await page.mouse.move(x, y, { steps: 1 });
141
+ await sleep(15 + Math.random() * 35);
142
+ }
143
+
144
+ // Brief pause at target before clicking (mouse settles)
145
+ await humanDelay(50, 200);
146
+
147
+ // Click with button press/release timing (real clicks have duration)
148
+ await page.mouse.click(endX, endY);
149
+
150
+ // Post-click: sometimes move mouse away immediately, sometimes linger
151
+ if (Math.random() < 0.3) {
152
+ await humanDelay(200, 600); // Linger on the clicked element
153
+ } else {
154
+ // Move away slowly
155
+ await page.mouse.move(endX + (Math.random() - 0.5) * 100, endY + (Math.random() - 0.5) * 100, { steps: 3 });
156
+ }
157
+
158
+ // Rare double-click (real users sometimes double-click by accident)
159
+ if (Math.random() < 0.02) {
160
+ await humanDelay(100, 300);
161
+ await page.mouse.click(endX, endY);
162
+ }
163
+
164
+ return;
165
+ }
166
+ } catch {}
167
+
168
+ // Fallback: use page.mouse.click at element center (still produces trusted events)
169
+ // Never use element.click() — it produces isTrusted:false events that Twitter detects
170
+ try {
171
+ const box = await el.boundingBox();
172
+ if (box) {
173
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
174
+ return;
175
+ }
176
+ } catch {}
177
+ // Last resort: use Playwright's click (dispatches real mouse events, trusted)
178
+ await humanDelay(50, 150);
179
+ await el.click({ timeout: 5000 }).catch(() => {});
180
+ }
181
+
182
+ async function safeClick(page, locator) {
183
+ return humanClick(page, locator);
184
+ }
185
+
186
+ async function getBodyText(page) {
187
+ try { return (await page.evaluate(() => document.body.innerText)).toLowerCase(); }
188
+ catch { return ''; }
189
+ }
190
+
191
+ /**
192
+ * Log-normal random delay — models real human dwell time better than uniform.
193
+ * Most pauses are short (2-5s), but occasionally a user reads for 20-30s.
194
+ * @param {number} median - median delay in ms (default 3000)
195
+ * @returns {Promise} sleep promise
196
+ */
197
+ function logNormalDelay(median = 3000) {
198
+ // Log-normal distribution: median * exp(sigma * N(0,1))
199
+ const sigma = 0.8;
200
+ const u1 = Math.random();
201
+ const u2 = Math.random();
202
+ const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
203
+ const delay = median * Math.exp(sigma * z);
204
+ // Clamp to reasonable bounds
205
+ return sleep(Math.min(Math.max(delay, 500), 60000));
206
+ }
207
+
208
+ /**
209
+ * Session warm-up — simulates what a real user does when they first open X:
210
+ * scroll the feed, hover over tweets, maybe click a profile, read content.
211
+ * This should run after browser start, before the first action.
212
+ */
213
+ async function sessionWarmup(page, durationMs = 8000) {
214
+ const startTime = Date.now();
215
+ const viewport = page.viewportSize();
216
+
217
+ // 1. Initial pause — user just opened the app, looking at feed
218
+ await logNormalDelay(2000);
219
+
220
+ // 2. Check notifications (real users check notifications first)
221
+ await humanCheckNotifications(page);
222
+
223
+ while (Date.now() - startTime < durationMs) {
224
+ const action = Math.random();
225
+
226
+ if (action < 0.25) {
227
+ // Scroll down the feed with variable speed
228
+ try {
229
+ const scrollAmt = 100 + Math.floor(Math.random() * 500);
230
+ await humanScroll(page, scrollAmt);
231
+ } catch {}
232
+ await logNormalDelay(2000);
233
+ } else if (action < 0.40) {
234
+ // Hover over a tweet and read it
235
+ try {
236
+ if (viewport) {
237
+ const x = viewport.width * (0.2 + Math.random() * 0.6);
238
+ const y = viewport.height * (0.2 + Math.random() * 0.5);
239
+ await page.mouse.move(x, y, { steps: 5 + Math.floor(Math.random() * 8) });
240
+ await logNormalDelay(2000);
241
+ }
242
+ } catch {}
243
+ } else if (action < 0.50) {
244
+ // Read a tweet in detail (longer hover + micro-scroll)
245
+ await humanReadTweet(page, 4000 + Math.random() * 4000);
246
+ } else if (action < 0.60) {
247
+ // Scroll back up using mouse wheel
248
+ try {
249
+ await humanScroll(page, -(100 + Math.random() * 300));
250
+ } catch {}
251
+ await logNormalDelay(1800);
252
+ } else if (action < 0.68) {
253
+ // Keyboard scroll (Space / PageDown / ArrowDown)
254
+ const keyChoice = Math.random();
255
+ if (keyChoice < 0.5) await keyboardScroll(page, 'down');
256
+ else {
257
+ await page.keyboard.press('ArrowDown');
258
+ await sleep(100 + Math.random() * 200);
259
+ await page.keyboard.press('ArrowDown');
260
+ }
261
+ await logNormalDelay(1500);
262
+ } else if (action < 0.75) {
263
+ // Idle mouse jitter (reading) with micro-tremor
264
+ await idleMouseJitter(page, 2000 + Math.random() * 2000);
265
+ } else if (action < 0.80) {
266
+ // Occasional Tab navigation
267
+ await occasionalTabNavigation(page);
268
+ await logNormalDelay(1000);
269
+ } else if (action < 0.84) {
270
+ // Rare window resize
271
+ await occasionalResize(page);
272
+ await logNormalDelay(1500);
273
+ } else if (action < 0.90) {
274
+ // Check notifications again
275
+ await humanCheckNotifications(page);
276
+ await logNormalDelay(1000);
277
+ } else if (action < 0.95) {
278
+ // Hover over sidebar items (Home, Explore, etc.)
279
+ try {
280
+ const sidebarItems = page.locator('nav a, nav [role="link"]').first();
281
+ if (await sidebarItems.isVisible({ timeout: 1000 }).catch(() => false)) {
282
+ await humanHover(page, sidebarItems);
283
+ }
284
+ } catch {}
285
+ await logNormalDelay(800);
286
+ } else {
287
+ // Brief pause (thinking / distracted)
288
+ await logNormalDelay(3000);
289
+ }
290
+ }
291
+ }
292
+
293
+ /**
294
+ * Human-like hover over an element — moves mouse to it, hovers, then moves away.
295
+ * Real users hover over tweets/links before clicking them.
296
+ */
297
+ async function humanHover(page, locator) {
298
+ try {
299
+ const el = typeof locator === 'string' ? page.locator(locator).first() : locator;
300
+ const box = await el.boundingBox();
301
+ if (!box) return;
302
+ const x = box.x + box.width * (0.2 + Math.random() * 0.6);
303
+ const y = box.y + box.height * (0.2 + Math.random() * 0.6);
304
+ // Move to the element with a curve
305
+ const steps = 3 + Math.floor(Math.random() * 4);
306
+ await page.mouse.move(x, y, { steps });
307
+ // Hover for a realistic duration (reading the content)
308
+ await logNormalDelay(800);
309
+ // Sometimes move away
310
+ if (Math.random() < 0.5) {
311
+ await page.mouse.move(x + (Math.random() - 0.5) * 80, y + (Math.random() - 0.5) * 80, { steps: 3 });
312
+ }
313
+ } catch {}
314
+ }
315
+
316
+ /**
317
+ * Human-like reading of a tweet — hover over it, scroll slightly, pause.
318
+ * Simulates a user reading the content before acting.
319
+ */
320
+ async function humanReadTweet(page, durationMs = 5000) {
321
+ const viewport = page.viewportSize();
322
+ if (!viewport) return;
323
+ // Hover over the middle of the viewport (where tweets usually are)
324
+ const tweetX = viewport.width * (0.3 + Math.random() * 0.4);
325
+ const tweetY = viewport.height * (0.3 + Math.random() * 0.3);
326
+ await page.mouse.move(tweetX, tweetY, { steps: 5 + Math.floor(Math.random() * 5) });
327
+ // Read for a while (log-normal: usually 3-8s, sometimes 15-20s)
328
+ await logNormalDelay(durationMs * 0.6);
329
+ // Slight scroll while reading
330
+ if (Math.random() < 0.4) {
331
+ await humanScroll(page, 30 + Math.random() * 80);
332
+ await logNormalDelay(durationMs * 0.3);
333
+ }
334
+ // Mouse micro-movements while reading
335
+ await idleMouseJitter(page, durationMs * 0.2);
336
+ }
337
+
338
+ /**
339
+ * Check notifications — real users check their notifications bell.
340
+ */
341
+ async function humanCheckNotifications(page) {
342
+ try {
343
+ // Look for the notifications bell/link
344
+ const notifLink = page.locator('a[href*="/notifications"], a[aria-label*="Notification"], a[data-testid="AppTabBar_Notifications_Link"]').first();
345
+ if (await notifLink.isVisible({ timeout: 2000 }).catch(() => false)) {
346
+ await humanHover(page, notifLink);
347
+ await logNormalDelay(1500);
348
+ // Don't actually click — just hover (less suspicious)
349
+ }
350
+ } catch {}
351
+ }
352
+
353
+ // ── Navigation ──────────────────────────────────────────────────────────────
354
+ async function naturalNavigate(page, targetUrl, options = {}) {
355
+ const currentUrl = page.url();
356
+ // Normalize for comparison (strip trailing slashes and query params)
357
+ const normCurrent = currentUrl.split('?')[0].replace(/\/+$/, '');
358
+ const normTarget = targetUrl.split('?')[0].replace(/\/+$/, '');
359
+ if (normCurrent === normTarget || normCurrent.includes(normTarget) || normTarget.includes(normCurrent)) {
360
+ await humanDelay(500, 1200);
361
+ return;
362
+ }
363
+
364
+ // ── Referrer chain: simulate arriving from the feed, not direct navigation ─
365
+ // Real users click tweets from their feed — they don't paste URLs directly.
366
+ // If we're on x.com already, the referrer will be natural.
367
+ // If we're on a blank page or non-x.com page, navigate to home first.
368
+ const isOnX = currentUrl.includes('x.com') || currentUrl.includes('twitter.com');
369
+ if (!isOnX) {
370
+ try {
371
+ await page.goto('https://x.com/home', { waitUntil: 'domcontentloaded', timeout: 30000 });
372
+ await page.waitForLoadState('networkidle', { timeout: 8000 }).catch(() => {});
373
+ await logNormalDelay(2000);
374
+ } catch {}
375
+ }
376
+
377
+ const waitUntil = options.waitUntil || 'domcontentloaded';
378
+ const timeout = options.timeout || 45000;
379
+ try {
380
+ await page.goto(targetUrl, { waitUntil, timeout, referer: isOnX ? currentUrl : 'https://x.com/home' });
381
+ } catch (e) {
382
+ // If it's a timeout but page might still be loading content, don't crash
383
+ console.log(`[naturalNavigate] goto warning: ${e.message}`);
384
+ }
385
+ // Wait for network to settle (X is a SPA — content loads after DOMContentLoaded)
386
+ try {
387
+ await page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {});
388
+ } catch {}
389
+ await randDelay(1500, 3000);
390
+ }
391
+
392
+ async function humanPreAction(page, accountId = 0) {
393
+ // Random scroll + delay to simulate human behavior
394
+ // Use mouse wheel event (produces real wheel events, not just JS scroll)
395
+ try {
396
+ await humanScroll(page, 100 + Math.random() * 200);
397
+ } catch {}
398
+ await randDelay(800, 1800);
399
+ }
400
+
401
+ /**
402
+ * Human-like scroll using mouse wheel events (fires real 'wheel' events).
403
+ * Real users scroll with the mouse wheel, not JS scrollBy().
404
+ * @param {number} deltaY - pixels to scroll (positive = down, negative = up)
405
+ */
406
+ async function humanScroll(page, deltaY = 300) {
407
+ try {
408
+ // Variable speed scrolling — real users scroll at different speeds
409
+ // Sometimes fast flick, sometimes slow drag
410
+ const isFastFlick = Math.random() < 0.3;
411
+ const stepDelay = isFastFlick ? 10 + Math.random() * 15 : 25 + Math.random() * 50;
412
+ const steps = Math.ceil(Math.abs(deltaY) / (isFastFlick ? 200 : 120));
413
+ const stepSize = deltaY / steps;
414
+
415
+ // Momentum scrolling — start slow, speed up, slow down (like a real flick)
416
+ for (let i = 0; i < steps; i++) {
417
+ const progress = i / steps;
418
+ // Ease-in-out: slow at start and end, fast in middle
419
+ const momentum = 0.5 + 0.5 * Math.sin(progress * Math.PI);
420
+ const adjustedStep = stepSize * (0.3 + momentum * 0.7);
421
+ await page.mouse.wheel(0, adjustedStep);
422
+ await sleep(stepDelay * (1 - momentum * 0.5)); // Faster in the middle
423
+ }
424
+
425
+ // Sometimes overshoot and scroll back slightly (real users overshoot)
426
+ if (Math.random() < 0.15 && Math.abs(deltaY) > 200) {
427
+ await sleep(100 + Math.random() * 200);
428
+ await page.mouse.wheel(0, -deltaY * 0.05);
429
+ }
430
+ } catch {
431
+ try { await page.evaluate((dy) => window.scrollBy(0, dy), deltaY); } catch {}
432
+ }
433
+ }
434
+
435
+ /**
436
+ * Keyboard-based scrolling — real users use Space, Page Down, arrow keys.
437
+ */
438
+ async function keyboardScroll(page, direction = 'down') {
439
+ try {
440
+ const key = direction === 'down' ? 'Space' : 'PageUp';
441
+ await page.keyboard.press(key);
442
+ await sleep(100 + Math.random() * 200);
443
+ } catch {}
444
+ }
445
+
446
+ /**
447
+ * Occasional Tab key navigation — real users sometimes Tab through elements.
448
+ */
449
+ async function occasionalTabNavigation(page) {
450
+ try {
451
+ const tabCount = 1 + Math.floor(Math.random() * 3);
452
+ for (let i = 0; i < tabCount; i++) {
453
+ await page.keyboard.press('Tab');
454
+ await sleep(50 + Math.random() * 150);
455
+ }
456
+ // Shift+Tab back
457
+ if (Math.random() < 0.5) {
458
+ await page.keyboard.press('Shift+Tab');
459
+ await sleep(50 + Math.random() * 100);
460
+ }
461
+ } catch {}
462
+ }
463
+
464
+ /**
465
+ * Rare window resize — real users occasionally resize their browser.
466
+ */
467
+ async function occasionalResize(page) {
468
+ try {
469
+ const viewport = page.viewportSize();
470
+ if (!viewport) return;
471
+ // Small resize (±50px) — not dramatic
472
+ const newWidth = viewport.width + Math.floor((Math.random() - 0.5) * 100);
473
+ const newHeight = viewport.height + Math.floor((Math.random() - 0.5) * 100);
474
+ await page.setViewportSize({ width: newWidth, height: newHeight });
475
+ await sleep(500 + Math.random() * 1000);
476
+ // Resize back
477
+ await page.setViewportSize({ width: viewport.width, height: viewport.height });
478
+ } catch {}
479
+ }
480
+
481
+ /**
482
+ * Idle mouse jitter — simulates micro-movements a real user makes
483
+ * while reading/looking at the screen (not perfectly still).
484
+ * Call during waits to keep the session looking alive.
485
+ */
486
+ async function idleMouseJitter(page, durationMs = 2000) {
487
+ const startTime = Date.now();
488
+ const viewport = page.viewportSize();
489
+ if (!viewport) return;
490
+ // Track last position for micro-tremor simulation
491
+ let lastX = viewport.width / 2;
492
+ let lastY = viewport.height / 2;
493
+ while (Date.now() - startTime < durationMs) {
494
+ try {
495
+ // Micro-tremor: small movements near last position (like a hand holding a mouse)
496
+ if (Math.random() < 0.6) {
497
+ const tremorX = lastX + (Math.random() - 0.5) * 30;
498
+ const tremorY = lastY + (Math.random() - 0.5) * 30;
499
+ await page.mouse.move(tremorX, tremorY, { steps: 1 });
500
+ lastX = tremorX;
501
+ lastY = tremorY;
502
+ await sleep(200 + Math.random() * 500);
503
+ } else {
504
+ // Occasional larger movement to a new area
505
+ lastX = viewport.width * (0.2 + Math.random() * 0.6);
506
+ lastY = viewport.height * (0.2 + Math.random() * 0.6);
507
+ await page.mouse.move(lastX, lastY, { steps: 3 + Math.floor(Math.random() * 5) });
508
+ await sleep(300 + Math.random() * 800);
509
+ }
510
+ } catch { break; }
511
+ }
512
+ }
513
+
514
+ /**
515
+ * Human-like post-action behavior — simulates what a real user does after
516
+ * performing an action: pause, scroll, maybe move mouse, browse a bit.
517
+ * This runs BEFORE the browser closes so the session doesn't look robotic
518
+ * (action → instant close).
519
+ */
520
+ async function humanPostAction(page) {
521
+ // 1. Brief pause — user reads the result of their action (with idle mouse jitter + micro-tremor)
522
+ await idleMouseJitter(page, 1500 + Math.random() * 2500);
523
+
524
+ // 2. Random scroll down (reading the timeline) — use mouse wheel with momentum
525
+ try {
526
+ const scrollAmount = 100 + Math.floor(Math.random() * 400);
527
+ await humanScroll(page, scrollAmount);
528
+ } catch {}
529
+ await idleMouseJitter(page, 1000 + Math.random() * 1500);
530
+
531
+ // 3. Sometimes read a tweet in detail
532
+ if (Math.random() < 0.3) {
533
+ await humanReadTweet(page, 3000 + Math.random() * 5000);
534
+ }
535
+
536
+ // 4. Sometimes scroll back up
537
+ if (Math.random() < 0.4) {
538
+ try {
539
+ await humanScroll(page, -(150 + Math.random() * 300));
540
+ } catch {}
541
+ await idleMouseJitter(page, 800 + Math.random() * 1200);
542
+ }
543
+
544
+ // 5. Random mouse movement (like user is looking around)
545
+ try {
546
+ const viewport = page.viewportSize();
547
+ if (viewport) {
548
+ const steps = 2 + Math.floor(Math.random() * 3);
549
+ for (let i = 0; i < steps; i++) {
550
+ const x = Math.random() * viewport.width;
551
+ const y = Math.random() * viewport.height;
552
+ await page.mouse.move(x, y, { steps: 3 + Math.floor(Math.random() * 5) });
553
+ await sleep(200 + Math.random() * 500);
554
+ }
555
+ }
556
+ } catch {}
557
+
558
+ // 6. Sometimes check notifications (real users check after posting)
559
+ if (Math.random() < 0.25) {
560
+ await humanCheckNotifications(page);
561
+ await logNormalDelay(1500);
562
+ }
563
+
564
+ // 7. Sometimes navigate to home page (like user checking their feed after posting)
565
+ if (Math.random() < 0.3) {
566
+ try {
567
+ await page.goto('https://x.com/home', { waitUntil: 'domcontentloaded', timeout: 15000 }).catch(() => {});
568
+ await page.waitForLoadState('networkidle', { timeout: 8000 }).catch(() => {});
569
+ await idleMouseJitter(page, 2000 + Math.random() * 3000);
570
+ // Scroll the feed using mouse wheel with momentum
571
+ await humanScroll(page, 200 + Math.random() * 300);
572
+ await idleMouseJitter(page, 1000 + Math.random() * 1500);
573
+ // Maybe read a tweet
574
+ if (Math.random() < 0.4) {
575
+ await humanReadTweet(page, 3000 + Math.random() * 3000);
576
+ }
577
+ } catch {}
578
+ }
579
+
580
+ // 8. Sometimes visit own profile (like user checking how their profile looks)
581
+ if (Math.random() < 0.15) {
582
+ try {
583
+ // Click on the profile link in the sidebar
584
+ const profileLink = page.locator('a[href*="/profile"], [data-testid="AppTabBar_Profile_Link"]').first();
585
+ if (await profileLink.isVisible({ timeout: 2000 }).catch(() => false)) {
586
+ await humanHover(page, profileLink);
587
+ await logNormalDelay(1000);
588
+ }
589
+ } catch {}
590
+ }
591
+
592
+ // 9. Final pause before closing — log-normal: usually 2-5s, occasionally 15-30s
593
+ await logNormalDelay(3000);
594
+ }
595
+
596
+ // ── TOTP ───────────────────────────────────────────────────────────────────
597
+ function generateTOTP(secret) {
598
+ const OTPAuth = require('otpauth');
599
+ const normalized = String(secret || '').replace(/\s+/g, '').toUpperCase();
600
+ if (!normalized) throw new Error('Missing TOTP secret');
601
+ const totp = new OTPAuth.TOTP({
602
+ algorithm: 'SHA1', digits: 6, period: 30,
603
+ secret: OTPAuth.Secret.fromBase32(normalized),
604
+ });
605
+ return totp.generate();
606
+ }
607
+
608
+ // ── Stage detection (simplified from src/stageDetector.js) ──────────────────
609
+ const SELECTORS = {
610
+ usernameInput: 'input[autocomplete="username"]',
611
+ passwordInput: 'input[type="password"]',
612
+ nextButton: 'button:has-text("Next")',
613
+ loginButton: 'button[data-testid="LoginForm_Login_Button"]',
614
+ twoFactorInput: 'input[name="text"]',
615
+ homeIndicator: '[data-testid="SideNav_NewTweet_Button"]',
616
+ tweetButton: '[data-testid="tweetButton"]',
617
+ primaryColumn: '[data-testid="primaryColumn"]',
618
+ };
619
+
620
+ async function detectStage(page) {
621
+ try {
622
+ const url = page.url();
623
+ if (url.includes('/login') || url.includes('/i/flow/login')) {
624
+ // Check if username or password step
625
+ const hasUsername = await isLocatorVisible(page.locator(SELECTORS.usernameInput));
626
+ const hasPassword = await isLocatorVisible(page.locator(SELECTORS.passwordInput));
627
+ if (hasPassword) return 'login_password_step';
628
+ if (hasUsername) return 'login_username_step';
629
+ return 'login_required';
630
+ }
631
+ // Check if logged in
632
+ const hasHome = await isLocatorVisible(page.locator(SELECTORS.homeIndicator), 3000);
633
+ const hasPrimary = await isLocatorVisible(page.locator(SELECTORS.primaryColumn), 3000);
634
+ if (hasHome || hasPrimary) return 'home_logged_in';
635
+ return 'unknown';
636
+ } catch { return 'unknown'; }
637
+ }
638
+
639
+ async function waitForLoggedIn(page, options = {}) {
640
+ const timeoutMs = options.timeoutMs || 22000;
641
+ const intervalMs = options.intervalMs || 1000;
642
+ const start = Date.now();
643
+ while (Date.now() - start < timeoutMs) {
644
+ const stage = await detectStage(page);
645
+ if (stage === 'home_logged_in') return true;
646
+ if (stage === 'checkpoint' || stage === 'login_username_step' || stage === 'login_password_step') return false;
647
+ await sleep(intervalMs);
648
+ }
649
+ return false;
650
+ }
651
+
652
+ // ── Cookie helpers ──────────────────────────────────────────────────────────
653
+ async function injectCookies(context, cookiesData) {
654
+ if (!cookiesData) return;
655
+ try {
656
+ let cookies = [];
657
+ if (typeof cookiesData === 'string') {
658
+ try { cookies = JSON.parse(cookiesData); }
659
+ catch { try { cookies = JSON.parse(Buffer.from(cookiesData, 'base64').toString()); } catch {} }
660
+ } else if (Array.isArray(cookiesData)) {
661
+ cookies = cookiesData;
662
+ }
663
+ if (!cookies.length) return;
664
+ const normalized = cookies.map(c => ({
665
+ name: c.name, value: c.value,
666
+ domain: c.domain || '.x.com', path: c.path || '/',
667
+ expires: c.expires || -1, httpOnly: c.httpOnly !== false,
668
+ secure: c.secure !== false, sameSite: c.sameSite || 'Lax',
669
+ }));
670
+ await context.addCookies(normalized);
671
+ } catch {}
672
+ }
673
+
674
+ async function saveCookies(context) {
675
+ try { return await context.cookies(); } catch { return []; }
676
+ }
677
+
678
+ // ── Proxy parsing ───────────────────────────────────────────────────────────
679
+ function parseProxy(proxyStr) {
680
+ if (!proxyStr || !proxyStr.trim()) return undefined;
681
+ const parts = proxyStr.trim().split(':');
682
+ if (parts.length >= 4) {
683
+ const [host, port, user, ...passParts] = parts;
684
+ return { server: `http://${host}:${port}`, username: user, password: passParts.join(':') };
685
+ } else if (parts.length === 2) {
686
+ return { server: `http://${host}:${port}` };
687
+ }
688
+ return undefined;
689
+ }
690
+
691
+ module.exports = {
692
+ sleep, humanDelay, randDelay,
693
+ isLocatorVisible, safeFill, safeClick, humanClick, humanType, getBodyText,
694
+ naturalNavigate, humanPreAction, humanPostAction, idleMouseJitter,
695
+ logNormalDelay, sessionWarmup,
696
+ humanScroll, keyboardScroll, occasionalTabNavigation, occasionalResize,
697
+ humanHover, humanReadTweet, humanCheckNotifications,
698
+ generateTOTP,
699
+ detectStage, waitForLoggedIn, SELECTORS,
700
+ injectCookies, saveCookies,
701
+ parseProxy,
702
+ highlightElement,
703
+ };
704
+
705
+ /**
706
+ * Draw a colored outline around an element so the user can visually see
707
+ * what the agent is doing. The outline stays for 2 seconds then fades.
708
+ */
709
+ async function highlightElement(page, locator, color = 'red', label = '') {
710
+ try {
711
+ const el = typeof locator === 'string' ? page.locator(locator).first() : locator;
712
+ const box = await el.boundingBox();
713
+ if (!box) return;
714
+ await page.evaluate(({ box, color, label }) => {
715
+ const div = document.createElement('div');
716
+ div.style.cssText = `
717
+ position: fixed;
718
+ left: ${box.x - 4}px;
719
+ top: ${box.y - 4}px;
720
+ width: ${box.width + 8}px;
721
+ height: ${box.height + 8}px;
722
+ border: 3px solid ${color};
723
+ border-radius: 4px;
724
+ z-index: 999999;
725
+ pointer-events: none;
726
+ transition: opacity 0.5s;
727
+ box-shadow: 0 0 8px ${color};
728
+ `;
729
+ if (label) {
730
+ const lbl = document.createElement('div');
731
+ lbl.textContent = label;
732
+ lbl.style.cssText = `
733
+ position: fixed;
734
+ left: ${box.x - 4}px;
735
+ top: ${box.y - 20}px;
736
+ background: ${color};
737
+ color: white;
738
+ padding: 2px 8px;
739
+ font-size: 12px;
740
+ font-family: sans-serif;
741
+ border-radius: 3px;
742
+ z-index: 999999;
743
+ pointer-events: none;
744
+ `;
745
+ document.body.appendChild(lbl);
746
+ setTimeout(() => { lbl.style.opacity = '0'; }, 2000);
747
+ setTimeout(() => lbl.remove(), 3000);
748
+ }
749
+ document.body.appendChild(div);
750
+ setTimeout(() => { div.style.opacity = '0'; }, 2000);
751
+ setTimeout(() => div.remove(), 3000);
752
+ }, { box, color, label });
753
+ } catch {}
754
754
  }