+6
-11
@@ -13,7 +13,7 @@ import { registerUnbookmarkCommand } from '../commands/unbookmark.js';
|
||||
import { registerUserTweetsCommand } from '../commands/user-tweets.js';
|
||||
import { registerUserCommands } from '../commands/users.js';
|
||||
import { getCliVersion } from '../lib/version.js';
|
||||
import { type CliContext, collectCookieSource } from './shared.js';
|
||||
import type { CliContext } from './shared.js';
|
||||
|
||||
export const KNOWN_COMMANDS = new Set([
|
||||
'tweet',
|
||||
@@ -83,8 +83,8 @@ export function createProgram(ctx: CliContext): Command {
|
||||
'afterAll',
|
||||
() =>
|
||||
`\n${ctx.colors.section('Examples')}\n${[
|
||||
formatExample('bird whoami', 'Show the logged-in account via GraphQL cookies'),
|
||||
formatExample('bird --firefox-profile default-release whoami', 'Use Firefox profile cookies'),
|
||||
formatExample('bird whoami', 'Show the relay account'),
|
||||
formatExample('bird --relay-base-url http://localhost:6900 whoami', 'Use a specific twitter safe relay'),
|
||||
formatExample('bird tweet "hello from bird"', 'Send a tweet'),
|
||||
formatExample(
|
||||
'bird 1234567890123456789 --json',
|
||||
@@ -105,19 +105,14 @@ export function createProgram(ctx: CliContext): Command {
|
||||
`\n\n${ctx.colors.section('Config')}\n${ctx.colors.muted(
|
||||
` Reads ${ctx.colors.argument('~/.config/bird/config.json5')} and ${ctx.colors.argument('./.birdrc.json5')} (JSON5)`,
|
||||
)}\n${ctx.colors.muted(
|
||||
` Supports: chromeProfile, firefoxProfile, cookieSource, cookieTimeoutMs, timeoutMs, quoteDepth`,
|
||||
` Supports: relayBaseUrl, timeoutMs, quoteDepth`,
|
||||
)}\n\n${ctx.colors.section('Env')}\n${ctx.colors.muted(
|
||||
` ${ctx.colors.option('NO_COLOR')}, ${ctx.colors.option('BIRD_TIMEOUT_MS')}, ${ctx.colors.option('BIRD_COOKIE_TIMEOUT_MS')}, ${ctx.colors.option('BIRD_QUOTE_DEPTH')}`,
|
||||
` ${ctx.colors.option('TWITTER_RELAY_BASE_URL')}, ${ctx.colors.option('NO_COLOR')}, ${ctx.colors.option('BIRD_TIMEOUT_MS')}, ${ctx.colors.option('BIRD_QUOTE_DEPTH')}`,
|
||||
)}`,
|
||||
);
|
||||
|
||||
program
|
||||
.option('--auth-token <token>', 'Twitter auth_token cookie')
|
||||
.option('--ct0 <token>', 'Twitter ct0 cookie')
|
||||
.option('--chrome-profile <name>', 'Chrome profile name for cookie extraction', ctx.config.chromeProfile)
|
||||
.option('--firefox-profile <name>', 'Firefox profile name for cookie extraction', ctx.config.firefoxProfile)
|
||||
.option('--cookie-timeout <ms>', 'Cookie extraction timeout in milliseconds (keychain/OS helpers)')
|
||||
.option('--cookie-source <source>', 'Cookie source for browser cookie extraction (repeatable)', collectCookieSource)
|
||||
.option('--relay-base-url <url>', 'twitter safe relay base URL', ctx.config.relayBaseUrl)
|
||||
.option('--media <path>', 'Attach media file (repeatable, up to 4 images or 1 video)', collect)
|
||||
.option('--alt <text>', 'Alt text for the corresponding --media (repeatable)', collect)
|
||||
.option('--timeout <ms>', 'Request timeout in milliseconds')
|
||||
|
||||
+7
-62
@@ -4,7 +4,6 @@ import { join } from 'node:path';
|
||||
import type { Command } from 'commander';
|
||||
import JSON5 from 'json5';
|
||||
import kleur from 'kleur';
|
||||
import { type CookieSource, resolveCredentials } from '../lib/cookies.js';
|
||||
import { extractTweetId } from '../lib/extract-tweet-id.js';
|
||||
import {
|
||||
hyperlink,
|
||||
@@ -17,10 +16,7 @@ import {
|
||||
import type { TweetData } from '../lib/twitter-client.js';
|
||||
|
||||
export type BirdConfig = {
|
||||
chromeProfile?: string;
|
||||
firefoxProfile?: string;
|
||||
cookieSource?: CookieSource | CookieSource[];
|
||||
cookieTimeoutMs?: number;
|
||||
relayBaseUrl?: string;
|
||||
timeoutMs?: number;
|
||||
quoteDepth?: number;
|
||||
};
|
||||
@@ -48,7 +44,7 @@ export type CliContext = {
|
||||
applyOutputFromCommand: (command: Command) => void;
|
||||
resolveTimeoutFromOptions: (options: { timeout?: string | number }) => number | undefined;
|
||||
resolveQuoteDepthFromOptions: (options: { quoteDepth?: string | number }) => number | undefined;
|
||||
resolveCredentialsFromOptions: (opts: CredentialsOptions) => ReturnType<typeof resolveCredentials>;
|
||||
resolveRelayBaseUrlFromOptions: (opts: RelayOptions) => string | undefined;
|
||||
loadMedia: (opts: { media: string[]; alts: string[] }) => MediaSpec[];
|
||||
printTweets: (tweets: TweetData[], opts?: { json?: boolean; emptyMessage?: string; showSeparator?: boolean }) => void;
|
||||
printTweetsResult: (
|
||||
@@ -65,38 +61,6 @@ export type CliContext = {
|
||||
extractTweetId: (tweetIdOrUrl: string) => string;
|
||||
};
|
||||
|
||||
const COOKIE_SOURCES: CookieSource[] = ['safari', 'chrome', 'firefox'];
|
||||
|
||||
function parseCookieSource(value: string): CookieSource {
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (normalized === 'safari' || normalized === 'chrome' || normalized === 'firefox') {
|
||||
return normalized;
|
||||
}
|
||||
throw new Error(`Invalid --cookie-source "${value}". Allowed: safari, chrome, firefox.`);
|
||||
}
|
||||
|
||||
export const collectCookieSource = (value: string, previous: CookieSource[] = []): CookieSource[] => {
|
||||
previous.push(parseCookieSource(value));
|
||||
return previous;
|
||||
};
|
||||
|
||||
function resolveCookieSourceOrder(input: unknown): CookieSource[] | undefined {
|
||||
if (typeof input === 'string') {
|
||||
return [parseCookieSource(input)];
|
||||
}
|
||||
if (Array.isArray(input)) {
|
||||
const result: CookieSource[] = [];
|
||||
for (const entry of input) {
|
||||
if (typeof entry !== 'string') {
|
||||
continue;
|
||||
}
|
||||
result.push(parseCookieSource(entry));
|
||||
}
|
||||
return result.length > 0 ? result : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function resolveTimeoutMs(...values: Array<string | number | undefined | null>): number | undefined {
|
||||
for (const value of values) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
@@ -170,13 +134,8 @@ function loadConfig(warn: (message: string) => void): BirdConfig {
|
||||
};
|
||||
}
|
||||
|
||||
type CredentialsOptions = {
|
||||
authToken?: string;
|
||||
ct0?: string;
|
||||
chromeProfile?: string;
|
||||
firefoxProfile?: string;
|
||||
cookieSource?: CookieSource[];
|
||||
cookieTimeout?: string | number;
|
||||
type RelayOptions = {
|
||||
relayBaseUrl?: string;
|
||||
};
|
||||
|
||||
export function createCliContext(normalizedArgs: string[], env: NodeJS.ProcessEnv = process.env): CliContext {
|
||||
@@ -268,26 +227,12 @@ export function createCliContext(normalizedArgs: string[], env: NodeJS.ProcessEn
|
||||
return resolveTimeoutMs(options.timeout, config.timeoutMs, env.BIRD_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
function resolveCookieTimeoutFromOptions(options: { cookieTimeout?: string | number }): number | undefined {
|
||||
return resolveTimeoutMs(options.cookieTimeout, config.cookieTimeoutMs, env.BIRD_COOKIE_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
function resolveQuoteDepthFromOptions(options: { quoteDepth?: string | number }): number | undefined {
|
||||
return resolveQuoteDepth(options.quoteDepth, config.quoteDepth, env.BIRD_QUOTE_DEPTH);
|
||||
}
|
||||
|
||||
function resolveCredentialsFromOptions(opts: CredentialsOptions): ReturnType<typeof resolveCredentials> {
|
||||
const cookieSource = opts.cookieSource?.length
|
||||
? opts.cookieSource
|
||||
: (resolveCookieSourceOrder(config.cookieSource) ?? COOKIE_SOURCES);
|
||||
return resolveCredentials({
|
||||
authToken: opts.authToken,
|
||||
ct0: opts.ct0,
|
||||
cookieSource,
|
||||
chromeProfile: opts.chromeProfile || config.chromeProfile,
|
||||
firefoxProfile: opts.firefoxProfile || config.firefoxProfile,
|
||||
cookieTimeoutMs: resolveCookieTimeoutFromOptions(opts),
|
||||
});
|
||||
function resolveRelayBaseUrlFromOptions(opts: RelayOptions): string | undefined {
|
||||
return opts.relayBaseUrl || config.relayBaseUrl || env.TWITTER_RELAY_BASE_URL;
|
||||
}
|
||||
|
||||
function loadMedia(opts: { media: string[]; alts: string[] }): MediaSpec[] {
|
||||
@@ -422,7 +367,7 @@ export function createCliContext(normalizedArgs: string[], env: NodeJS.ProcessEn
|
||||
applyOutputFromCommand,
|
||||
resolveTimeoutFromOptions,
|
||||
resolveQuoteDepthFromOptions,
|
||||
resolveCredentialsFromOptions,
|
||||
resolveRelayBaseUrlFromOptions,
|
||||
loadMedia,
|
||||
printTweets,
|
||||
printTweetsResult,
|
||||
|
||||
@@ -34,17 +34,7 @@ export function registerBookmarksCommand(program: Command, ctx: CliContext): voi
|
||||
process.exit(1);
|
||||
}
|
||||
const maxPages = maxPagesParsed.value;
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
const usePagination = Boolean(cmdOpts.all || cmdOpts.cursor);
|
||||
if (maxPages !== undefined && !usePagination) {
|
||||
@@ -56,7 +46,7 @@ export function registerBookmarksCommand(program: Command, ctx: CliContext): voi
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||
const folderId = cmdOpts.folderId ? extractBookmarkFolderId(cmdOpts.folderId) : null;
|
||||
if (cmdOpts.folderId && !folderId) {
|
||||
console.error(`${ctx.p('err')}Invalid --folder-id. Expected numeric ID or https://x.com/i/bookmarks/<id>.`);
|
||||
|
||||
+21
-33
@@ -1,47 +1,35 @@
|
||||
import type { Command } from 'commander';
|
||||
import type { CliContext } from '../cli/shared.js';
|
||||
import { TwitterClient } from '../lib/twitter-client.js';
|
||||
|
||||
export function registerCheckCommand(program: Command, ctx: CliContext): void {
|
||||
program
|
||||
.command('check')
|
||||
.description('Check credential availability')
|
||||
.description('Check twitter safe relay availability')
|
||||
.action(async () => {
|
||||
const opts = program.opts();
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
console.log(`${ctx.p('info')}Credential check`);
|
||||
console.log('─'.repeat(40));
|
||||
console.log(`${ctx.p('info')}Relay check`);
|
||||
console.log('-'.repeat(40));
|
||||
|
||||
if (cookies.authToken) {
|
||||
console.log(`${ctx.p('ok')}auth_token: ${cookies.authToken.slice(0, 10)}...`);
|
||||
if (!relayBaseUrl) {
|
||||
console.log(`${ctx.p('err')}TWITTER_RELAY_BASE_URL: not set`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`${ctx.p('ok')}relay: ${relayBaseUrl}`);
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||
const result = await client.getCurrentUser();
|
||||
|
||||
if (result.success && result.user) {
|
||||
console.log(`${ctx.l('user')}@${result.user.username} (${result.user.name})`);
|
||||
console.log(`${ctx.l('userId')}${result.user.id}`);
|
||||
console.log(`\n${ctx.p('ok')}Ready to use twitter safe relay.`);
|
||||
} else {
|
||||
console.log(`${ctx.p('err')}auth_token: not found`);
|
||||
}
|
||||
|
||||
if (cookies.ct0) {
|
||||
console.log(`${ctx.p('ok')}ct0: ${cookies.ct0.slice(0, 10)}...`);
|
||||
} else {
|
||||
console.log(`${ctx.p('err')}ct0: not found`);
|
||||
}
|
||||
|
||||
if (cookies.source) {
|
||||
console.log(`${ctx.l('source')}${cookies.source}`);
|
||||
}
|
||||
|
||||
if (warnings.length > 0) {
|
||||
console.log(`\n${ctx.p('warn')}Warnings:`);
|
||||
for (const warning of warnings) {
|
||||
console.log(` - ${warning}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (cookies.authToken && cookies.ct0) {
|
||||
console.log(`\n${ctx.p('ok')}Ready to tweet!`);
|
||||
} else {
|
||||
console.log(`\n${ctx.p('err')}Missing credentials. Options:`);
|
||||
console.log(' 1. Login to x.com in Safari/Chrome/Firefox');
|
||||
console.log(' 2. Set AUTH_TOKEN and CT0 environment variables');
|
||||
console.log(' 3. Use --auth-token and --ct0 flags');
|
||||
console.log(`${ctx.p('err')}Relay check failed: ${result.error ?? 'Unknown error'}`);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
+2
-12
@@ -14,24 +14,14 @@ export function registerHomeCommand(program: Command, ctx: CliContext): void {
|
||||
const opts = program.opts();
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
if (!Number.isFinite(count) || count <= 0) {
|
||||
console.error(`${ctx.p('err')}Invalid --count. Expected a positive integer.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
|
||||
const result = cmdOpts.following
|
||||
|
||||
+4
-24
@@ -42,19 +42,9 @@ export function registerListsCommand(program: Command, ctx: CliContext): void {
|
||||
const opts = program.opts();
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const count = Number.parseInt(cmdOpts.count || '100', 10);
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||
|
||||
const result = cmdOpts.memberOf ? await client.getListMemberships(count) : await client.getOwnedLists(count);
|
||||
|
||||
@@ -118,19 +108,9 @@ export function registerListsCommand(program: Command, ctx: CliContext): void {
|
||||
console.error(`${ctx.p('err')}Invalid --count. Expected a positive integer.`);
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
const timelineOptions = { includeRaw };
|
||||
const paginationOptions = { includeRaw, maxPages: pagination.maxPages, cursor: pagination.cursor };
|
||||
|
||||
+2
-12
@@ -101,12 +101,7 @@ export function registerNewsCommand(program: Command, ctx: CliContext): void {
|
||||
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
||||
const count = Number.parseInt(cmdOpts.count || '10', 10);
|
||||
const tweetsPerItem = Number.parseInt(cmdOpts.tweetsPerItem || '5', 10);
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
if (Number.isNaN(count) || count < 1) {
|
||||
console.error(`${ctx.p('err')}--count must be a positive number`);
|
||||
@@ -118,11 +113,6 @@ export function registerNewsCommand(program: Command, ctx: CliContext): void {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Determine which tabs to fetch from
|
||||
const tabs: ExploreTab[] = [];
|
||||
if (cmdOpts.forYou) {
|
||||
@@ -144,7 +134,7 @@ export function registerNewsCommand(program: Command, ctx: CliContext): void {
|
||||
// If no specific tabs selected, use defaults (all tabs except trending)
|
||||
const tabsToFetch = tabs.length > 0 ? tabs : undefined;
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
const withTweets = cmdOpts.withTweets ?? false;
|
||||
const aiOnly = cmdOpts.aiOnly ?? false;
|
||||
|
||||
+4
-34
@@ -40,23 +40,8 @@ export function registerPostCommands(program: Command, ctx: CliContext): void {
|
||||
console.error(`${ctx.p('err')}${error instanceof Error ? error.message : String(error)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (cookies.source) {
|
||||
console.error(`${ctx.l('source')}${cookies.source}`);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const mediaIds = await uploadMediaOrExit(client, media, ctx);
|
||||
const result = await client.tweet(text, mediaIds);
|
||||
|
||||
@@ -86,25 +71,10 @@ export function registerPostCommands(program: Command, ctx: CliContext): void {
|
||||
process.exit(1);
|
||||
}
|
||||
const tweetId = ctx.extractTweetId(tweetIdOrUrl);
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (cookies.source) {
|
||||
console.error(`${ctx.l('source')}${cookies.source}`);
|
||||
}
|
||||
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
console.error(`${ctx.p('info')}Replying to tweet: ${tweetId}`);
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const mediaIds = await uploadMediaOrExit(client, media, ctx);
|
||||
const result = await client.reply(text, tweetId, mediaIds);
|
||||
|
||||
|
||||
+6
-36
@@ -17,19 +17,9 @@ export function registerReadCommands(program: Command, ctx: CliContext): void {
|
||||
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
||||
|
||||
const tweetId = ctx.extractTweetId(tweetIdOrUrl);
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
const result = await client.getTweet(tweetId, { includeRaw });
|
||||
|
||||
@@ -78,19 +68,9 @@ export function registerReadCommands(program: Command, ctx: CliContext): void {
|
||||
console.error(`${ctx.p('err')}${pagination.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
|
||||
const result = pagination.usePagination
|
||||
@@ -155,19 +135,9 @@ export function registerReadCommands(program: Command, ctx: CliContext): void {
|
||||
console.error(`${ctx.p('err')}${pagination.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
|
||||
const result = pagination.usePagination
|
||||
|
||||
+4
-24
@@ -31,17 +31,7 @@ export function registerSearchCommands(program: Command, ctx: CliContext): void
|
||||
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
||||
const count = Number.parseInt(cmdOpts.count || '10', 10);
|
||||
const maxPages = cmdOpts.maxPages ? Number.parseInt(cmdOpts.maxPages, 10) : undefined;
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
const usePagination = cmdOpts.all || cmdOpts.cursor;
|
||||
if (maxPages !== undefined && !usePagination) {
|
||||
@@ -57,7 +47,7 @@ export function registerSearchCommands(program: Command, ctx: CliContext): void
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
const searchOptions = { includeRaw };
|
||||
const paginationOptions = { includeRaw, maxPages, cursor: cmdOpts.cursor };
|
||||
@@ -99,19 +89,9 @@ export function registerSearchCommands(program: Command, ctx: CliContext): void
|
||||
}
|
||||
|
||||
let query: string | null = fromUserOpt.query;
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
|
||||
if (!query) {
|
||||
const who = await client.getCurrentUser();
|
||||
|
||||
@@ -10,19 +10,9 @@ export function registerUnbookmarkCommand(program: Command, ctx: CliContext): vo
|
||||
.action(async (tweetIdOrUrls: string[]) => {
|
||||
const opts = program.opts();
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||
let failures = 0;
|
||||
|
||||
for (const input of tweetIdOrUrls) {
|
||||
|
||||
@@ -86,19 +86,9 @@ export function registerUserTweetsCommand(program: Command, ctx: CliContext): vo
|
||||
console.error(`${ctx.p('err')}Invalid handle: ${handle}`);
|
||||
process.exit(2);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
|
||||
// Look up user ID from username
|
||||
console.error(`${ctx.p('info')}Looking up @${username}...`);
|
||||
|
||||
+11
-57
@@ -36,19 +36,9 @@ export function registerUserCommands(program: Command, ctx: CliContext): void {
|
||||
console.error(`${ctx.p('err')}Invalid --max-pages. Expected a positive integer.`);
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||
|
||||
let userId = cmdOpts.user;
|
||||
if (!userId) {
|
||||
@@ -196,19 +186,9 @@ export function registerUserCommands(program: Command, ctx: CliContext): void {
|
||||
console.error(`${ctx.p('err')}Invalid --max-pages. Expected a positive integer.`);
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||
|
||||
let userId = cmdOpts.user;
|
||||
if (!userId) {
|
||||
@@ -347,17 +327,7 @@ export function registerUserCommands(program: Command, ctx: CliContext): void {
|
||||
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
||||
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
||||
const maxPages = cmdOpts.maxPages ? Number.parseInt(cmdOpts.maxPages, 10) : undefined;
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
const usePagination = cmdOpts.all || cmdOpts.cursor;
|
||||
if (maxPages !== undefined && !usePagination) {
|
||||
@@ -373,7 +343,7 @@ export function registerUserCommands(program: Command, ctx: CliContext): void {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
const timelineOptions = { includeRaw };
|
||||
const paginationOptions = { includeRaw, maxPages, cursor: cmdOpts.cursor };
|
||||
@@ -397,37 +367,21 @@ export function registerUserCommands(program: Command, ctx: CliContext): void {
|
||||
|
||||
program
|
||||
.command('whoami')
|
||||
.description('Show which Twitter account the current credentials belong to')
|
||||
.description('Show which Twitter account the relay belongs to')
|
||||
.action(async () => {
|
||||
const opts = program.opts();
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
||||
|
||||
for (const warning of warnings) {
|
||||
console.error(`${ctx.p('warn')}${warning}`);
|
||||
}
|
||||
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (cookies.source) {
|
||||
console.error(`${ctx.l('source')}${cookies.source}`);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const result = await client.getCurrentUser();
|
||||
|
||||
const credentialSource = cookies.source ?? 'env/auto-detected cookies';
|
||||
|
||||
if (result.success && result.user) {
|
||||
console.log(`${ctx.l('user')}@${result.user.username} (${result.user.name})`);
|
||||
console.log(`${ctx.l('userId')}${result.user.id}`);
|
||||
console.log(`${ctx.l('engine')}graphql`);
|
||||
console.log(`${ctx.l('credentials')}${credentialSource}`);
|
||||
console.log(`${ctx.l('engine')}twitter-safe-relay`);
|
||||
console.log(`${ctx.l('credentials')}${relayBaseUrl ?? 'TWITTER_RELAY_BASE_URL'}`);
|
||||
} else {
|
||||
console.error(`${ctx.p('err')}Failed to determine current user: ${result.error ?? 'Unknown error'}`);
|
||||
process.exit(1);
|
||||
|
||||
@@ -1,235 +0,0 @@
|
||||
/**
|
||||
* Browser cookie extraction for Twitter authentication.
|
||||
* Delegates to @steipete/sweet-cookie for Safari/Chrome/Firefox reads.
|
||||
*/
|
||||
|
||||
import { getCookies } from '@steipete/sweet-cookie';
|
||||
|
||||
export interface TwitterCookies {
|
||||
authToken: string | null;
|
||||
ct0: string | null;
|
||||
cookieHeader: string | null;
|
||||
source: string | null;
|
||||
}
|
||||
|
||||
export interface CookieExtractionResult {
|
||||
cookies: TwitterCookies;
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
export type CookieSource = 'safari' | 'chrome' | 'firefox';
|
||||
|
||||
const TWITTER_COOKIE_NAMES = ['auth_token', 'ct0'] as const;
|
||||
const TWITTER_URL = 'https://x.com/';
|
||||
const TWITTER_ORIGINS: string[] = ['https://x.com/', 'https://twitter.com/'];
|
||||
const DEFAULT_COOKIE_TIMEOUT_MS = 30_000;
|
||||
|
||||
function normalizeValue(value: unknown): string | null {
|
||||
if (typeof value !== 'string') {
|
||||
return null;
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function cookieHeader(authToken: string, ct0: string): string {
|
||||
return `auth_token=${authToken}; ct0=${ct0}`;
|
||||
}
|
||||
|
||||
function buildEmpty(): TwitterCookies {
|
||||
return { authToken: null, ct0: null, cookieHeader: null, source: null };
|
||||
}
|
||||
|
||||
function readEnvCookie(cookies: TwitterCookies, keys: readonly string[], field: 'authToken' | 'ct0'): void {
|
||||
if (cookies[field]) {
|
||||
return;
|
||||
}
|
||||
for (const key of keys) {
|
||||
const value = normalizeValue(process.env[key]);
|
||||
if (!value) {
|
||||
continue;
|
||||
}
|
||||
cookies[field] = value;
|
||||
if (!cookies.source) {
|
||||
cookies.source = `env ${key}`;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveSources(cookieSource?: CookieSource | CookieSource[]): CookieSource[] {
|
||||
if (Array.isArray(cookieSource)) {
|
||||
return cookieSource;
|
||||
}
|
||||
if (cookieSource) {
|
||||
return [cookieSource];
|
||||
}
|
||||
return ['safari', 'chrome', 'firefox'];
|
||||
}
|
||||
|
||||
function labelForSource(source: CookieSource, profile?: string): string {
|
||||
if (source === 'safari') {
|
||||
return 'Safari';
|
||||
}
|
||||
if (source === 'chrome') {
|
||||
return profile ? `Chrome profile "${profile}"` : 'Chrome default profile';
|
||||
}
|
||||
return profile ? `Firefox profile "${profile}"` : 'Firefox default profile';
|
||||
}
|
||||
|
||||
function pickCookieValue(
|
||||
cookies: Array<{ name?: string; value?: string; domain?: string }>,
|
||||
name: (typeof TWITTER_COOKIE_NAMES)[number],
|
||||
): string | null {
|
||||
const matches = cookies.filter((c) => c?.name === name && typeof c.value === 'string');
|
||||
if (matches.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const preferred = matches.find((c) => (c.domain ?? '').endsWith('x.com'));
|
||||
if (preferred?.value) {
|
||||
return preferred.value;
|
||||
}
|
||||
|
||||
const twitter = matches.find((c) => (c.domain ?? '').endsWith('twitter.com'));
|
||||
if (twitter?.value) {
|
||||
return twitter.value;
|
||||
}
|
||||
|
||||
return matches[0]?.value ?? null;
|
||||
}
|
||||
|
||||
async function readTwitterCookiesFromBrowser(options: {
|
||||
source: CookieSource;
|
||||
chromeProfile?: string;
|
||||
firefoxProfile?: string;
|
||||
cookieTimeoutMs?: number;
|
||||
}): Promise<CookieExtractionResult> {
|
||||
const warnings: string[] = [];
|
||||
const out = buildEmpty();
|
||||
|
||||
const { cookies, warnings: providerWarnings } = await getCookies({
|
||||
url: TWITTER_URL,
|
||||
origins: TWITTER_ORIGINS,
|
||||
names: [...TWITTER_COOKIE_NAMES],
|
||||
browsers: [options.source],
|
||||
mode: 'merge',
|
||||
chromeProfile: options.chromeProfile,
|
||||
firefoxProfile: options.firefoxProfile,
|
||||
timeoutMs: options.cookieTimeoutMs,
|
||||
});
|
||||
warnings.push(...providerWarnings);
|
||||
|
||||
const authToken = pickCookieValue(cookies, 'auth_token');
|
||||
const ct0 = pickCookieValue(cookies, 'ct0');
|
||||
if (authToken) {
|
||||
out.authToken = authToken;
|
||||
}
|
||||
if (ct0) {
|
||||
out.ct0 = ct0;
|
||||
}
|
||||
|
||||
if (out.authToken && out.ct0) {
|
||||
out.cookieHeader = cookieHeader(out.authToken, out.ct0);
|
||||
out.source = labelForSource(
|
||||
options.source,
|
||||
options.source === 'chrome' ? options.chromeProfile : options.firefoxProfile,
|
||||
);
|
||||
return { cookies: out, warnings };
|
||||
}
|
||||
|
||||
if (options.source === 'safari') {
|
||||
warnings.push('No Twitter cookies found in Safari. Make sure you are logged into x.com in Safari.');
|
||||
} else if (options.source === 'chrome') {
|
||||
warnings.push('No Twitter cookies found in Chrome. Make sure you are logged into x.com in Chrome.');
|
||||
} else {
|
||||
warnings.push(
|
||||
'No Twitter cookies found in Firefox. Make sure you are logged into x.com in Firefox and the profile exists.',
|
||||
);
|
||||
}
|
||||
|
||||
return { cookies: out, warnings };
|
||||
}
|
||||
|
||||
export async function extractCookiesFromSafari(): Promise<CookieExtractionResult> {
|
||||
return readTwitterCookiesFromBrowser({ source: 'safari' });
|
||||
}
|
||||
|
||||
export async function extractCookiesFromChrome(profile?: string): Promise<CookieExtractionResult> {
|
||||
return readTwitterCookiesFromBrowser({ source: 'chrome', chromeProfile: profile });
|
||||
}
|
||||
|
||||
export async function extractCookiesFromFirefox(profile?: string): Promise<CookieExtractionResult> {
|
||||
return readTwitterCookiesFromBrowser({ source: 'firefox', firefoxProfile: profile });
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve Twitter credentials from multiple sources.
|
||||
* Priority: CLI args > environment variables > browsers (ordered).
|
||||
*/
|
||||
export async function resolveCredentials(options: {
|
||||
authToken?: string;
|
||||
ct0?: string;
|
||||
cookieSource?: CookieSource | CookieSource[];
|
||||
chromeProfile?: string;
|
||||
firefoxProfile?: string;
|
||||
cookieTimeoutMs?: number;
|
||||
}): Promise<CookieExtractionResult> {
|
||||
const warnings: string[] = [];
|
||||
const cookies = buildEmpty();
|
||||
const cookieTimeoutMs =
|
||||
typeof options.cookieTimeoutMs === 'number' &&
|
||||
Number.isFinite(options.cookieTimeoutMs) &&
|
||||
options.cookieTimeoutMs > 0
|
||||
? options.cookieTimeoutMs
|
||||
: process.platform === 'darwin'
|
||||
? DEFAULT_COOKIE_TIMEOUT_MS
|
||||
: undefined;
|
||||
|
||||
if (options.authToken) {
|
||||
cookies.authToken = options.authToken;
|
||||
cookies.source = 'CLI argument';
|
||||
}
|
||||
if (options.ct0) {
|
||||
cookies.ct0 = options.ct0;
|
||||
if (!cookies.source) {
|
||||
cookies.source = 'CLI argument';
|
||||
}
|
||||
}
|
||||
|
||||
readEnvCookie(cookies, ['AUTH_TOKEN', 'TWITTER_AUTH_TOKEN'], 'authToken');
|
||||
readEnvCookie(cookies, ['CT0', 'TWITTER_CT0'], 'ct0');
|
||||
|
||||
if (cookies.authToken && cookies.ct0) {
|
||||
cookies.cookieHeader = cookieHeader(cookies.authToken, cookies.ct0);
|
||||
return { cookies, warnings };
|
||||
}
|
||||
|
||||
const sourcesToTry = resolveSources(options.cookieSource);
|
||||
for (const source of sourcesToTry) {
|
||||
const res = await readTwitterCookiesFromBrowser({
|
||||
source,
|
||||
chromeProfile: options.chromeProfile,
|
||||
firefoxProfile: options.firefoxProfile,
|
||||
cookieTimeoutMs,
|
||||
});
|
||||
warnings.push(...res.warnings);
|
||||
if (res.cookies.authToken && res.cookies.ct0) {
|
||||
return { cookies: res.cookies, warnings };
|
||||
}
|
||||
}
|
||||
|
||||
if (!cookies.authToken) {
|
||||
warnings.push(
|
||||
'Missing auth_token - provide via --auth-token, AUTH_TOKEN env var, or login to x.com in Safari/Chrome/Firefox',
|
||||
);
|
||||
}
|
||||
if (!cookies.ct0) {
|
||||
warnings.push('Missing ct0 - provide via --ct0, CT0 env var, or login to x.com in Safari/Chrome/Firefox');
|
||||
}
|
||||
if (cookies.authToken && cookies.ct0) {
|
||||
cookies.cookieHeader = cookieHeader(cookies.authToken, cookies.ct0);
|
||||
}
|
||||
|
||||
return { cookies, warnings };
|
||||
}
|
||||
@@ -1,12 +1,3 @@
|
||||
export {
|
||||
type CookieExtractionResult,
|
||||
type CookieSource,
|
||||
extractCookiesFromChrome,
|
||||
extractCookiesFromFirefox,
|
||||
extractCookiesFromSafari,
|
||||
resolveCredentials,
|
||||
type TwitterCookies,
|
||||
} from './cookies.js';
|
||||
export { runtimeQueryIds } from './runtime-query-ids.js';
|
||||
export {
|
||||
type CurrentUserResult,
|
||||
|
||||
@@ -4,6 +4,8 @@ import { type OperationName, QUERY_IDS, TARGET_QUERY_ID_OPERATIONS } from './twi
|
||||
import type { CurrentUserResult, TwitterClientOptions } from './twitter-client-types.js';
|
||||
import { normalizeQuoteDepth } from './twitter-client-utils.js';
|
||||
|
||||
const TRAILING_SLASHES = /\/+$/;
|
||||
|
||||
// biome-ignore lint/suspicious/noExplicitAny: TS mixin base constructor requirement.
|
||||
export type Constructor<T = object> = new (...args: any[]) => T;
|
||||
// biome-ignore lint/suspicious/noExplicitAny: TS mixin base constructor requirement.
|
||||
@@ -13,9 +15,7 @@ export type Mixin<TBase extends AbstractConstructor<TwitterClientBase>, TAdded>
|
||||
) => TwitterClientBase & TAdded;
|
||||
|
||||
export abstract class TwitterClientBase {
|
||||
protected authToken: string;
|
||||
protected ct0: string;
|
||||
protected cookieHeader: string;
|
||||
protected relayBaseUrl: string;
|
||||
protected userAgent: string;
|
||||
protected timeoutMs?: number;
|
||||
protected quoteDepth: number;
|
||||
@@ -24,12 +24,7 @@ export abstract class TwitterClientBase {
|
||||
protected clientUserId?: string;
|
||||
|
||||
constructor(options: TwitterClientOptions) {
|
||||
if (!options.cookies.authToken || !options.cookies.ct0) {
|
||||
throw new Error('Both authToken and ct0 cookies are required');
|
||||
}
|
||||
this.authToken = options.cookies.authToken;
|
||||
this.ct0 = options.cookies.ct0;
|
||||
this.cookieHeader = options.cookies.cookieHeader || `auth_token=${this.authToken}; ct0=${this.ct0}`;
|
||||
this.relayBaseUrl = this.normalizeRelayBaseUrl(options.relayBaseUrl ?? process.env.TWITTER_RELAY_BASE_URL);
|
||||
this.userAgent =
|
||||
options.userAgent ||
|
||||
'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';
|
||||
@@ -72,14 +67,15 @@ export abstract class TwitterClientBase {
|
||||
}
|
||||
|
||||
protected async fetchWithTimeout(url: string, init: RequestInit): Promise<Response> {
|
||||
const relayUrl = this.toRelayUrl(url);
|
||||
if (!this.timeoutMs || this.timeoutMs <= 0) {
|
||||
return fetch(url, init);
|
||||
return fetch(relayUrl, init);
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
|
||||
try {
|
||||
return await fetch(url, { ...init, signal: controller.signal });
|
||||
return await fetch(relayUrl, { ...init, signal: controller.signal });
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
@@ -93,20 +89,31 @@ export abstract class TwitterClientBase {
|
||||
return randomBytes(16).toString('hex');
|
||||
}
|
||||
|
||||
private normalizeRelayBaseUrl(value: string | undefined): string {
|
||||
const trimmed = value?.trim();
|
||||
if (!trimmed) {
|
||||
throw new Error('TWITTER_RELAY_BASE_URL is required');
|
||||
}
|
||||
return trimmed.replace(TRAILING_SLASHES, '');
|
||||
}
|
||||
|
||||
private toRelayUrl(url: string): string {
|
||||
const parsed = new URL(url);
|
||||
if (!['x.com', 'twitter.com', 'api.twitter.com', 'upload.twitter.com'].includes(parsed.hostname)) {
|
||||
throw new Error(`Unsupported Twitter API host: ${parsed.hostname}`);
|
||||
}
|
||||
return `${this.relayBaseUrl}${parsed.pathname}${parsed.search}`;
|
||||
}
|
||||
|
||||
protected getBaseHeaders(): Record<string, string> {
|
||||
const headers: Record<string, string> = {
|
||||
accept: '*/*',
|
||||
'accept-language': 'en-US,en;q=0.9',
|
||||
authorization:
|
||||
'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
|
||||
'x-csrf-token': this.ct0,
|
||||
'x-twitter-auth-type': 'OAuth2Session',
|
||||
'x-twitter-active-user': 'yes',
|
||||
'x-twitter-client-language': 'en',
|
||||
'x-client-uuid': this.clientUuid,
|
||||
'x-twitter-client-deviceid': this.clientDeviceId,
|
||||
'x-client-transaction-id': this.createTransactionId(),
|
||||
cookie: this.cookieHeader,
|
||||
'user-agent': this.userAgent,
|
||||
origin: 'https://x.com',
|
||||
referer: 'https://x.com/',
|
||||
|
||||
@@ -6,10 +6,6 @@ export const TWITTER_GRAPHQL_POST_URL = 'https://x.com/i/api/graphql';
|
||||
export const TWITTER_UPLOAD_URL = 'https://upload.twitter.com/i/media/upload.json';
|
||||
export const TWITTER_MEDIA_METADATA_URL = 'https://x.com/i/api/1.1/media/metadata/create.json';
|
||||
export const TWITTER_STATUS_UPDATE_URL = 'https://x.com/i/api/1.1/statuses/update.json';
|
||||
export const SETTINGS_SCREEN_NAME_REGEX = /"screen_name":"([^"]+)"/;
|
||||
export const SETTINGS_USER_ID_REGEX = /"user_id"\s*:\s*"(\d+)"/;
|
||||
export const SETTINGS_NAME_REGEX = /"name":"([^"\\]*(?:\\.[^"\\]*)*)"/;
|
||||
|
||||
// Query IDs rotate frequently; the values in query-ids.json are refreshed by
|
||||
// scripts/update-query-ids.ts. The fallback values keep the client usable if
|
||||
// the file is missing or incomplete.
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import type { TwitterCookies } from './cookies.js';
|
||||
|
||||
// Raw media entity from Twitter API
|
||||
export interface GraphqlMediaEntity {
|
||||
id_str?: string;
|
||||
@@ -327,7 +325,7 @@ export interface FollowingResult {
|
||||
}
|
||||
|
||||
export interface TwitterClientOptions {
|
||||
cookies: TwitterCookies;
|
||||
relayBaseUrl?: string;
|
||||
userAgent?: string;
|
||||
timeoutMs?: number;
|
||||
// Max depth for quoted tweets (0 disables). Defaults to 1.
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
import type { AbstractConstructor, Mixin, TwitterClientBase } from './twitter-client-base.js';
|
||||
import {
|
||||
SETTINGS_NAME_REGEX,
|
||||
SETTINGS_SCREEN_NAME_REGEX,
|
||||
SETTINGS_USER_ID_REGEX,
|
||||
TWITTER_API_BASE,
|
||||
} from './twitter-client-constants.js';
|
||||
import { TWITTER_API_BASE } from './twitter-client-constants.js';
|
||||
import { buildFollowingFeatures } from './twitter-client-features.js';
|
||||
import type { CurrentUserResult, FollowingResult, TwitterUser } from './twitter-client-types.js';
|
||||
import { extractCursorFromInstructions, parseUsersFromInstructions } from './twitter-client-utils.js';
|
||||
@@ -157,7 +152,7 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the account associated with the current cookies
|
||||
* Fetch the account associated with the configured relay.
|
||||
*/
|
||||
async getCurrentUser(): Promise<CurrentUserResult> {
|
||||
const candidateUrls = [
|
||||
@@ -234,48 +229,6 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: scrape the authenticated settings page (HTML) for screen_name/user_id
|
||||
const profilePages = ['https://x.com/settings/account', 'https://twitter.com/settings/account'];
|
||||
for (const page of profilePages) {
|
||||
try {
|
||||
const response = await this.fetchWithTimeout(page, {
|
||||
headers: {
|
||||
cookie: this.cookieHeader,
|
||||
'user-agent': this.userAgent,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
lastError = `HTTP ${response.status} (settings page)`;
|
||||
continue;
|
||||
}
|
||||
|
||||
const html = await response.text();
|
||||
const usernameMatch = SETTINGS_SCREEN_NAME_REGEX.exec(html);
|
||||
const idMatch = SETTINGS_USER_ID_REGEX.exec(html);
|
||||
const nameMatch = SETTINGS_NAME_REGEX.exec(html);
|
||||
|
||||
const username = usernameMatch?.[1];
|
||||
const userId = idMatch?.[1];
|
||||
const name = nameMatch?.[1]?.replace(/\\"/g, '"');
|
||||
|
||||
if (username && userId) {
|
||||
return {
|
||||
success: true,
|
||||
user: {
|
||||
id: userId,
|
||||
username,
|
||||
name: name || username,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
lastError = 'Could not parse settings page for user info';
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: lastError ?? 'Unknown error fetching current user',
|
||||
@@ -375,7 +328,7 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
}
|
||||
|
||||
// GraphQL Following can also return 404 (queryId churn / endpoint flakiness).
|
||||
// Fallback to the internal v1.1 REST endpoint used by the web client (cookie-auth; no dev API key).
|
||||
// Fallback to the internal v1.1 REST endpoint used by the web client through the relay.
|
||||
// Note: REST fallback does not support cursor pagination.
|
||||
const restAttempt = await this.getFollowingViaRest(userId, count);
|
||||
if (restAttempt.success) {
|
||||
@@ -481,7 +434,7 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
}
|
||||
|
||||
// GraphQL Followers regularly returns 404 (queryId churn / endpoint flakiness).
|
||||
// Fallback to the internal v1.1 REST endpoint used by the web client (cookie-auth; no dev API key).
|
||||
// Fallback to the internal v1.1 REST endpoint used by the web client through the relay.
|
||||
// Note: REST fallback does not support cursor pagination.
|
||||
const restAttempt = await this.getFollowersViaRest(userId, count);
|
||||
if (restAttempt.success) {
|
||||
|
||||
Reference in New Issue
Block a user