| 1 | import { randomBytes, randomUUID } from 'node:crypto'; |
| 2 | import { isValidCookieValue, isValidHeaderValue, redactSecrets } from './cookies.js'; |
| 3 | import { |
| 4 | createAbortError, |
| 5 | raceWithAbort, |
| 6 | readResponseTextBounded, |
| 7 | runtimeQueryIds, |
| 8 | } from './runtime-query-ids.js'; |
| 9 | import { QUERY_IDS, SEARCH_QUERY_ID_OPERATIONS } from './twitter-client-constants.js'; |
| 10 | import { normalizeQuoteDepth } from './twitter-client-utils.js'; |
| 11 | const DEFAULT_MAX_RESPONSE_BYTES = 10 * 1024 * 1024; |
| 12 | const ERROR_BODY_MAX_BYTES = 256 * 1024; |
| 13 | function createComposedSignal(callerSignal, timeoutMs) { |
| 14 | const hasTimeout = typeof timeoutMs === 'number' && Number.isFinite(timeoutMs) && timeoutMs > 0; |
| 15 | if (!callerSignal && !hasTimeout) { |
| 16 | return { signal: undefined, cleanup: () => {} }; |
| 17 | } |
| 18 | const controller = new AbortController(); |
| 19 | let timeoutId = null; |
| 20 | const onCallerAbort = () => controller.abort(callerSignal.reason); |
| 21 | if (callerSignal) { |
| 22 | if (callerSignal.aborted) { |
| 23 | controller.abort(callerSignal.reason); |
| 24 | } |
| 25 | else { |
| 26 | callerSignal.addEventListener('abort', onCallerAbort, { once: true }); |
| 27 | } |
| 28 | } |
| 29 | if (hasTimeout && !controller.signal.aborted) { |
| 30 | timeoutId = setTimeout(() => { |
| 31 | controller.abort(createAbortError(`Request timed out after ${timeoutMs}ms`)); |
| 32 | }, timeoutMs); |
| 33 | } |
| 34 | return { |
| 35 | signal: controller.signal, |
| 36 | cleanup() { |
| 37 | if (timeoutId !== null) { |
| 38 | clearTimeout(timeoutId); |
| 39 | timeoutId = null; |
| 40 | } |
| 41 | if (callerSignal) { |
| 42 | callerSignal.removeEventListener('abort', onCallerAbort); |
| 43 | } |
| 44 | }, |
| 45 | }; |
| 46 | } |
| 47 | export class TwitterClientBase { |
| 48 | authToken; |
| 49 | ct0; |
| 50 | cookieHeader; |
| 51 | userAgent; |
| 52 | timeoutMs; |
| 53 | maxResponseBytes; |
| 54 | quoteDepth; |
| 55 | clientUuid; |
| 56 | clientDeviceId; |
| 57 | clientUserId; |
| 58 | constructor(options) { |
| 59 | const cookies = options?.cookies; |
| 60 | if (!cookies?.authToken || !cookies?.ct0) { |
| 61 | throw new Error('Both authToken and ct0 cookies are required'); |
| 62 | } |
| 63 | if (!isValidCookieValue(cookies.authToken) || !isValidCookieValue(cookies.ct0)) { |
| 64 | throw new Error('Invalid auth_token/ct0 format'); |
| 65 | } |
| 66 | if (cookies.cookieHeader !== undefined && cookies.cookieHeader !== null && cookies.cookieHeader !== '') { |
| 67 | if (!isValidHeaderValue(cookies.cookieHeader)) { |
| 68 | throw new Error('Invalid auth_token/ct0 format'); |
| 69 | } |
| 70 | } |
| 71 | this.authToken = cookies.authToken; |
| 72 | this.ct0 = cookies.ct0; |
| 73 | this.cookieHeader = cookies.cookieHeader || `auth_token=${this.authToken}; ct0=${this.ct0}`; |
| 74 | this.userAgent = |
| 75 | options.userAgent || |
| 76 | 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'; |
| 77 | this.timeoutMs = options.timeoutMs; |
| 78 | this.maxResponseBytes = |
| 79 | typeof options.maxResponseBytes === 'number' && |
| 80 | Number.isFinite(options.maxResponseBytes) && |
| 81 | options.maxResponseBytes > 0 |
| 82 | ? options.maxResponseBytes |
| 83 | : DEFAULT_MAX_RESPONSE_BYTES; |
| 84 | this.quoteDepth = normalizeQuoteDepth(options.quoteDepth); |
| 85 | this.clientUuid = randomUUID(); |
| 86 | this.clientDeviceId = randomUUID(); |
| 87 | } |
| 88 | redactError(message) { |
| 89 | return redactSecrets(message, [this.authToken, this.ct0, this.cookieHeader]); |
| 90 | } |
| 91 | async sleep(ms) { |
| 92 | await new Promise((resolve) => setTimeout(resolve, ms)); |
| 93 | } |
| 94 | async getQueryId(operationName) { |
| 95 | const cached = await runtimeQueryIds.getQueryId(operationName); |
| 96 | return cached ?? QUERY_IDS[operationName]; |
| 97 | } |
| 98 | async refreshQueryIds(opts = {}) { |
| 99 | if (process.env.NODE_ENV === 'test') { |
| 100 | return; |
| 101 | } |
| 102 | try { |
| 103 | const budgetMs = |
| 104 | typeof opts.timeoutMs === 'number' && Number.isFinite(opts.timeoutMs) |
| 105 | ? opts.timeoutMs |
| 106 | : this.timeoutMs; |
| 107 | if (typeof budgetMs === 'number' && Number.isFinite(budgetMs) && budgetMs <= 0) { |
| 108 | return; |
| 109 | } |
| 110 | const refreshOpts = { force: true }; |
| 111 | if (typeof budgetMs === 'number' && Number.isFinite(budgetMs) && budgetMs > 0) { |
| 112 | refreshOpts.refreshTimeoutMs = Math.min(15_000, budgetMs); |
| 113 | refreshOpts.fetchTimeoutMs = Math.min(10_000, budgetMs); |
| 114 | } |
| 115 | await runtimeQueryIds.refresh(SEARCH_QUERY_ID_OPERATIONS, refreshOpts); |
| 116 | } |
| 117 | catch { |
| 118 | // ignore refresh failures; callers will fall back to baked-in IDs |
| 119 | } |
| 120 | } |
| 121 | async withRefreshedQueryIdsOn404(attempt) { |
| 122 | const firstAttempt = await attempt(); |
| 123 | if (firstAttempt.success || !firstAttempt.had404) { |
| 124 | return { result: firstAttempt, refreshed: false }; |
| 125 | } |
| 126 | await this.refreshQueryIds(); |
| 127 | const secondAttempt = await attempt(); |
| 128 | return { result: secondAttempt, refreshed: true }; |
| 129 | } |
| 130 | async getTweetDetailQueryIds() { |
| 131 | const primary = await this.getQueryId('TweetDetail'); |
| 132 | return Array.from(new Set([primary, '97JF30KziU00483E_8elBA', 'aFvUsJm2c-oDkJV75blV6g'])); |
| 133 | } |
| 134 | async getSearchTimelineQueryIds() { |
| 135 | const primary = await this.getQueryId('SearchTimeline'); |
| 136 | return Array.from(new Set([primary, 'M1jEez78PEfVfbQLvlWMvQ', '5h0kNbk3ii97rmfY6CdgAA', 'Tp1sewRU1AsZpBWhqCZicQ'])); |
| 137 | } |
| 138 | async fetchWithTimeout(url, init) { |
| 139 | const { signal, cleanup } = createComposedSignal(init?.signal, this.timeoutMs); |
| 140 | try { |
| 141 | const fetchInit = signal ? { ...init, signal } : init; |
| 142 | return await raceWithAbort(fetch(url, fetchInit), signal); |
| 143 | } |
| 144 | finally { |
| 145 | cleanup(); |
| 146 | } |
| 147 | } |
| 148 | async fetchTextWithTimeout(url, init = {}, opts = {}) { |
| 149 | const maxBytes = opts.maxBytes ?? this.maxResponseBytes; |
| 150 | const skipBodyStatuses = opts.skipBodyStatuses; |
| 151 | const effectiveTimeoutMs = |
| 152 | typeof opts.timeoutMs === 'number' && Number.isFinite(opts.timeoutMs) |
| 153 | ? opts.timeoutMs |
| 154 | : this.timeoutMs; |
| 155 | if (typeof effectiveTimeoutMs === 'number' && Number.isFinite(effectiveTimeoutMs) && effectiveTimeoutMs <= 0) { |
| 156 | throw createAbortError('Request timed out'); |
| 157 | } |
| 158 | const { signal, cleanup } = createComposedSignal(init?.signal, effectiveTimeoutMs); |
| 159 | try { |
| 160 | const fetchInit = signal ? { ...init, signal } : init; |
| 161 | const response = await raceWithAbort(fetch(url, fetchInit), signal); |
| 162 | if (skipBodyStatuses?.has(response.status)) { |
| 163 | await response.body?.cancel().catch(() => {}); |
| 164 | return { ok: response.ok, status: response.status, text: '' }; |
| 165 | } |
| 166 | const limit = response.ok ? maxBytes : Math.min(maxBytes, ERROR_BODY_MAX_BYTES); |
| 167 | const text = await readResponseTextBounded(response, limit, signal, { |
| 168 | truncateOnLimit: !response.ok, |
| 169 | }); |
| 170 | return { ok: response.ok, status: response.status, text }; |
| 171 | } |
| 172 | finally { |
| 173 | cleanup(); |
| 174 | } |
| 175 | } |
| 176 | getHeaders() { |
| 177 | return this.getJsonHeaders(); |
| 178 | } |
| 179 | createTransactionId() { |
| 180 | return randomBytes(16).toString('hex'); |
| 181 | } |
| 182 | getBaseHeaders() { |
| 183 | const headers = { |
| 184 | accept: '*/*', |
| 185 | 'accept-language': 'en-US,en;q=0.9', |
| 186 | authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA', |
| 187 | 'x-csrf-token': this.ct0, |
| 188 | 'x-twitter-auth-type': 'OAuth2Session', |
| 189 | 'x-twitter-active-user': 'yes', |
| 190 | 'x-twitter-client-language': 'en', |
| 191 | 'x-client-uuid': this.clientUuid, |
| 192 | 'x-twitter-client-deviceid': this.clientDeviceId, |
| 193 | 'x-client-transaction-id': this.createTransactionId(), |
| 194 | cookie: this.cookieHeader, |
| 195 | 'user-agent': this.userAgent, |
| 196 | origin: 'https://x.com', |
| 197 | referer: 'https://x.com/', |
| 198 | }; |
| 199 | if (this.clientUserId) { |
| 200 | headers['x-twitter-client-user-id'] = this.clientUserId; |
| 201 | } |
| 202 | return headers; |
| 203 | } |
| 204 | getJsonHeaders() { |
| 205 | return { |
| 206 | ...this.getBaseHeaders(), |
| 207 | 'content-type': 'application/json', |
| 208 | }; |
| 209 | } |
| 210 | getUploadHeaders() { |
| 211 | // Note: do not set content-type; URLSearchParams/FormData need to set it (incl boundary) themselves. |
| 212 | return this.getBaseHeaders(); |
| 213 | } |
| 214 | async ensureClientUserId() { |
| 215 | if (process.env.NODE_ENV === 'test') { |
| 216 | return; |
| 217 | } |
| 218 | if (this.clientUserId) { |
| 219 | return; |
| 220 | } |
| 221 | const result = await this.getCurrentUser(); |
| 222 | if (result.success && result.user?.id) { |
| 223 | this.clientUserId = result.user.id; |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | //# sourceMappingURL=twitter-client-base.js.map |