/** * X access. * - search(): logged-in GraphQL SearchTimeline ("Latest") with the user's own cookies * - profile(): public profile page (server-rendered, no login) * - tweet(): one tweet by id via the public syndication endpoint (no login) * - resolveTco(): follow a t.co short link */ const db = require('../db') const { UA, extractPayloads, tweetsFrom, decodeEntities } = require('./parse') const FALLBACK_BEARER = 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA' const FEATURES = [ 'rweb_video_screen_enabled', 'rweb_cashtags_enabled', 'profile_label_improvements_pcf_label_in_post_enabled', 'responsive_web_profile_redirect_enabled', 'rweb_tipjar_consumption_enabled', 'verified_phone_label_enabled', 'creator_subscriptions_tweet_preview_api_enabled', 'responsive_web_graphql_timeline_navigation_enabled', 'premium_content_api_read_enabled', 'communities_web_enable_tweet_community_results_fetch', 'c9s_tweet_anatomy_moderator_badge_enabled', 'responsive_web_grok_analyze_button_fetch_trends_enabled', 'responsive_web_grok_analyze_post_followups_enabled', 'rweb_cashtags_composer_attachment_enabled', 'responsive_web_jetfuel_frame', 'rweb_sports_post_context_enabled', 'x_elections_post_context_enabled', 'responsive_web_grok_share_attachment_enabled', 'responsive_web_grok_annotations_enabled', 'articles_preview_enabled', 'responsive_web_edit_tweet_api_enabled', 'graphql_is_translatable_rweb_tweet_is_translatable_enabled', 'view_counts_everywhere_api_enabled', 'longform_notetweets_consumption_enabled', 'responsive_web_twitter_article_tweet_consumption_enabled', 'content_disclosure_indicator_enabled', 'content_disclosure_ai_generated_indicator_enabled', 'responsive_web_grok_show_grok_translated_post', 'responsive_web_grok_analysis_button_from_backend', 'post_ctas_fetch_enabled', 'freedom_of_speech_not_reach_fetch_enabled', 'standardized_nudges_misinfo', 'tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled', 'longform_notetweets_rich_text_read_enabled', 'longform_notetweets_inline_media_enabled', 'responsive_web_grok_image_annotation_enabled', 'responsive_web_grok_community_note_auto_translation_is_enabled', 'responsive_web_enhance_cards_enabled', ] class XError extends Error { constructor(message, extra = {}) { super(message) Object.assign(this, extra) } } /* ---------------------------------------------------------------- cookies -- */ function parseCookies(input) { const raw = String(input || '').trim() const jar = {} for (const part of raw.split(/[;\n]+/)) { const match = /^\s*([A-Za-z0-9_.-]+)\s*=\s*([^\s;]+)\s*$/.exec(part) if (match) jar[match[1]] = match[2] } if (!jar.auth_token) { const tokens = raw.split(/\s+/).filter(Boolean) if (tokens.length >= 2 && !tokens[0].includes('=')) { jar.auth_token = tokens[0] jar.ct0 = tokens[1] } } return jar } const cookieHeader = (jar) => Object.entries(jar) .map(([k, v]) => `${k}=${v}`) .join('; ') const ct0Of = (cookies) => /(?:^|;\s*)ct0=([^;]+)/.exec(cookies || '')?.[1] || '' /* ------------------------------------------------------------ query id ---- */ /** x.com rotates the SearchTimeline query id; read the current one from the web bundle. */ async function discoverQueryId(cookies) { const res = await fetch('https://x.com/home', { headers: { 'user-agent': UA, accept: 'text/html', cookie: cookies }, signal: AbortSignal.timeout(25000), }) const html = res.ok ? await res.text() : '' const bundles = [ ...new Set(html.match(/https:\/\/abs\.twimg\.com\/responsive-web\/client-web\/[^"'\s>]+\.js/g) || []), ] // The main bundle is the one that carries the GraphQL operation table. bundles.sort((a, b) => Number(/\/main\./.test(b)) - Number(/\/main\./.test(a))) for (const url of bundles.slice(0, 6)) { try { const js = await (await fetch(url, { headers: { 'user-agent': UA }, signal: AbortSignal.timeout(45000) })).text() const queryId = /queryId:"([^"]+)",operationName:"SearchTimeline"/.exec(js)?.[1] const bearer = /Bearer ([A-Za-z0-9%_-]{60,140})/.exec(js)?.[1] if (queryId) { db.setSetting('x_query_id', queryId, { quiet: true }) if (bearer) db.setSetting('x_bearer', bearer, { quiet: true }) return { queryId, bearer: bearer || FALLBACK_BEARER } } } catch { /* next bundle */ } } throw new XError('找不到 X 搜索接口(页面结构可能变了)') } /* ----------------------------------------------------------------- search -- */ async function callSearch(query, { cookies, queryId, bearer, count }) { const body = { variables: { rawQuery: query, count, querySource: 'typed_query', product: 'Latest', withGrokTranslatedBio: false }, features: Object.fromEntries(FEATURES.map((name) => [name, true])), fieldToggles: { withArticleRichContentState: true, withArticlePlainText: false, withGrokAnalyze: false }, queryId, } const res = await fetch(`https://x.com/i/api/graphql/${queryId}/SearchTimeline`, { method: 'POST', headers: { authorization: `Bearer ${bearer}`, 'x-csrf-token': ct0Of(cookies), cookie: cookies, 'content-type': 'application/json', 'x-twitter-auth-type': 'OAuth2Session', 'x-twitter-active-user': 'yes', 'x-twitter-client-language': 'en', 'user-agent': UA, referer: `https://x.com/search?q=${encodeURIComponent(query)}&f=live`, }, body: JSON.stringify(body), signal: AbortSignal.timeout(30000), }) if (res.status === 429) { const reset = Number(res.headers.get('x-rate-limit-reset') || 0) throw new XError('X 搜索限流', { rateLimited: true, resetAt: reset || Math.floor(Date.now() / 1000) + 300 }) } if (res.status === 401 || res.status === 403) { const text = await res.text().catch(() => '') // 403 + "353" / csrf problems also mean the cookies are no good. throw new XError(`X 登录已失效(HTTP ${res.status}),请重新复制 Cookie`, { authFailed: true, detail: text.slice(0, 200) }) } if (res.status === 404 || res.status === 400) throw new XError(`X 搜索接口已变更(HTTP ${res.status})`, { stale: true }) if (!res.ok) throw new XError(`X 搜索失败:HTTP ${res.status}`) const json = await res.json().catch(() => null) if (!json) throw new XError('X 搜索返回内容无法解析') if (json.errors?.length && !json.data) { const msg = json.errors.map((e) => e.message).join('; ') if (/authoriz|authenticat|login/i.test(msg)) throw new XError(`X 登录已失效:${msg}`, { authFailed: true }) throw new XError(`X 搜索出错:${msg}`, { stale: /query|feature/i.test(msg) }) } return tweetsFrom([json]) } /** Live "Latest" search with the stored session. */ async function search(query, { count = 20, cookies = db.getSetting('x_cookies') } = {}) { if (!cookies) throw new XError('X 未登录', { noSession: true }) let queryId = db.getSetting('x_query_id') let bearer = db.getSetting('x_bearer') || FALLBACK_BEARER if (!queryId) ({ queryId, bearer } = await discoverQueryId(cookies)) try { return await callSearch(query, { cookies, queryId, bearer, count }) } catch (err) { if (!err.stale) throw err ;({ queryId, bearer } = await discoverQueryId(cookies)) return callSearch(query, { cookies, queryId, bearer, count }) } } /** Who is logged in (screen name from the home page), or null when the cookies are dead. */ async function whoAmI(cookies) { const res = await fetch('https://x.com/home', { headers: { 'user-agent': UA, accept: 'text/html', 'accept-language': 'en-US,en;q=0.9', cookie: cookies }, redirect: 'manual', signal: AbortSignal.timeout(25000), }) if (res.status >= 300 && res.status < 400) return { loggedIn: false } const html = res.status === 200 ? await res.text() : '' if (/name="redirect_after_login"|loginButton/.test(html)) return { loggedIn: false } const handle = /"screen_name":"([A-Za-z0-9_]{1,20})"/.exec(html.replace(/\\"/g, '"'))?.[1] || null return { loggedIn: res.status === 200, handle } } /* ---------------------------------------------------------- public reads -- */ /** Latest posts of a public profile (server-rendered page, no login). */ async function profile(handle) { const clean = String(handle || '').replace(/^@/, '').trim() if (!clean) return [] const res = await fetch(`https://x.com/${encodeURIComponent(clean)}`, { headers: { 'user-agent': UA, accept: 'text/html', 'accept-language': 'en-US,en;q=0.9' }, redirect: 'manual', signal: AbortSignal.timeout(25000), }) if (res.status !== 200) throw new XError(`@${clean} 主页 HTTP ${res.status}`) return tweetsFrom(extractPayloads(await res.text())).filter( (tweet) => !tweet.handle || tweet.handle.toLowerCase() === clean.toLowerCase() ) } /** One tweet by id (public syndication endpoint). */ async function tweet(id) { const token = ((Number(id) / 1e15) * Math.PI).toString(36).replace(/(0+|\.)/g, '') const res = await fetch(`https://cdn.syndication.twimg.com/tweet-result?id=${id}&token=${token}&lang=en`, { headers: { 'user-agent': UA }, signal: AbortSignal.timeout(15000), }) if (!res.ok) throw new XError(`读取推文失败:HTTP ${res.status}`) const t = await res.json() if (!t?.id_str) throw new XError('这条推文不存在或不可见') let text = decodeEntities(t.note_tweet?.text || t.text || '') const entities = [...(t.entities?.urls || []), ...(t.note_tweet?.entities?.urls || [])] const links = entities.map((u) => u.expanded_url).filter(Boolean) for (const u of entities) if (u.url && u.expanded_url) text = text.split(u.url).join(u.expanded_url) for (const m of t.entities?.media || []) if (m.url) text = text.split(m.url).join('').trim() return { id: t.id_str, text, created_at: Math.floor(Date.parse(t.created_at) / 1000) || 0, likes: Number(t.favorite_count || 0), replies: Number(t.conversation_count || 0), reposts: 0, views: 0, handle: t.user?.screen_name || null, name: t.user?.name || null, media: (t.mediaDetails || []).map((m) => ({ type: m.type || 'photo', url: m.media_url_https })), links, tco: text.match(/https:\/\/t\.co\/[A-Za-z0-9]+/g) || [], } } /* -------------------------------------------------------------------- t.co -- */ const tcoCache = new Map() async function resolveTco(url) { if (tcoCache.has(url)) return tcoCache.get(url) let target = null try { const res = await fetch(url, { redirect: 'manual', headers: { 'user-agent': UA }, signal: AbortSignal.timeout(7000) }) target = res.headers.get('location') if (!target) { const body = await res.text().catch(() => '') target = /location\.replace\("([^"]+)"/.exec(body)?.[1]?.replace(/\\\//g, '/') || /URL=([^">\s]+)/i.exec(body)?.[1] || null } } catch { return null } if (tcoCache.size > 5000) tcoCache.delete(tcoCache.keys().next().value) tcoCache.set(url, target) return target } module.exports = { search, whoAmI, profile, tweet, resolveTco, parseCookies, cookieHeader, XError }