@xkwdstore/agent 2.0.1

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 ADDED
@@ -0,0 +1,245 @@
1
+ # @xkwdstore/agent
2
+
3
+ Terminal-only, cryptographically authenticated CLI for XKWDStore browser automation.
4
+
5
+ ## Installation — staged Protocol-v2 release
6
+
7
+ > **Staged release notice**
8
+ >
9
+ > Protocol-v2 installer prepared for Agent 2.0.1. Public installation becomes
10
+ > active after `@xkwdstore/agent@2.0.1` is published to npm. Until the
11
+ > package is published, version 2.0.1 is **not usable** through the public
12
+ > installer; the pinned `npx` command below will fail on a clean machine.
13
+
14
+ Once the package is published, end users install with a one-line PowerShell
15
+ command that creates a desktop launcher pinned to this version:
16
+
17
+ ```powershell
18
+ irm https://raw.githubusercontent.com/EssaGhazwani/TW-manager-install/main/install.ps1 | iex
19
+ ```
20
+
21
+ The generated launcher runs the pinned future command:
22
+
23
+ ```powershell
24
+ npx --yes @xkwdstore/agent@2.0.1 start
25
+ ```
26
+
27
+ Automated installer tests use `-NoLaunch` or a mocked `npx` command so the
28
+ real pinned package is never executed from the public registry during
29
+ installation validation.
30
+
31
+ ## Platform Support
32
+
33
+ | Platform | Status |
34
+ |----------|--------|
35
+ | **Windows** | Implementation present. ACL hardening awaits real Windows runner CI. |
36
+ | **Linux (with Secret Service / libsecret)** | Implementation present. Pending platform verification on CI. |
37
+ | **macOS** | **Unsupported.** Fails closed with an explicit error. No macOS Keychain integration is implemented. |
38
+
39
+ ## Requirements
40
+
41
+ - **Node.js 22 or later** — check with `node --version`
42
+ - **Google Chrome** installed on your computer
43
+ - A terminal (PowerShell, Windows Terminal, or Linux shell)
44
+ - **Linux**: `gnome-keyring` or `seahorse` (provides `libsecret` / `secret-tool`)
45
+
46
+ ## First Run
47
+
48
+ On first run, the agent will:
49
+
50
+ 1. Generate an Ed25519 key pair locally on your computer.
51
+ 2. Open your browser to x.kwdstore.com for authorization.
52
+ 3. Wait for you to sign in and approve the computer.
53
+ 4. Connect securely after approval.
54
+
55
+ **No pairing code. No email prompt. No API key. No download. No installer.**
56
+
57
+ The private key is stored using your operating system's secure credential storage:
58
+ - **Windows**: DPAPI (current-user scope) — pending ACL hardening CI verification
59
+ - **Linux**: Secret Service / libsecret
60
+ - **macOS**: Not supported — fails with an explicit error
61
+
62
+ The private key **never leaves your computer**, never appears in logs, and never
63
+ appears in command-line arguments.
64
+
65
+ ## Subsequent Runs
66
+
67
+ After first authorization, the agent connects automatically.
68
+
69
+ No browser approval is needed unless:
70
+ - The device key was deleted
71
+ - The device was revoked from the dashboard
72
+ - Secure storage was reset
73
+ - The server no longer recognizes the public key
74
+
75
+ ## Commands
76
+
77
+ | Command | Description |
78
+ |---------|-------------|
79
+ | `start` | Start the agent (connect, run browser sessions) |
80
+ | `status` | Show device and connection status |
81
+ | `logout` | Delete local device identity (requires re-authorization) |
82
+ | `revoke-local` | Delete local device identity and credentials |
83
+ | `doctor` | Run diagnostic checks |
84
+ | `version` | Print version information |
85
+ | `help` | Show help |
86
+
87
+ ### Options
88
+
89
+ - `--server=<url>` — Server URL (default: `https://x.kwdstore.com`)
90
+ - `--replace` — Replace a running instance (safe takeover)
91
+
92
+ ## Stopping the Agent
93
+
94
+ Press **Ctrl+C** in the terminal. The agent closes all browser sessions and
95
+ disconnects cleanly. No background process remains.
96
+
97
+ ## Data Storage
98
+
99
+ The agent stores runtime data in your operating system's standard application-data
100
+ directory:
101
+
102
+ | Platform | Location |
103
+ |----------|----------|
104
+ | Windows | `%LOCALAPPDATA%\XKWDStore\` |
105
+ | Linux | `${XDG_DATA_HOME:-~/.local/share}/xkwdstore/` |
106
+
107
+ This directory contains:
108
+ - Chrome profiles (persistent cookies and browser storage)
109
+ - Bounded logs (no cookies, tokens, private keys, or secrets)
110
+ - Non-secret device metadata (deviceId, publicKey, fingerprint)
111
+ - Temporary runtime files
112
+
113
+ **Nothing is written to Desktop, Documents, Downloads, or OneDrive.**
114
+
115
+ ## Security
116
+
117
+ ### Device Identity
118
+
119
+ The device identity is an **Ed25519 key pair** generated locally. The server
120
+ authenticates the computer by verifying signatures made by the private key.
121
+ Hardware attributes (hostname, OS, architecture) are collected for display and
122
+ anomaly detection only — they are **not** authentication credentials.
123
+
124
+ ### WebSocket Authentication
125
+
126
+ Every WebSocket connection uses **Ed25519 challenge-response**:
127
+ 1. Server sends a challenge with a random nonce.
128
+ 2. Client signs the challenge with its private key.
129
+ 3. Server verifies the signature against the registered public key.
130
+
131
+ No HTTP credential exchange. No in-memory ticket. No bearer token in the URL.
132
+
133
+ ### Revocation
134
+
135
+ A device can be revoked from the dashboard. Revocation immediately prevents all
136
+ future challenge-response authentication. Active connections are closed when
137
+ the server processes the revocation event — this requires the
138
+ `protocolV2Revocation` integration test to pass.
139
+
140
+ ### Windows Private Key Storage
141
+
142
+ 1. Key is DPAPI-protected through stdin.
143
+ 2. Encrypted envelope is written to disk.
144
+ 3. A restricted DACL is applied via PowerShell.
145
+ 4. ACL application is verified (not best-effort): the write **fails** if the
146
+ ACL cannot be applied or verified.
147
+
148
+ **Status**: Implementation present. ACL fail-closed tests require a real
149
+ Windows runner (pending CI billing restoration).
150
+
151
+ ## What This Agent Does NOT Do
152
+
153
+ - ❌ Download or install a browser (uses your system Chrome)
154
+ - ❌ Run a self-updater (you pin the version in the command)
155
+ - ❌ Poll GitHub for manifests
156
+ - ❌ Require a pairing code
157
+ - ❌ Require an email in the terminal
158
+ - ❌ Keep a tray application running
159
+ - ❌ Install a Windows service
160
+ - ❌ Create a Scheduled Task
161
+ - ❌ Write to Desktop, Documents, Downloads, or OneDrive
162
+ - ❌ Store private keys in plaintext
163
+ - ❌ Use `curl | sh` or `Invoke-WebRequest | Invoke-Expression`
164
+ - ❌ Support macOS (fails closed)
165
+
166
+ ## Version Management
167
+
168
+ The agent does NOT update itself. To use a newer version, change the version
169
+ number in the command. The pinned future command for this release is:
170
+
171
+ ```powershell
172
+ npx --yes @xkwdstore/agent@2.0.1 start
173
+ ```
174
+
175
+ > Version 2.0.1 is not usable through the public installer until it is
176
+ > published to npm.
177
+
178
+ The server checks compatibility at startup and displays a clear message if the
179
+ agent version is no longer supported.
180
+
181
+ ## Privacy
182
+
183
+ The agent collects and sends the following non-secret information to the server:
184
+ - Hostname (for display)
185
+ - Operating system and version
186
+ - CPU architecture
187
+ - Current OS username
188
+ - Chrome version
189
+ - A locally-salted hash of machine identifiers (for anomaly detection, not
190
+ authentication)
191
+
192
+ The agent does **not** send:
193
+ - Raw motherboard serial numbers
194
+ - Raw disk serial numbers
195
+ - Raw machine GUIDs
196
+ - Private keys
197
+ - Cookies or browser storage
198
+ - Passwords or tokens
199
+
200
+ ## Troubleshooting
201
+
202
+ Run `xkwd-agent doctor` to check:
203
+ - Node.js version
204
+ - Chrome installation
205
+ - Secure storage availability
206
+ - Data directory
207
+ - Device enrollment status
208
+ - Server connectivity
209
+
210
+ ### Chrome Not Found
211
+
212
+ ```
213
+ Google Chrome was not found.
214
+ Install Chrome and run the command again.
215
+ No browser was downloaded or installed automatically.
216
+ ```
217
+
218
+ Install Google Chrome from https://www.google.com/chrome/ and run the command again.
219
+
220
+ ### Secure Storage Unavailable (Linux)
221
+
222
+ ```
223
+ Secure key storage is unavailable on this system.
224
+ ```
225
+
226
+ Install `gnome-keyring` or `seahorse` (provides `libsecret` / `secret-tool`).
227
+
228
+ ### macOS Not Supported
229
+
230
+ ```
231
+ macOS is not supported. The agent fails closed on macOS.
232
+ ```
233
+
234
+ The agent does not implement macOS Keychain integration. Use a Linux or Windows computer.
235
+
236
+ ### Already Running
237
+
238
+ ```
239
+ XKWDStore Agent is already running on this computer.
240
+ PID: ...
241
+ Started: ...
242
+ Device: ...
243
+ ```
244
+
245
+ Use `xkwd-agent start --replace` to safely replace the running instance.
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@xkwdstore/agent",
3
+ "version": "2.0.1",
4
+ "description": "XKWDStore Agent — terminal-only, cryptographically authenticated CLI for browser automation",
5
+ "main": "src/cli.js",
6
+ "bin": {
7
+ "xkwd-agent": "src/cli.js"
8
+ },
9
+ "scripts": {
10
+ "start": "node src/cli.js start",
11
+ "dev": "node src/cli.js start",
12
+ "test": "node --test tests/*.test.js",
13
+ "build": "echo 'No build step — this is a pure npm CLI package'"
14
+ },
15
+ "engines": {
16
+ "node": ">=22.0.0"
17
+ },
18
+ "files": [
19
+ "src/cli.js",
20
+ "src/deviceKeyStore.js",
21
+ "src/chromeDetector.js",
22
+ "src/enrollmentClient.js",
23
+ "src/processLock.js",
24
+ "src/wsClient.js",
25
+ "src/challengeCodec.js",
26
+ "src/sessionHandler.js",
27
+ "src/fingerprint.js",
28
+ "src/fingerprintStore.js",
29
+ "src/profilePath.js",
30
+ "src/stealth.js",
31
+ "src/leaseClient.js",
32
+ "src/proxyEgress.js",
33
+ "src/proxyPolicy.js",
34
+ "src/configStore.js",
35
+ "src/secretStore.js",
36
+ "src/actions/",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "dependencies": {
41
+ "otpauth": "^9.3.0",
42
+ "playwright-core": "^1.58.2",
43
+ "ws": "^8.19.0"
44
+ },
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/EssaGhazwani/TW-manager.git",
48
+ "directory": "apps/local-agent"
49
+ },
50
+ "license": "UNLICENSED",
51
+ "private": false,
52
+ "publishConfig": {
53
+ "access": "public"
54
+ }
55
+ }
@@ -0,0 +1,138 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Comment action — post a reply/comment on a tweet.
5
+ * Ported from backend/routes/browser.js doComment().
6
+ */
7
+
8
+ const { sleep, humanDelay, randDelay, naturalNavigate, humanPreAction, humanType, humanClick, detectStage } = require('./helpers');
9
+
10
+ async function comment(page, payload) {
11
+ const { tweetUrl, commentText } = payload;
12
+ if (!tweetUrl || !commentText) throw new Error('tweetUrl and commentText required');
13
+
14
+ // Navigate to the tweet
15
+ await page.goto(tweetUrl, { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(() => {});
16
+ await randDelay(1800, 3200);
17
+
18
+ if (page.url().includes('/login') || page.url().includes('/i/flow')) {
19
+ throw new Error('Not logged in — open browser and login first');
20
+ }
21
+
22
+ // Find and click the reply button
23
+ const tweetIdMatch = tweetUrl.match(/\/status\/(\d+)/);
24
+ const tweetId = tweetIdMatch ? tweetIdMatch[1] : null;
25
+ const replySelectors = [
26
+ 'button[data-testid="reply"]',
27
+ '[data-testid="reply"]',
28
+ 'button[aria-label*="Reply"]',
29
+ ];
30
+
31
+ let replyClicked = false;
32
+ for (const sel of replySelectors) {
33
+ const scoped = tweetId ? `article:has(a[href*="/status/${tweetId}"]) ${sel}` : sel;
34
+ const btn = page.locator(scoped).first();
35
+ if (await btn.isVisible({ timeout: 3000 }).catch(() => false)) {
36
+ await humanClick(page, btn);
37
+ replyClicked = true;
38
+ break;
39
+ }
40
+ }
41
+
42
+ if (!replyClicked && tweetId) {
43
+ // Fallback for tweet detail pages where the target article does not include
44
+ // a status link back to itself.
45
+ for (const sel of replySelectors) {
46
+ const btn = page.locator(sel).first();
47
+ if (await btn.isVisible({ timeout: 3000 }).catch(() => false)) {
48
+ await humanClick(page, btn);
49
+ replyClicked = true;
50
+ break;
51
+ }
52
+ }
53
+ }
54
+
55
+ if (!replyClicked) throw new Error('Could not find reply button');
56
+
57
+ // Wait for dialog or inline editor
58
+ await sleep(1500);
59
+ const editorSelectors = [
60
+ 'div[role="dialog"] [data-testid="tweetTextarea_0"] div[contenteditable="true"][role="textbox"]',
61
+ '[data-testid="tweetTextarea_0"] div[contenteditable="true"][role="textbox"]',
62
+ '.public-DraftEditor-content',
63
+ ];
64
+
65
+ let editor = null;
66
+ for (const sel of editorSelectors) {
67
+ const el = page.locator(sel).first();
68
+ if (await el.isVisible({ timeout: 5000 }).catch(() => false)) {
69
+ editor = el;
70
+ break;
71
+ }
72
+ }
73
+
74
+ if (!editor) throw new Error('Could not find comment editor');
75
+ await editor.click();
76
+ await humanDelay(300, 600);
77
+
78
+ // Clear any existing text
79
+ await page.keyboard.press('Control+a');
80
+ await page.keyboard.press('Backspace');
81
+
82
+ // Type comment
83
+ const isRTL = /[\u0600-\u06FF\u0750-\u077F]/.test(commentText);
84
+ if (isRTL) {
85
+ await page.evaluate(() => {
86
+ const el = document.querySelector('[data-testid="tweetTextarea_0"]');
87
+ if (el) el.setAttribute('dir', 'rtl');
88
+ });
89
+ const words = commentText.split(' ');
90
+ for (const word of words) {
91
+ await page.evaluate((w) => document.execCommand('insertText', false, w + ' '), word);
92
+ await humanDelay(50, 100);
93
+ }
94
+ } else {
95
+ await humanType(page, commentText, { delayMin: 50, delayMax: 150 });
96
+ }
97
+
98
+ await humanDelay(500, 1000);
99
+
100
+ // Click send/reply button
101
+ const sendSelectors = [
102
+ 'div[role="dialog"] [data-testid="tweetButton"]',
103
+ '[data-testid="tweetButton"]',
104
+ '[data-testid="tweetButtonInline"]',
105
+ ];
106
+
107
+ let sent = false;
108
+ for (const sel of sendSelectors) {
109
+ const btn = page.locator(sel).first();
110
+ if (await btn.isVisible({ timeout: 3000 }).catch(() => false)) {
111
+ await humanClick(page, btn);
112
+ sent = true;
113
+ break;
114
+ }
115
+ }
116
+
117
+ if (!sent) {
118
+ await page.keyboard.press('Control+Enter');
119
+ }
120
+
121
+ // Wait for dialog to close
122
+ try {
123
+ await page.waitForSelector('div[role="dialog"]', { state: 'detached', timeout: 15000 });
124
+ } catch {
125
+ await page.keyboard.press('Control+Enter');
126
+ await sleep(3000);
127
+ }
128
+
129
+ // Check for failure
130
+ const bodyText = await page.evaluate(() => document.body.innerText).catch(() => '');
131
+ if (/something went wrong|try again|failed/i.test(bodyText)) {
132
+ throw new Error('Comment submit reported a failure');
133
+ }
134
+
135
+ return { success: true, message: 'Comment posted' };
136
+ }
137
+
138
+ module.exports = { comment };
@@ -0,0 +1,150 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Death By Captcha solver for the Local Agent.
5
+ *
6
+ * Uses the DBC HTTP API to solve image-based CAPTCHAs encountered
7
+ * during Twitter/X login or challenge flows.
8
+ *
9
+ * The agent receives DBC credentials from the VPS in the startSession
10
+ * command options (dbcUsername, dbcPassword).
11
+ */
12
+
13
+ const https = require('https');
14
+ const http = require('http');
15
+ const { URL } = require('url');
16
+
17
+ const DBC_API_BASE = 'http://api.dbcapi.me/api';
18
+ const DBC_TIMEOUT_MS = 90000;
19
+ const DBC_POLL_INTERVAL_MS = 4000;
20
+
21
+ let _username = null;
22
+ let _password = null;
23
+
24
+ /**
25
+ * Configure DBC credentials (called when a session starts).
26
+ */
27
+ function configure(username, password) {
28
+ _username = username || null;
29
+ _password = password || null;
30
+ }
31
+
32
+ /**
33
+ * Check if DBC is enabled.
34
+ */
35
+ function isEnabled() {
36
+ return !!(_username && _password);
37
+ }
38
+
39
+ /**
40
+ * Make an HTTP request and return the response body as a string.
41
+ */
42
+ function httpRequest(url, options = {}) {
43
+ return new Promise((resolve, reject) => {
44
+ const parsed = new URL(url);
45
+ const lib = parsed.protocol === 'https:' ? https : http;
46
+ const req = lib.request(url, {
47
+ method: options.method || 'GET',
48
+ headers: options.headers || {},
49
+ timeout: options.timeout || 30000,
50
+ }, (res) => {
51
+ let data = '';
52
+ res.on('data', (chunk) => { data += chunk; });
53
+ res.on('end', () => {
54
+ try { resolve(JSON.parse(data)); }
55
+ catch { resolve(data); }
56
+ });
57
+ });
58
+ req.on('error', reject);
59
+ req.on('timeout', () => { req.destroy(); reject(new Error('Request timed out')); });
60
+ if (options.body) req.write(options.body);
61
+ req.end();
62
+ });
63
+ }
64
+
65
+ /**
66
+ * Solve an image-based CAPTCHA.
67
+ * @param {string|Buffer} image - Base64 string or Buffer of the captcha image
68
+ * @param {object} options - { timeoutMs }
69
+ * @returns {Promise<{captcha:string, text:string}>}
70
+ */
71
+ async function solveImageCaptcha(image, options = {}) {
72
+ if (!isEnabled()) throw new Error('DBC credentials not configured');
73
+
74
+ const timeoutMs = options.timeoutMs || DBC_TIMEOUT_MS;
75
+ let base64Image;
76
+ if (Buffer.isBuffer(image)) {
77
+ base64Image = image.toString('base64');
78
+ } else if (typeof image === 'string') {
79
+ base64Image = image.replace(/^data:image\/\w+;base64,/, '');
80
+ } else {
81
+ throw new Error('Invalid image input for DBC solve');
82
+ }
83
+
84
+ // Upload captcha
85
+ const params = new URLSearchParams();
86
+ params.append('username', _username);
87
+ params.append('password', _password);
88
+ params.append('type', '4'); // image CAPTCHA
89
+ params.append('captchafile', `base64:${base64Image}`);
90
+
91
+ console.log('[dbc] Uploading image captcha to DBC...');
92
+ const upload = await httpRequest(`${DBC_API_BASE}/captcha`, {
93
+ method: 'POST',
94
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
95
+ body: params.toString(),
96
+ timeout: 30000,
97
+ });
98
+
99
+ if (!upload || !upload.captcha) {
100
+ throw new Error(`DBC upload failed: ${JSON.stringify(upload)}`);
101
+ }
102
+
103
+ const captchaId = upload.captcha;
104
+ console.log(`[dbc] Captcha uploaded: ${captchaId}`);
105
+
106
+ // Poll for answer
107
+ const deadline = Date.now() + timeoutMs;
108
+ while (Date.now() < deadline) {
109
+ await new Promise(r => setTimeout(r, DBC_POLL_INTERVAL_MS));
110
+
111
+ const status = await httpRequest(`${DBC_API_BASE}/captcha/${captchaId}`, {
112
+ method: 'GET',
113
+ timeout: 15000,
114
+ });
115
+
116
+ if (status && status.text) {
117
+ console.log(`[dbc] Captcha solved: ${status.text}`);
118
+ return { captcha: captchaId, text: status.text };
119
+ }
120
+
121
+ if (status && status.is_correct === 0 && status.text) {
122
+ throw new Error(`DBC captcha rejected: ${status.text}`);
123
+ }
124
+ }
125
+
126
+ throw new Error('DBC captcha solve timed out');
127
+ }
128
+
129
+ /**
130
+ * Report an incorrectly solved captcha for refund.
131
+ */
132
+ async function reportBad(captchaId) {
133
+ if (!isEnabled() || !captchaId) return;
134
+ try {
135
+ await httpRequest(`${DBC_API_BASE}/captcha/${captchaId}/report`, {
136
+ method: 'POST',
137
+ timeout: 15000,
138
+ });
139
+ console.log(`[dbc] Reported bad captcha: ${captchaId}`);
140
+ } catch (err) {
141
+ console.log(`[dbc] Failed to report bad captcha ${captchaId}: ${err.message}`);
142
+ }
143
+ }
144
+
145
+ module.exports = {
146
+ configure,
147
+ isEnabled,
148
+ solveImageCaptcha,
149
+ reportBad,
150
+ };
@@ -0,0 +1,83 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Follow action — follow a user on X.
5
+ * Ported from backend/routes/browser.js doFollow().
6
+ */
7
+
8
+ const { sleep, humanDelay, randDelay, naturalNavigate, humanPreAction, humanClick, detectStage } = require('./helpers');
9
+
10
+ // Follow button labels in multiple languages
11
+ const FOLLOW_LABELS = [
12
+ 'follow', 'seguir', 'suivre', 'folgen', 'تابع', 'フォロー',
13
+ 'segui', 'volgen', 'śledź', 'seguir', '关注', '팔로우',
14
+ ];
15
+
16
+ const FOLLOWING_LABELS = [
17
+ 'following', 'siguiendo', 'abonné', 'folgt', 'يتابعك', 'フォロー中',
18
+ 'following', 'volgend', 'obserwujesz', 'seguindo', '已关注', '팔로잉',
19
+ 'unfollow', 'dejar de seguir', 'ne plus suivre', 'entfolgen', 'إلغاء المتابعة',
20
+ ];
21
+
22
+ async function follow(page, payload) {
23
+ const { username } = payload;
24
+ if (!username) throw new Error('username required');
25
+
26
+ const cleanUsername = String(username).replace(/^@/, '').replace(/^.*x\.com\//, '');
27
+ await naturalNavigate(page, `https://x.com/${cleanUsername}`);
28
+ await humanPreAction(page);
29
+
30
+ // Check if page loaded properly
31
+ if (page.url().includes('/login') || page.url().includes('/i/flow')) {
32
+ throw new Error('Not logged in — open browser and login first');
33
+ }
34
+
35
+ // Check for suspended/not-found
36
+ const title = await page.title().catch(() => '');
37
+ const bodyText = await page.evaluate(() => document.body.innerText).catch(() => '');
38
+ if (/account suspended|doesn't exist|page doesn't exist/i.test(title + bodyText)) {
39
+ throw new Error(`Account @${cleanUsername} is suspended or not found`);
40
+ }
41
+
42
+ // Strategy 1: data-testid selectors
43
+ const testIdSelectors = [
44
+ `[data-testid="${cleanUsername}-follow"]`,
45
+ '[data-testid="follow"]',
46
+ ];
47
+ for (const sel of testIdSelectors) {
48
+ const btn = page.locator(sel).first();
49
+ if (await btn.isVisible({ timeout: 2000 }).catch(() => false)) {
50
+ await humanClick(page, btn);
51
+ await sleep(3000);
52
+ return { success: true, message: `Following @${cleanUsername}` };
53
+ }
54
+ }
55
+
56
+ // Strategy 2: scan buttons for follow labels
57
+ const buttons = page.locator('[role="button"], button');
58
+ const count = await buttons.count();
59
+ for (let i = 0; i < count; i++) {
60
+ const btn = buttons.nth(i);
61
+ const text = (await btn.innerText().catch(() => '')).toLowerCase().trim();
62
+ if (FOLLOW_LABELS.some(label => text === label || text.includes(label))) {
63
+ // Check if it's actually "following" (already following)
64
+ if (FOLLOWING_LABELS.some(label => text.includes(label))) continue;
65
+ await humanClick(page, btn);
66
+ await sleep(3000);
67
+ return { success: true, message: `Following @${cleanUsername}` };
68
+ }
69
+ }
70
+
71
+ // Check if already following
72
+ for (let i = 0; i < count; i++) {
73
+ const btn = buttons.nth(i);
74
+ const text = (await btn.innerText().catch(() => '')).toLowerCase().trim();
75
+ if (FOLLOWING_LABELS.some(label => text.includes(label))) {
76
+ return { success: true, message: `Already following @${cleanUsername}`, status: 'already_following' };
77
+ }
78
+ }
79
+
80
+ throw new Error(`Could not find follow button for @${cleanUsername}`);
81
+ }
82
+
83
+ module.exports = { follow };