@xkwdstore/agent 2.1.5 → 2.1.6

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,439 +1,439 @@
1
- 'use strict';
2
-
3
- /**
4
- * Canonical X session authentication verification (agent side).
5
- *
6
- * WHY THIS EXISTS
7
- * ---------------
8
- * "Chrome opened" is not "signed in". The start/restart/refresh paths used to
9
- * treat a launched persistent context as a successful session: a fresh profile
10
- * with stale or rejected cookies, a profile belonging to a DIFFERENT X account,
11
- * or an X challenge page all looked identical to a healthy login.
12
- *
13
- * This module is the ONE place that answers the authentication question, so the
14
- * machine worker, the direct runtime and the action/login endpoints agree on:
15
- *
16
- * authenticated | signed_out | wrong_account | challenge_required | unknown
17
- *
18
- * It deliberately verifies account identity from SIGNED-IN-ACCOUNT signals
19
- * (the profile link's handle / the account-switcher handle plus the presence of
20
- * the auth cookie pair) rather than from a home URL or a generic page layout.
21
- * A page can render a home-like shell while signed out, and a redirect to
22
- * /home says nothing about WHICH account is signed in.
23
- *
24
- * SAFETY
25
- * ------
26
- * - Never throws to a caller; every failure is a typed state + safe reason.
27
- * - Never reads or returns cookie VALUES; only names/presence/counts.
28
- * - Bounded: verification polls for a short budget then reports unknown.
29
- * - Challenge pages are reported as challenge_required so the operator is
30
- * asked to act instead of an automated flow guessing.
31
- */
32
-
33
- const AUTH_STATE = Object.freeze({
34
- AUTHENTICATED: 'authenticated',
35
- SIGNED_OUT: 'signed_out',
36
- WRONG_ACCOUNT: 'wrong_account',
37
- CHALLENGE_REQUIRED: 'challenge_required',
38
- UNKNOWN: 'unknown',
39
- });
40
-
41
- const CANONICAL_ORIGIN = 'https://x.com';
42
- const CANONICAL_HOME = 'https://x.com/home';
43
- const AUTH_COOKIE_NAMES = Object.freeze(['auth_token', 'ct0', 'twid']);
44
-
45
- // Paths on x.com that are NOT a handle in the profile link.
46
- const NON_HANDLE_PATHS = new Set([
47
- 'home', 'explore', 'notifications', 'messages', 'i', 'settings', 'compose',
48
- 'search', 'login', 'logout', 'signup', 'tos', 'privacy', 'account', 'jobs',
49
- 'connect_people', 'premium_sign_up',
50
- ]);
51
-
52
- function normalizeHandle(value) {
53
- if (typeof value !== 'string') return null;
54
- const v = value.trim().replace(/^@+/, '');
55
- if (!v) return null;
56
- return v.toLowerCase();
57
- }
58
-
59
- /** A syntactically plausible X handle (never an email/phone). */
60
- function asExpectedHandle(value) {
61
- if (typeof value !== 'string') return null;
62
- const v = value.trim().replace(/^@+/, '');
63
- return /^[A-Za-z0-9_]{1,15}$/.test(v) ? v.toLowerCase() : null;
64
- }
65
-
66
- /** True for a URL that belongs to an authorized X/Twitter web origin. */
67
- function isAuthorizedXUrl(value) {
68
- if (typeof value !== 'string' || !value) return false;
69
- try {
70
- const u = new URL(value);
71
- if (u.protocol !== 'https:' && u.protocol !== 'http:') return false;
72
- const host = u.hostname.toLowerCase();
73
- return host === 'x.com' || host.endsWith('.x.com') || host === 'twitter.com' || host.endsWith('.twitter.com');
74
- } catch {
75
- return false;
76
- }
77
- }
78
-
79
- /**
80
- * Classify a navigation/transport failure into a SAFE reason code. A proxy or
81
- * DNS failure is NOT a logout: conflating them would make the UI demand a
82
- * password for a network fault.
83
- */
84
- function classifyNavigationError(err) {
85
- const raw = String((err && err.message) || err || '');
86
- const lower = raw.toLowerCase();
87
- if (/timeout|timed out|etimedout/.test(lower)) {
88
- return { code: 'NAVIGATION_TIMEOUT', stage: 'navigation', reason: 'origin_navigation_timeout' };
89
- }
90
- if (/net::err_tunnel_connection_failed|proxy|407|tunnel/.test(lower)) {
91
- return { code: 'PROXY_NAVIGATION_FAILED', stage: 'proxy', reason: 'proxy_transport_failed' };
92
- }
93
- if (/net::err_name_not_resolved|enotfound|getaddrinfo/.test(lower)) {
94
- return { code: 'NAVIGATION_DNS_FAILED', stage: 'navigation', reason: 'origin_dns_failed' };
95
- }
96
- if (/net::err_connection|econnrefused|econnreset/.test(lower)) {
97
- return { code: 'NAVIGATION_UNREACHABLE', stage: 'navigation', reason: 'origin_unreachable' };
98
- }
99
- return { code: 'NAVIGATION_FAILED', stage: 'navigation', reason: 'origin_navigation_failed' };
100
- }
101
-
102
- /**
103
- * Summarize cookies WITHOUT exposing values. Used to decide whether a profile
104
- * already carries an X session (which must never be overwritten by stale
105
- * imported cookies).
106
- */
107
- function summarizeCookies(cookies) {
108
- const names = new Set();
109
- const list = Array.isArray(cookies) ? cookies : [];
110
- for (const c of list) {
111
- if (c && typeof c.name === 'string' && isAuthorizedXUrl(c.url || (`https://${String(c.domain || '').replace(/^\./, '')}/`))) {
112
- names.add(c.name);
113
- }
114
- }
115
- const present = AUTH_COOKIE_NAMES.filter((n) => names.has(n));
116
- return {
117
- count: list.length,
118
- authCookieNames: present,
119
- hasAuthToken: present.includes('auth_token'),
120
- hasCt0: present.includes('ct0'),
121
- hasTwid: present.includes('twid'),
122
- };
123
- }
124
-
125
- /** Read cookie facts from the live context; never returns values. */
126
- async function readCookieFacts(context) {
127
- try {
128
- if (!context || typeof context.cookies !== 'function') return null;
129
- const cookies = await context.cookies([CANONICAL_ORIGIN, 'https://twitter.com']);
130
- return summarizeCookies(cookies);
131
- } catch {
132
- return null;
133
- }
134
- }
135
-
136
- /** Read DOM-level signed-in/challenge signals. Never throws. */
137
- async function readDomSignals(page) {
138
- try {
139
- if (!page || typeof page.evaluate !== 'function') return null;
140
- if (typeof page.isClosed === 'function' && page.isClosed()) return null;
141
- const raw = await page.evaluate(() => {
142
- const q = (s) => { try { return document.querySelector(s); } catch { return null; } };
143
- const attr = (el, a) => { try { return el ? el.getAttribute(a) : null; } catch { return null; } };
144
- const text = (el, n) => { try { return el ? (el.innerText || el.textContent || '').slice(0, n || 300) : null; } catch { return null; } };
145
- const profileLink = q('a[data-testid="AppTabBar_Profile_Link"]');
146
- const switcher = q('[data-testid="SideNav_AccountSwitcher_Button"]');
147
- const userName = q('[data-testid="UserName"]');
148
- const loginForm = !!q('[data-testid="LoginForm"]')
149
- || !!q('input[autocomplete="username"]')
150
- || !!q('[data-testid="loginButton"]');
151
- const challengeEl = q('[data-testid="challenge"]')
152
- || q('iframe[src*="arkose"]')
153
- || q('iframe[src*="funcaptcha"]')
154
- || q('iframe[title*="captcha"]');
155
- const body = (document.body && (document.body.innerText || document.body.textContent)) || '';
156
- const head = body.slice(0, 4000);
157
- const challengeText = /verify you are human|unusual activity|login challenge|confirm you are a person|temporarily limited|authenticate your account/i.test(head);
158
- return {
159
- url: (typeof location !== 'undefined' && location.href) || null,
160
- profileHref: attr(profileLink, 'href'),
161
- switcherText: text(switcher),
162
- userName: text(userName, 120),
163
- loginForm,
164
- challenge: !!challengeEl || challengeText,
165
- };
166
- });
167
- return raw && typeof raw === 'object' ? raw : null;
168
- } catch {
169
- return null;
170
- }
171
- }
172
-
173
- function handleFromDom(dom) {
174
- if (!dom) return null;
175
- if (typeof dom.profileHref === 'string') {
176
- const m = /^\/([A-Za-z0-9_]{1,15})(?:[/?#]|$)/.exec(dom.profileHref);
177
- if (m && !NON_HANDLE_PATHS.has(m[1].toLowerCase())) return normalizeHandle(m[1]);
178
- }
179
- if (typeof dom.switcherText === 'string') {
180
- const m = /@([A-Za-z0-9_]{1,15})\b/.exec(dom.switcherText);
181
- if (m) return normalizeHandle(m[1]);
182
- }
183
- return null;
184
- }
185
-
186
- /**
187
- * Pure classification from the two observation sources. Exported so every
188
- * state can be unit-tested without a browser.
189
- *
190
- * @param {object} o
191
- * @param {object|null} o.dom
192
- * @param {object|null} o.cookieFacts
193
- * @param {string} [o.expectedUsername]
194
- * @returns {{authState:string, reason:string, stage:string, handle:string|null}}
195
- */
196
- function classifyAuth(o = {}) {
197
- const dom = o.dom || null;
198
- const facts = o.cookieFacts || null;
199
- const expected = asExpectedHandle(o.expectedUsername);
200
-
201
- if (!dom && !facts) {
202
- return { authState: AUTH_STATE.UNKNOWN, reason: 'no_browser_signal', stage: 'verify', handle: null };
203
- }
204
-
205
- const url = dom && typeof dom.url === 'string' ? dom.url : null;
206
-
207
- // Challenge first: an X challenge can be shown on /home, /login or any flow.
208
- if (dom && dom.challenge) {
209
- return { authState: AUTH_STATE.CHALLENGE_REQUIRED, reason: 'x_challenge_present', stage: 'verify', handle: null };
210
- }
211
- if (url && /\/account\/access|\/i\/flow\/login(?:[/?]|$)|\/login(?:[/?]|$)/.test(url)) {
212
- // A login URL alone is signed_out evidence, but a challenge URL is stronger.
213
- if (/\/account\/access/.test(url)) {
214
- return { authState: AUTH_STATE.CHALLENGE_REQUIRED, reason: 'x_account_access_challenge', stage: 'verify', handle: null };
215
- }
216
- }
217
-
218
- const handle = dom ? handleFromDom(dom) : null;
219
- const hasAuthToken = !!(facts && facts.hasAuthToken);
220
- const hasCt0 = !!(facts && facts.hasCt0);
221
-
222
- // A signed-in DOM signal is only trusted together with the auth cookie pair.
223
- const signedInSignal = !!(handle || (dom && dom.switcherText));
224
-
225
- if (signedInSignal && handle && expected && handle !== expected) {
226
- return { authState: AUTH_STATE.WRONG_ACCOUNT, reason: 'signed_in_handle_mismatch', stage: 'verify', handle };
227
- }
228
-
229
- if (hasAuthToken && hasCt0 && signedInSignal) {
230
- return { authState: AUTH_STATE.AUTHENTICATED, reason: 'signed_in_signal', stage: 'verify', handle };
231
- }
232
-
233
- // The auth pair is present but the page has not exposed a trusted signed-in
234
- // signal (still loading, different surface, or an A/B shell). Preserve it and
235
- // report unknown rather than claiming either success or logout.
236
- if (hasAuthToken && hasCt0) {
237
- return { authState: AUTH_STATE.UNKNOWN, reason: 'signed_in_signal_missing', stage: 'verify', handle };
238
- }
239
-
240
- if (dom && dom.loginForm) {
241
- return { authState: AUTH_STATE.SIGNED_OUT, reason: 'login_form_present', stage: 'verify', handle };
242
- }
243
- if (url && /\/(?:i\/flow\/login|login)(?:[/?]|$)/.test(url)) {
244
- return { authState: AUTH_STATE.SIGNED_OUT, reason: 'login_url', stage: 'verify', handle };
245
- }
246
- if (hasAuthToken && !hasCt0) {
247
- return { authState: AUTH_STATE.SIGNED_OUT, reason: 'csrf_cookie_missing', stage: 'verify', handle };
248
- }
249
- if (facts && facts.count === 0 && dom) {
250
- return { authState: AUTH_STATE.SIGNED_OUT, reason: 'auth_cookies_absent', stage: 'verify', handle };
251
- }
252
-
253
- return { authState: AUTH_STATE.UNKNOWN, reason: 'unclassified_surface', stage: 'verify', handle };
254
- }
255
-
256
- /**
257
- * Verify the live X session, bounded and idempotent. Polls until a terminal
258
- * state is observed or the budget elapses, then returns the last observation.
259
- *
260
- * @param {object} page
261
- * @param {object} context
262
- * @param {{expectedUsername?:string, timeoutMs?:number, pollMs?:number}} [opts]
263
- */
264
- async function verifyXAuth(page, context, opts = {}) {
265
- const timeoutMs = Number.isFinite(opts.timeoutMs) ? Math.max(0, opts.timeoutMs) : 8000;
266
- const pollMs = Number.isFinite(opts.pollMs) ? Math.max(50, opts.pollMs) : 500;
267
- const canDom = !!(page && typeof page.evaluate === 'function');
268
- const canCookies = !!(context && typeof context.cookies === 'function');
269
- // A page/context that exposes no observation surface (legacy test doubles or
270
- // a non-browser caller) cannot be verified. Return immediately: waiting the
271
- // full budget would stall a launch for no benefit.
272
- if (!canDom && !canCookies) {
273
- return { authState: AUTH_STATE.UNKNOWN, reason: 'no_browser_signal', stage: 'verify', handle: null, url: null, browserReady: true };
274
- }
275
- const deadline = Date.now() + timeoutMs;
276
- let last = { authState: AUTH_STATE.UNKNOWN, reason: 'not_observed', stage: 'verify', handle: null };
277
- for (;;) {
278
- const [dom, cookieFacts] = await Promise.all([readDomSignals(page), readCookieFacts(context)]);
279
- last = classifyAuth({ dom, cookieFacts, expectedUsername: opts.expectedUsername });
280
- last.url = dom && dom.url ? dom.url : null;
281
- last.browserReady = true;
282
- // Without DOM signals a signed-in account cannot be proven, and polling will
283
- // not change that. Stop after the first observation.
284
- if (last.authState !== AUTH_STATE.UNKNOWN || !canDom) return last;
285
- if (Date.now() >= deadline) return last;
286
- await new Promise((r) => setTimeout(r, Math.min(pollMs, Math.max(0, deadline - Date.now()))));
287
- }
288
- }
289
-
290
- /**
291
- * The canonical startup sequence shared by the machine worker and the direct
292
- * runtime:
293
- *
294
- * 1. navigate to the canonical X origin (a configured authorized URL is
295
- * honoured; anything else is refused),
296
- * 2. verify the EXISTING session before touching cookie state,
297
- * 3. authenticated / wrong_account / challenge_required -> preserve as-is,
298
- * 4. signed_out (or unverifiable profile with no auth cookies) + eligible
299
- * bootstrap cookies -> apply them with their original scope, verify again,
300
- * 5. return the terminal state.
301
- *
302
- * The sequence never overwrites a session that is already signed in and never
303
- * loops: the second verification is the last one.
304
- *
305
- * @param {object} o
306
- * @param {object} o.page
307
- * @param {object} o.context
308
- * @param {object[]|null} o.cookies — already-normalized bootstrap cookies
309
- * @param {string} [o.url]
310
- * @param {string} [o.expectedUsername]
311
- * @param {function} [o.applyCookies] — async (context, cookies) => { ok, state, ... }
312
- * @param {number} [o.navigationTimeoutMs]
313
- * @param {number} [o.verifyTimeoutMs]
314
- */
315
- async function restoreAndVerify(o = {}) {
316
- const { page, context, cookies, applyCookies } = o;
317
- const requested = typeof o.url === 'string' && o.url ? o.url : CANONICAL_HOME;
318
- const target = isAuthorizedXUrl(requested) ? requested : CANONICAL_HOME;
319
- const navigationTimeoutMs = Number.isFinite(o.navigationTimeoutMs) ? o.navigationTimeoutMs : 45000;
320
- const verifyTimeoutMs = Number.isFinite(o.verifyTimeoutMs) ? o.verifyTimeoutMs : 8000;
321
-
322
- const out = {
323
- authState: AUTH_STATE.UNKNOWN,
324
- reason: 'not_verified',
325
- stage: 'navigation',
326
- handle: null,
327
- url: null,
328
- browserReady: true,
329
- cookieState: null,
330
- cookieApplied: 0,
331
- cookieRejected: 0,
332
- navigationOk: false,
333
- };
334
-
335
- // ── 1. canonical origin ───────────────────────────────────────────────────
336
- try {
337
- if (typeof page.goto !== 'function') throw Object.assign(new Error('page cannot navigate'), { code: 'NO_PAGE' });
338
- await page.goto(target, { waitUntil: 'domcontentloaded', timeout: navigationTimeoutMs });
339
- out.navigationOk = true;
340
- } catch (err) {
341
- const nav = classifyNavigationError(err);
342
- return { ...out, authState: AUTH_STATE.UNKNOWN, reason: nav.reason, stage: nav.stage, code: nav.code };
343
- }
344
-
345
- // ── 2. verify the existing session BEFORE any cookie write ────────────────
346
- let first;
347
- try {
348
- first = await verifyXAuth(page, context, { expectedUsername: o.expectedUsername, timeoutMs: verifyTimeoutMs });
349
- } catch {
350
- first = { authState: AUTH_STATE.UNKNOWN, reason: 'verify_failed', stage: 'verify', handle: null };
351
- }
352
- out.authState = first.authState;
353
- out.reason = first.reason;
354
- out.stage = first.stage;
355
- out.handle = first.handle || null;
356
- out.url = first.url || null;
357
-
358
- if (first.authState === AUTH_STATE.AUTHENTICATED
359
- || first.authState === AUTH_STATE.WRONG_ACCOUNT
360
- || first.authState === AUTH_STATE.CHALLENGE_REQUIRED) {
361
- return out;
362
- }
363
-
364
- // ── 3. eligible bootstrap cookies? ────────────────────────────────────────
365
- const eligible = first.authState === AUTH_STATE.SIGNED_OUT
366
- || first.authState === AUTH_STATE.UNKNOWN;
367
- const hasBootstrap = Array.isArray(cookies) && cookies.length > 0;
368
- if (!eligible || !hasBootstrap || typeof applyCookies !== 'function') {
369
- return out;
370
- }
371
-
372
- let applied;
373
- try {
374
- applied = await applyCookies(context, cookies);
375
- } catch (err) {
376
- applied = { ok: false, state: 'rejected', reason: 'cookie_injection_failed', applied: 0, rejected: cookies.length };
377
- }
378
- out.cookieState = applied && applied.state ? applied.state : (applied && applied.ok ? 'accepted' : 'rejected');
379
- out.cookieApplied = (applied && applied.applied) || 0;
380
- out.cookieRejected = (applied && applied.rejected) || 0;
381
- out.stage = 'cookie_restore';
382
- if (!applied || applied.ok !== true || out.cookieApplied === 0) {
383
- out.reason = (applied && applied.reason) || 'cookie_restore_failed';
384
- out.code = 'COOKIE_RESTORE_FAILED';
385
- return out;
386
- }
387
-
388
- // ── 4. verify again after the bootstrap write ─────────────────────────────
389
- try {
390
- await page.goto(CANONICAL_HOME, { waitUntil: 'domcontentloaded', timeout: navigationTimeoutMs });
391
- } catch (err) {
392
- const nav = classifyNavigationError(err);
393
- return { ...out, authState: AUTH_STATE.UNKNOWN, reason: nav.reason, stage: nav.stage, code: nav.code };
394
- }
395
- let second;
396
- try {
397
- second = await verifyXAuth(page, context, { expectedUsername: o.expectedUsername, timeoutMs: verifyTimeoutMs });
398
- } catch {
399
- second = { authState: AUTH_STATE.UNKNOWN, reason: 'verify_failed', stage: 'verify', handle: null };
400
- }
401
- out.authState = second.authState;
402
- out.reason = second.reason;
403
- out.stage = 'verify';
404
- out.handle = second.handle || null;
405
- out.url = second.url || null;
406
- return out;
407
- }
408
-
409
- /** Safe, non-secret summary for logs/API responses. */
410
- function authSummary(verified) {
411
- const v = verified || {};
412
- const state = typeof v.authState === 'string' ? v.authState : AUTH_STATE.UNKNOWN;
413
- return {
414
- authState: state,
415
- loggedIn: state === AUTH_STATE.AUTHENTICATED,
416
- reason: v.reason || null,
417
- stage: v.stage || null,
418
- handle: v.handle || null,
419
- browserReady: v.browserReady === true,
420
- };
421
- }
422
-
423
- module.exports = {
424
- AUTH_STATE,
425
- CANONICAL_ORIGIN,
426
- CANONICAL_HOME,
427
- AUTH_COOKIE_NAMES,
428
- normalizeHandle,
429
- asExpectedHandle,
430
- isAuthorizedXUrl,
431
- classifyNavigationError,
432
- summarizeCookies,
433
- readCookieFacts,
434
- readDomSignals,
435
- classifyAuth,
436
- verifyXAuth,
437
- restoreAndVerify,
438
- authSummary,
439
- };
1
+ 'use strict';
2
+
3
+ /**
4
+ * Canonical X session authentication verification (agent side).
5
+ *
6
+ * WHY THIS EXISTS
7
+ * ---------------
8
+ * "Chrome opened" is not "signed in". The start/restart/refresh paths used to
9
+ * treat a launched persistent context as a successful session: a fresh profile
10
+ * with stale or rejected cookies, a profile belonging to a DIFFERENT X account,
11
+ * or an X challenge page all looked identical to a healthy login.
12
+ *
13
+ * This module is the ONE place that answers the authentication question, so the
14
+ * machine worker, the direct runtime and the action/login endpoints agree on:
15
+ *
16
+ * authenticated | signed_out | wrong_account | challenge_required | unknown
17
+ *
18
+ * It deliberately verifies account identity from SIGNED-IN-ACCOUNT signals
19
+ * (the profile link's handle / the account-switcher handle plus the presence of
20
+ * the auth cookie pair) rather than from a home URL or a generic page layout.
21
+ * A page can render a home-like shell while signed out, and a redirect to
22
+ * /home says nothing about WHICH account is signed in.
23
+ *
24
+ * SAFETY
25
+ * ------
26
+ * - Never throws to a caller; every failure is a typed state + safe reason.
27
+ * - Never reads or returns cookie VALUES; only names/presence/counts.
28
+ * - Bounded: verification polls for a short budget then reports unknown.
29
+ * - Challenge pages are reported as challenge_required so the operator is
30
+ * asked to act instead of an automated flow guessing.
31
+ */
32
+
33
+ const AUTH_STATE = Object.freeze({
34
+ AUTHENTICATED: 'authenticated',
35
+ SIGNED_OUT: 'signed_out',
36
+ WRONG_ACCOUNT: 'wrong_account',
37
+ CHALLENGE_REQUIRED: 'challenge_required',
38
+ UNKNOWN: 'unknown',
39
+ });
40
+
41
+ const CANONICAL_ORIGIN = 'https://x.com';
42
+ const CANONICAL_HOME = 'https://x.com/home';
43
+ const AUTH_COOKIE_NAMES = Object.freeze(['auth_token', 'ct0', 'twid']);
44
+
45
+ // Paths on x.com that are NOT a handle in the profile link.
46
+ const NON_HANDLE_PATHS = new Set([
47
+ 'home', 'explore', 'notifications', 'messages', 'i', 'settings', 'compose',
48
+ 'search', 'login', 'logout', 'signup', 'tos', 'privacy', 'account', 'jobs',
49
+ 'connect_people', 'premium_sign_up',
50
+ ]);
51
+
52
+ function normalizeHandle(value) {
53
+ if (typeof value !== 'string') return null;
54
+ const v = value.trim().replace(/^@+/, '');
55
+ if (!v) return null;
56
+ return v.toLowerCase();
57
+ }
58
+
59
+ /** A syntactically plausible X handle (never an email/phone). */
60
+ function asExpectedHandle(value) {
61
+ if (typeof value !== 'string') return null;
62
+ const v = value.trim().replace(/^@+/, '');
63
+ return /^[A-Za-z0-9_]{1,15}$/.test(v) ? v.toLowerCase() : null;
64
+ }
65
+
66
+ /** True for a URL that belongs to an authorized X/Twitter web origin. */
67
+ function isAuthorizedXUrl(value) {
68
+ if (typeof value !== 'string' || !value) return false;
69
+ try {
70
+ const u = new URL(value);
71
+ if (u.protocol !== 'https:' && u.protocol !== 'http:') return false;
72
+ const host = u.hostname.toLowerCase();
73
+ return host === 'x.com' || host.endsWith('.x.com') || host === 'twitter.com' || host.endsWith('.twitter.com');
74
+ } catch {
75
+ return false;
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Classify a navigation/transport failure into a SAFE reason code. A proxy or
81
+ * DNS failure is NOT a logout: conflating them would make the UI demand a
82
+ * password for a network fault.
83
+ */
84
+ function classifyNavigationError(err) {
85
+ const raw = String((err && err.message) || err || '');
86
+ const lower = raw.toLowerCase();
87
+ if (/timeout|timed out|etimedout/.test(lower)) {
88
+ return { code: 'NAVIGATION_TIMEOUT', stage: 'navigation', reason: 'origin_navigation_timeout' };
89
+ }
90
+ if (/net::err_tunnel_connection_failed|proxy|407|tunnel/.test(lower)) {
91
+ return { code: 'PROXY_NAVIGATION_FAILED', stage: 'proxy', reason: 'proxy_transport_failed' };
92
+ }
93
+ if (/net::err_name_not_resolved|enotfound|getaddrinfo/.test(lower)) {
94
+ return { code: 'NAVIGATION_DNS_FAILED', stage: 'navigation', reason: 'origin_dns_failed' };
95
+ }
96
+ if (/net::err_connection|econnrefused|econnreset/.test(lower)) {
97
+ return { code: 'NAVIGATION_UNREACHABLE', stage: 'navigation', reason: 'origin_unreachable' };
98
+ }
99
+ return { code: 'NAVIGATION_FAILED', stage: 'navigation', reason: 'origin_navigation_failed' };
100
+ }
101
+
102
+ /**
103
+ * Summarize cookies WITHOUT exposing values. Used to decide whether a profile
104
+ * already carries an X session (which must never be overwritten by stale
105
+ * imported cookies).
106
+ */
107
+ function summarizeCookies(cookies) {
108
+ const names = new Set();
109
+ const list = Array.isArray(cookies) ? cookies : [];
110
+ for (const c of list) {
111
+ if (c && typeof c.name === 'string' && isAuthorizedXUrl(c.url || (`https://${String(c.domain || '').replace(/^\./, '')}/`))) {
112
+ names.add(c.name);
113
+ }
114
+ }
115
+ const present = AUTH_COOKIE_NAMES.filter((n) => names.has(n));
116
+ return {
117
+ count: list.length,
118
+ authCookieNames: present,
119
+ hasAuthToken: present.includes('auth_token'),
120
+ hasCt0: present.includes('ct0'),
121
+ hasTwid: present.includes('twid'),
122
+ };
123
+ }
124
+
125
+ /** Read cookie facts from the live context; never returns values. */
126
+ async function readCookieFacts(context) {
127
+ try {
128
+ if (!context || typeof context.cookies !== 'function') return null;
129
+ const cookies = await context.cookies([CANONICAL_ORIGIN, 'https://twitter.com']);
130
+ return summarizeCookies(cookies);
131
+ } catch {
132
+ return null;
133
+ }
134
+ }
135
+
136
+ /** Read DOM-level signed-in/challenge signals. Never throws. */
137
+ async function readDomSignals(page) {
138
+ try {
139
+ if (!page || typeof page.evaluate !== 'function') return null;
140
+ if (typeof page.isClosed === 'function' && page.isClosed()) return null;
141
+ const raw = await page.evaluate(() => {
142
+ const q = (s) => { try { return document.querySelector(s); } catch { return null; } };
143
+ const attr = (el, a) => { try { return el ? el.getAttribute(a) : null; } catch { return null; } };
144
+ const text = (el, n) => { try { return el ? (el.innerText || el.textContent || '').slice(0, n || 300) : null; } catch { return null; } };
145
+ const profileLink = q('a[data-testid="AppTabBar_Profile_Link"]');
146
+ const switcher = q('[data-testid="SideNav_AccountSwitcher_Button"]');
147
+ const userName = q('[data-testid="UserName"]');
148
+ const loginForm = !!q('[data-testid="LoginForm"]')
149
+ || !!q('input[autocomplete="username"]')
150
+ || !!q('[data-testid="loginButton"]');
151
+ const challengeEl = q('[data-testid="challenge"]')
152
+ || q('iframe[src*="arkose"]')
153
+ || q('iframe[src*="funcaptcha"]')
154
+ || q('iframe[title*="captcha"]');
155
+ const body = (document.body && (document.body.innerText || document.body.textContent)) || '';
156
+ const head = body.slice(0, 4000);
157
+ const challengeText = /verify you are human|unusual activity|login challenge|confirm you are a person|temporarily limited|authenticate your account/i.test(head);
158
+ return {
159
+ url: (typeof location !== 'undefined' && location.href) || null,
160
+ profileHref: attr(profileLink, 'href'),
161
+ switcherText: text(switcher),
162
+ userName: text(userName, 120),
163
+ loginForm,
164
+ challenge: !!challengeEl || challengeText,
165
+ };
166
+ });
167
+ return raw && typeof raw === 'object' ? raw : null;
168
+ } catch {
169
+ return null;
170
+ }
171
+ }
172
+
173
+ function handleFromDom(dom) {
174
+ if (!dom) return null;
175
+ if (typeof dom.profileHref === 'string') {
176
+ const m = /^\/([A-Za-z0-9_]{1,15})(?:[/?#]|$)/.exec(dom.profileHref);
177
+ if (m && !NON_HANDLE_PATHS.has(m[1].toLowerCase())) return normalizeHandle(m[1]);
178
+ }
179
+ if (typeof dom.switcherText === 'string') {
180
+ const m = /@([A-Za-z0-9_]{1,15})\b/.exec(dom.switcherText);
181
+ if (m) return normalizeHandle(m[1]);
182
+ }
183
+ return null;
184
+ }
185
+
186
+ /**
187
+ * Pure classification from the two observation sources. Exported so every
188
+ * state can be unit-tested without a browser.
189
+ *
190
+ * @param {object} o
191
+ * @param {object|null} o.dom
192
+ * @param {object|null} o.cookieFacts
193
+ * @param {string} [o.expectedUsername]
194
+ * @returns {{authState:string, reason:string, stage:string, handle:string|null}}
195
+ */
196
+ function classifyAuth(o = {}) {
197
+ const dom = o.dom || null;
198
+ const facts = o.cookieFacts || null;
199
+ const expected = asExpectedHandle(o.expectedUsername);
200
+
201
+ if (!dom && !facts) {
202
+ return { authState: AUTH_STATE.UNKNOWN, reason: 'no_browser_signal', stage: 'verify', handle: null };
203
+ }
204
+
205
+ const url = dom && typeof dom.url === 'string' ? dom.url : null;
206
+
207
+ // Challenge first: an X challenge can be shown on /home, /login or any flow.
208
+ if (dom && dom.challenge) {
209
+ return { authState: AUTH_STATE.CHALLENGE_REQUIRED, reason: 'x_challenge_present', stage: 'verify', handle: null };
210
+ }
211
+ if (url && /\/account\/access|\/i\/flow\/login(?:[/?]|$)|\/login(?:[/?]|$)/.test(url)) {
212
+ // A login URL alone is signed_out evidence, but a challenge URL is stronger.
213
+ if (/\/account\/access/.test(url)) {
214
+ return { authState: AUTH_STATE.CHALLENGE_REQUIRED, reason: 'x_account_access_challenge', stage: 'verify', handle: null };
215
+ }
216
+ }
217
+
218
+ const handle = dom ? handleFromDom(dom) : null;
219
+ const hasAuthToken = !!(facts && facts.hasAuthToken);
220
+ const hasCt0 = !!(facts && facts.hasCt0);
221
+
222
+ // A signed-in DOM signal is only trusted together with the auth cookie pair.
223
+ const signedInSignal = !!(handle || (dom && dom.switcherText));
224
+
225
+ if (signedInSignal && handle && expected && handle !== expected) {
226
+ return { authState: AUTH_STATE.WRONG_ACCOUNT, reason: 'signed_in_handle_mismatch', stage: 'verify', handle };
227
+ }
228
+
229
+ if (hasAuthToken && hasCt0 && signedInSignal) {
230
+ return { authState: AUTH_STATE.AUTHENTICATED, reason: 'signed_in_signal', stage: 'verify', handle };
231
+ }
232
+
233
+ // The auth pair is present but the page has not exposed a trusted signed-in
234
+ // signal (still loading, different surface, or an A/B shell). Preserve it and
235
+ // report unknown rather than claiming either success or logout.
236
+ if (hasAuthToken && hasCt0) {
237
+ return { authState: AUTH_STATE.UNKNOWN, reason: 'signed_in_signal_missing', stage: 'verify', handle };
238
+ }
239
+
240
+ if (dom && dom.loginForm) {
241
+ return { authState: AUTH_STATE.SIGNED_OUT, reason: 'login_form_present', stage: 'verify', handle };
242
+ }
243
+ if (url && /\/(?:i\/flow\/login|login)(?:[/?]|$)/.test(url)) {
244
+ return { authState: AUTH_STATE.SIGNED_OUT, reason: 'login_url', stage: 'verify', handle };
245
+ }
246
+ if (hasAuthToken && !hasCt0) {
247
+ return { authState: AUTH_STATE.SIGNED_OUT, reason: 'csrf_cookie_missing', stage: 'verify', handle };
248
+ }
249
+ if (facts && facts.count === 0 && dom) {
250
+ return { authState: AUTH_STATE.SIGNED_OUT, reason: 'auth_cookies_absent', stage: 'verify', handle };
251
+ }
252
+
253
+ return { authState: AUTH_STATE.UNKNOWN, reason: 'unclassified_surface', stage: 'verify', handle };
254
+ }
255
+
256
+ /**
257
+ * Verify the live X session, bounded and idempotent. Polls until a terminal
258
+ * state is observed or the budget elapses, then returns the last observation.
259
+ *
260
+ * @param {object} page
261
+ * @param {object} context
262
+ * @param {{expectedUsername?:string, timeoutMs?:number, pollMs?:number}} [opts]
263
+ */
264
+ async function verifyXAuth(page, context, opts = {}) {
265
+ const timeoutMs = Number.isFinite(opts.timeoutMs) ? Math.max(0, opts.timeoutMs) : 8000;
266
+ const pollMs = Number.isFinite(opts.pollMs) ? Math.max(50, opts.pollMs) : 500;
267
+ const canDom = !!(page && typeof page.evaluate === 'function');
268
+ const canCookies = !!(context && typeof context.cookies === 'function');
269
+ // A page/context that exposes no observation surface (legacy test doubles or
270
+ // a non-browser caller) cannot be verified. Return immediately: waiting the
271
+ // full budget would stall a launch for no benefit.
272
+ if (!canDom && !canCookies) {
273
+ return { authState: AUTH_STATE.UNKNOWN, reason: 'no_browser_signal', stage: 'verify', handle: null, url: null, browserReady: true };
274
+ }
275
+ const deadline = Date.now() + timeoutMs;
276
+ let last = { authState: AUTH_STATE.UNKNOWN, reason: 'not_observed', stage: 'verify', handle: null };
277
+ for (;;) {
278
+ const [dom, cookieFacts] = await Promise.all([readDomSignals(page), readCookieFacts(context)]);
279
+ last = classifyAuth({ dom, cookieFacts, expectedUsername: opts.expectedUsername });
280
+ last.url = dom && dom.url ? dom.url : null;
281
+ last.browserReady = true;
282
+ // Without DOM signals a signed-in account cannot be proven, and polling will
283
+ // not change that. Stop after the first observation.
284
+ if (last.authState !== AUTH_STATE.UNKNOWN || !canDom) return last;
285
+ if (Date.now() >= deadline) return last;
286
+ await new Promise((r) => setTimeout(r, Math.min(pollMs, Math.max(0, deadline - Date.now()))));
287
+ }
288
+ }
289
+
290
+ /**
291
+ * The canonical startup sequence shared by the machine worker and the direct
292
+ * runtime:
293
+ *
294
+ * 1. navigate to the canonical X origin (a configured authorized URL is
295
+ * honoured; anything else is refused),
296
+ * 2. verify the EXISTING session before touching cookie state,
297
+ * 3. authenticated / wrong_account / challenge_required -> preserve as-is,
298
+ * 4. signed_out (or unverifiable profile with no auth cookies) + eligible
299
+ * bootstrap cookies -> apply them with their original scope, verify again,
300
+ * 5. return the terminal state.
301
+ *
302
+ * The sequence never overwrites a session that is already signed in and never
303
+ * loops: the second verification is the last one.
304
+ *
305
+ * @param {object} o
306
+ * @param {object} o.page
307
+ * @param {object} o.context
308
+ * @param {object[]|null} o.cookies — already-normalized bootstrap cookies
309
+ * @param {string} [o.url]
310
+ * @param {string} [o.expectedUsername]
311
+ * @param {function} [o.applyCookies] — async (context, cookies) => { ok, state, ... }
312
+ * @param {number} [o.navigationTimeoutMs]
313
+ * @param {number} [o.verifyTimeoutMs]
314
+ */
315
+ async function restoreAndVerify(o = {}) {
316
+ const { page, context, cookies, applyCookies } = o;
317
+ const requested = typeof o.url === 'string' && o.url ? o.url : CANONICAL_HOME;
318
+ const target = isAuthorizedXUrl(requested) ? requested : CANONICAL_HOME;
319
+ const navigationTimeoutMs = Number.isFinite(o.navigationTimeoutMs) ? o.navigationTimeoutMs : 45000;
320
+ const verifyTimeoutMs = Number.isFinite(o.verifyTimeoutMs) ? o.verifyTimeoutMs : 8000;
321
+
322
+ const out = {
323
+ authState: AUTH_STATE.UNKNOWN,
324
+ reason: 'not_verified',
325
+ stage: 'navigation',
326
+ handle: null,
327
+ url: null,
328
+ browserReady: true,
329
+ cookieState: null,
330
+ cookieApplied: 0,
331
+ cookieRejected: 0,
332
+ navigationOk: false,
333
+ };
334
+
335
+ // ── 1. canonical origin ───────────────────────────────────────────────────
336
+ try {
337
+ if (typeof page.goto !== 'function') throw Object.assign(new Error('page cannot navigate'), { code: 'NO_PAGE' });
338
+ await page.goto(target, { waitUntil: 'domcontentloaded', timeout: navigationTimeoutMs });
339
+ out.navigationOk = true;
340
+ } catch (err) {
341
+ const nav = classifyNavigationError(err);
342
+ return { ...out, authState: AUTH_STATE.UNKNOWN, reason: nav.reason, stage: nav.stage, code: nav.code };
343
+ }
344
+
345
+ // ── 2. verify the existing session BEFORE any cookie write ────────────────
346
+ let first;
347
+ try {
348
+ first = await verifyXAuth(page, context, { expectedUsername: o.expectedUsername, timeoutMs: verifyTimeoutMs });
349
+ } catch {
350
+ first = { authState: AUTH_STATE.UNKNOWN, reason: 'verify_failed', stage: 'verify', handle: null };
351
+ }
352
+ out.authState = first.authState;
353
+ out.reason = first.reason;
354
+ out.stage = first.stage;
355
+ out.handle = first.handle || null;
356
+ out.url = first.url || null;
357
+
358
+ if (first.authState === AUTH_STATE.AUTHENTICATED
359
+ || first.authState === AUTH_STATE.WRONG_ACCOUNT
360
+ || first.authState === AUTH_STATE.CHALLENGE_REQUIRED) {
361
+ return out;
362
+ }
363
+
364
+ // ── 3. eligible bootstrap cookies? ────────────────────────────────────────
365
+ const eligible = first.authState === AUTH_STATE.SIGNED_OUT
366
+ || first.authState === AUTH_STATE.UNKNOWN;
367
+ const hasBootstrap = Array.isArray(cookies) && cookies.length > 0;
368
+ if (!eligible || !hasBootstrap || typeof applyCookies !== 'function') {
369
+ return out;
370
+ }
371
+
372
+ let applied;
373
+ try {
374
+ applied = await applyCookies(context, cookies);
375
+ } catch (err) {
376
+ applied = { ok: false, state: 'rejected', reason: 'cookie_injection_failed', applied: 0, rejected: cookies.length };
377
+ }
378
+ out.cookieState = applied && applied.state ? applied.state : (applied && applied.ok ? 'accepted' : 'rejected');
379
+ out.cookieApplied = (applied && applied.applied) || 0;
380
+ out.cookieRejected = (applied && applied.rejected) || 0;
381
+ out.stage = 'cookie_restore';
382
+ if (!applied || applied.ok !== true || out.cookieApplied === 0) {
383
+ out.reason = (applied && applied.reason) || 'cookie_restore_failed';
384
+ out.code = 'COOKIE_RESTORE_FAILED';
385
+ return out;
386
+ }
387
+
388
+ // ── 4. verify again after the bootstrap write ─────────────────────────────
389
+ try {
390
+ await page.goto(CANONICAL_HOME, { waitUntil: 'domcontentloaded', timeout: navigationTimeoutMs });
391
+ } catch (err) {
392
+ const nav = classifyNavigationError(err);
393
+ return { ...out, authState: AUTH_STATE.UNKNOWN, reason: nav.reason, stage: nav.stage, code: nav.code };
394
+ }
395
+ let second;
396
+ try {
397
+ second = await verifyXAuth(page, context, { expectedUsername: o.expectedUsername, timeoutMs: verifyTimeoutMs });
398
+ } catch {
399
+ second = { authState: AUTH_STATE.UNKNOWN, reason: 'verify_failed', stage: 'verify', handle: null };
400
+ }
401
+ out.authState = second.authState;
402
+ out.reason = second.reason;
403
+ out.stage = 'verify';
404
+ out.handle = second.handle || null;
405
+ out.url = second.url || null;
406
+ return out;
407
+ }
408
+
409
+ /** Safe, non-secret summary for logs/API responses. */
410
+ function authSummary(verified) {
411
+ const v = verified || {};
412
+ const state = typeof v.authState === 'string' ? v.authState : AUTH_STATE.UNKNOWN;
413
+ return {
414
+ authState: state,
415
+ loggedIn: state === AUTH_STATE.AUTHENTICATED,
416
+ reason: v.reason || null,
417
+ stage: v.stage || null,
418
+ handle: v.handle || null,
419
+ browserReady: v.browserReady === true,
420
+ };
421
+ }
422
+
423
+ module.exports = {
424
+ AUTH_STATE,
425
+ CANONICAL_ORIGIN,
426
+ CANONICAL_HOME,
427
+ AUTH_COOKIE_NAMES,
428
+ normalizeHandle,
429
+ asExpectedHandle,
430
+ isAuthorizedXUrl,
431
+ classifyNavigationError,
432
+ summarizeCookies,
433
+ readCookieFacts,
434
+ readDomSignals,
435
+ classifyAuth,
436
+ verifyXAuth,
437
+ restoreAndVerify,
438
+ authSummary,
439
+ };