From 1f6e228272d9ebd212586ff1856e7365a17451ce Mon Sep 17 00:00:00 2001 From: yuta Date: Wed, 24 Jun 2026 03:39:34 +0900 Subject: [PATCH 1/2] Use twitter safe relay --- .envrc | 1 + README.md | 55 +-- docs/index.html | 4 +- docs/releasing.md | 2 +- docs/testing.md | 17 +- flake.lock | 25 ++ flake.nix | 51 +++ package.json | 6 - patches/@steipete__sweet-cookie.patch | 76 ---- pnpm-lock.yaml | 35 +- pnpm-workspace.yaml | 2 + src/cli/program.ts | 17 +- src/cli/shared.ts | 69 +--- src/commands/bookmarks.ts | 14 +- src/commands/check.ts | 54 +-- src/commands/home.ts | 14 +- src/commands/lists.ts | 28 +- src/commands/news.ts | 14 +- src/commands/post.ts | 38 +- src/commands/read.ts | 42 +- src/commands/search.ts | 28 +- src/commands/unbookmark.ts | 14 +- src/commands/user-tweets.ts | 14 +- src/commands/users.ts | 68 +--- src/lib/cookies.ts | 235 ----------- src/lib/index.ts | 9 - src/lib/twitter-client-base.ts | 39 +- src/lib/twitter-client-constants.ts | 4 - src/lib/twitter-client-types.ts | 4 +- src/lib/twitter-client-users.ts | 55 +-- tests/commands.bookmarks.test.ts | 5 +- tests/commands.news.test.ts | 34 +- tests/commands.read.test.ts | 10 +- tests/commands.search.test.ts | 5 +- tests/commands.users.test.ts | 5 +- tests/cookies.test.ts | 381 ------------------ tests/help-output.test.ts | 5 +- tests/library-exports.test.ts | 3 +- tests/live/live-all.test.ts | 161 +++----- tests/live/live.test.ts | 115 ++---- tests/twitter-client-coverage.api.test.ts | 59 ++- tests/twitter-client-coverage.core.test.ts | 39 +- tests/twitter-client-coverage.news.test.ts | 31 +- tests/twitter-client-coverage.upload.test.ts | 25 +- tests/twitter-client-fixtures.ts | 7 +- ...ter-client.constructor-tweet-reply.test.ts | 68 ++-- tests/twitter-client.conversations.test.ts | 10 +- tests/twitter-client.current-user.test.ts | 42 +- ...witter-client.following-pagination.test.ts | 10 +- tests/twitter-client.following.test.ts | 16 +- tests/twitter-client.get-tweet.test.ts | 24 +- tests/twitter-client.home-timeline.test.ts | 16 +- tests/twitter-client.json-full.test.ts | 16 +- ...twitter-client.json-full.timelines.test.ts | 10 +- tests/twitter-client.likes.test.ts | 10 +- .../twitter-client.lists.memberships.test.ts | 6 +- .../twitter-client.lists.owned.errors.test.ts | 16 +- tests/twitter-client.lists.owned.test.ts | 14 +- ...tter-client.lists.pagination.edges.test.ts | 10 +- tests/twitter-client.lists.pagination.test.ts | 6 +- tests/twitter-client.lists.timeline.test.ts | 12 +- tests/twitter-client.media.test.ts | 8 +- tests/twitter-client.pagination.test.ts | 26 +- tests/twitter-client.search-bookmarks.test.ts | 34 +- tests/twitter-client.user-lookup.test.ts | 16 +- tests/twitter-client.user-tweets.test.ts | 28 +- 66 files changed, 597 insertions(+), 1720 deletions(-) create mode 100644 .envrc create mode 100644 flake.lock create mode 100644 flake.nix delete mode 100644 patches/@steipete__sweet-cookie.patch delete mode 100644 src/lib/cookies.ts delete mode 100644 tests/cookies.test.ts diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..3550a30 --- /dev/null +++ b/.envrc @@ -0,0 +1 @@ +use flake diff --git a/README.md b/README.md index 704967b..23c40e6 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ # bird 🐦 — fast X CLI for tweeting, replying, and reading -`bird` is a fast X CLI for tweeting, replying, and reading via X/Twitter GraphQL (cookie auth). +`bird` is a fast X CLI for tweeting, replying, and reading via X/Twitter GraphQL through twitter safe relay. ## Disclaimer -This project uses X/Twitter’s **undocumented** web GraphQL API (and cookie auth). X can change endpoints, query IDs, -and anti-bot behavior at any time — **expect this to break without notice**. +This project uses X/Twitter’s **undocumented** web GraphQL API through twitter safe relay. X can change endpoints, +query IDs, and anti-bot behavior at any time — **expect this to break without notice**. ## Install @@ -29,6 +29,9 @@ brew install steipete/tap/bird ## Quickstart ```bash +# Point bird at your running twitter safe relay +export TWITTER_RELAY_BASE_URL=http://localhost:6900 + # Show the logged-in account bird whoami @@ -127,10 +130,11 @@ By default, the command fetches from For You, News, Sports, and Entertainment ta `bird` can be used as a library (same GraphQL client as the CLI): ```ts -import { TwitterClient, resolveCredentials } from '@steipete/bird'; +import { TwitterClient } from '@steipete/bird'; -const { cookies } = await resolveCredentials({ cookieSource: 'safari' }); -const client = new TwitterClient({ cookies }); +const client = new TwitterClient({ + relayBaseUrl: process.env.TWITTER_RELAY_BASE_URL +}); // Search for tweets const searchResult = await client.search('from:steipete', 50); @@ -167,24 +171,19 @@ const sportsNews = await client.getNews(10, { - `bird list-timeline [-n count] [--all] [--max-pages n] [--cursor string] [--json]` — get tweets from a list timeline; `--max-pages` implies `--all`. - `bird following [--user ] [-n count] [--json]` — list users that you (or another user) follow. - `bird followers [--user ] [-n count] [--json]` — list users that follow you (or another user). -- `bird whoami` — print which Twitter account your cookies belong to. -- `bird check` — show which credentials are available and where they were sourced from. +- `bird whoami` — print which Twitter account your relay belongs to. +- `bird check` — verify relay configuration and account access. - `bird likes [-n count] [--json]` — list your liked tweets. - `bird news [-n count] [--ai-only] [--with-tweets] [--tweets-per-item n] [--for-you] [--news-only] [--sports] [--entertainment] [--trending-only] [--json]` — fetch news and trending topics from X's Explore tabs (fetches from For You, News, Sports, and Entertainment tabs by default). - `bird trending` — alias for `news` command. - `bird list-timeline [-n count] [--all] [--max-pages n] [--cursor string] [--json]` — get tweets from a list timeline; `--max-pages` implies `--all`. - `bird following [--user ] [-n count] [--json]` — list users that you (or another user) follow. - `bird followers [--user ] [-n count] [--json]` — list users that follow you (or another user). - - `bird whoami` — print which Twitter account your cookies belong to. - - `bird check` — show which credentials are available and where they were sourced from. + - `bird whoami` — print which Twitter account your relay belongs to. + - `bird check` — verify relay configuration and account access. Global options: -- `--auth-token `: set the `auth_token` cookie manually. -- `--ct0 `: set the `ct0` cookie manually. -- `--cookie-source `: choose browser cookie source (repeatable; order matters). -- `--chrome-profile `: Chrome profile for cookie extraction. -- `--firefox-profile `: Firefox profile for cookie extraction. -- `--cookie-timeout `: cookie extraction timeout for keychain/OS helpers (milliseconds). +- `--relay-base-url `: twitter safe relay base URL (defaults to `TWITTER_RELAY_BASE_URL`). - `--timeout `: abort requests after the given timeout (milliseconds). - `--quote-depth `: max quoted tweet depth in JSON output (default: 1; 0 disables). - `--plain`: stable output (no emoji, no color). @@ -195,23 +194,14 @@ Global options: ## Authentication (GraphQL) -GraphQL mode uses your existing X/Twitter web session (no password prompt). It sends requests to internal -X endpoints and authenticates via cookies (`auth_token`, `ct0`). +`bird` does not handle Twitter authentication locally. It sends Twitter API-compatible requests to twitter safe relay, +and the relay handles authentication. Write operations: - `tweet`/`reply` primarily use GraphQL (`CreateTweet`). - If GraphQL returns error `226` (“automated request”), `bird` falls back to the legacy `statuses/update.json` endpoint. -`bird` resolves credentials in this order: - -1. CLI flags: `--auth-token`, `--ct0` -2. Environment variables: `AUTH_TOKEN`, `CT0` (fallback: `TWITTER_AUTH_TOKEN`, `TWITTER_CT0`) -3. Browser cookies via `@steipete/sweet-cookie` (override via `--cookie-source` order) - -Browser cookie sources: -- Safari: `~/Library/Cookies/Cookies.binarycookies` (fallback: `~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies`) -- Chrome: `~/Library/Application Support/Google/Chrome//Cookies` -- Firefox: `~/Library/Application Support/Firefox/Profiles//cookies.sqlite` +Configure the relay URL with `TWITTER_RELAY_BASE_URL` or `--relay-base-url`. ## Config (JSON5) @@ -224,18 +214,15 @@ Example `~/.config/bird/config.json5`: ```json5 { - // Cookie source order for browser extraction (string or array) - cookieSource: ["firefox", "safari"], - firefoxProfile: "default-release", - cookieTimeoutMs: 30000, + relayBaseUrl: "http://localhost:6900", timeoutMs: 20000, quoteDepth: 1 } ``` Environment shortcuts: +- `TWITTER_RELAY_BASE_URL` - `BIRD_TIMEOUT_MS` -- `BIRD_COOKIE_TIMEOUT_MS` - `BIRD_QUOTE_DEPTH` ## Output @@ -331,7 +318,7 @@ Exit codes: - Attach media with `--media` (repeatable) and optional `--alt` per item. - Up to 4 images/GIFs, or 1 video (no mixing). Supported: jpg, jpeg, png, webp, gif, mp4, mov. -- Images/GIFs + 1 video supported (uploads via Twitter legacy upload endpoint + cookies; video may take longer to process). +- Images/GIFs + 1 video supported (uploads via Twitter legacy upload endpoint through the relay; video may take longer to process). Example: diff --git a/docs/index.html b/docs/index.html index 9f1b08c..9c17561 100644 --- a/docs/index.html +++ b/docs/index.html @@ -9,7 +9,7 @@ bird.fast — fast X CLI @@ -107,7 +107,7 @@ bird tweet "hi from bird.fast" auth - cookies + relay diff --git a/docs/releasing.md b/docs/releasing.md index 71c980a..0b96944 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -56,4 +56,4 @@ If you want a single-file binary for Homebrew/GitHub assets: ## Notes - Scoped npm name (`@steipete/bird`) requires `--access public` on first publish. - Homebrew formula assumes macOS universal binary; adjust URL/name if you ship per-arch. -- Config defaults (JSON5) and Safari/Chrome/Firefox cookie selection are documented in `README.md` — keep that in sync for each release. +- Config defaults (JSON5) and twitter safe relay setup are documented in `README.md` — keep that in sync for each release. diff --git a/docs/testing.md b/docs/testing.md index d5f33e1..8ff0051 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -8,27 +8,24 @@ Runs the CLI against real Twitter/X GraphQL endpoints to verify read-only commands still work. Requirements: -- Auth cookies in env: - - `AUTH_TOKEN` (or `TWITTER_AUTH_TOKEN`) - - `CT0` (or `TWITTER_CT0`) +- `TWITTER_RELAY_BASE_URL` pointing at a running twitter safe relay - Network access Run: - `pnpm test:live` -- `pnpm bird following --all --max-pages 2 --json --cookie-source chrome --chrome-profile Default` -- `pnpm bird list-timeline --all --max-pages 2 --json --cookie-source chrome --chrome-profile Default` -- `pnpm bird search "from:steipete" --all --max-pages 2 --json --cookie-source chrome --chrome-profile Default` -- `pnpm bird home --count 5 --json --cookie-source chrome --chrome-profile Default` -- `pnpm bird home --count 5 --following --json --cookie-source chrome --chrome-profile Default` +- `pnpm bird following --all --max-pages 2 --json` +- `pnpm bird list-timeline --all --max-pages 2 --json` +- `pnpm bird search "from:steipete" --all --max-pages 2 --json` +- `pnpm bird home --count 5 --json` +- `pnpm bird home --count 5 --following --json` Notes: - Live tests are skipped unless `BIRD_LIVE=1` (set by `pnpm test:live`). - Search query is configurable via `BIRD_LIVE_SEARCH_QUERY`. - Command timeout is configurable via `BIRD_LIVE_TIMEOUT_MS` (ms). -- Cookie extraction timeout is configurable via `BIRD_LIVE_COOKIE_TIMEOUT_MS` (ms). - Spawned CLI `NODE_ENV` defaults to `production` (override with `BIRD_LIVE_NODE_ENV`). - If you don't tweet, set `BIRD_LIVE_TWEET_ID` to a known tweet ID to use for `read/replies/thread`. - Long-form article coverage: set `BIRD_LIVE_LONGFORM_TWEET_ID` to a known article tweet ID (example: `2007184284944322584` from @X; refresh by finding a tweet with `article` via `bird user-tweets X -n 20 --json`). - Optional: set `BIRD_LIVE_BOOKMARK_FOLDER_ID` to exercise `bookmarks --folder-id`. - `bird query-ids --fresh` live coverage: set `BIRD_LIVE_QUERY_IDS_FRESH=1`. -- The live suite may hit internal X endpoints (v1.1 REST) as fallback; it still uses cookie auth (no developer API key). +- The live suite may hit internal X endpoints (v1.1 REST) as fallback through the relay. diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..500a957 --- /dev/null +++ b/flake.lock @@ -0,0 +1,25 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1781577229, + "narHash": "sha256-lrp67w8AulE9Ks53n27I45ADSzbOCn4H+CNW1Ck8B+8=", + "rev": "567a49d1913ce81ac6e9582e3553dd90a955875f", + "revCount": 1017464, + "type": "tarball", + "url": "https://api.flakehub.com/f/pinned/NixOS/nixpkgs/0.1.1017464%2Brev-567a49d1913ce81ac6e9582e3553dd90a955875f/019ed27e-44b2-7462-b1ef-3564aa6c28ee/source.tar.gz" + }, + "original": { + "type": "tarball", + "url": "https://flakehub.com/f/NixOS/nixpkgs/0.1" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..10a9426 --- /dev/null +++ b/flake.nix @@ -0,0 +1,51 @@ +{ + description = "A Nix-flake-based Node.js development environment"; + + inputs.nixpkgs.url = "https://flakehub.com/f/NixOS/nixpkgs/0.1"; # unstable Nixpkgs + + outputs = + { self, ... }@inputs: + + let + supportedSystems = [ + "x86_64-linux" + "aarch64-linux" + "aarch64-darwin" + ]; + forEachSupportedSystem = + f: + inputs.nixpkgs.lib.genAttrs supportedSystems ( + system: + f { + inherit system; + pkgs = import inputs.nixpkgs { + inherit system; + overlays = [ inputs.self.overlays.default ]; + }; + } + ); + in + { + overlays.default = final: prev: rec { + nodejs = prev.nodejs; + yarn = (prev.yarn.override { inherit nodejs; }); + }; + + devShells = forEachSupportedSystem ( + { pkgs, system }: + { + default = pkgs.mkShellNoCC { + packages = with pkgs; [ + nodejs + pnpm + yarn + bun + self.formatter.${system} + ]; + }; + } + ); + + formatter = forEachSupportedSystem ({ pkgs, ... }: pkgs.nixfmt); + }; +} diff --git a/package.json b/package.json index c4676a0..ee25f8c 100644 --- a/package.json +++ b/package.json @@ -35,16 +35,10 @@ "graphql:update": "tsx scripts/update-query-ids.ts" }, "dependencies": { - "@steipete/sweet-cookie": "0.1.0", "commander": "^14.0.2", "json5": "^2.2.3", "kleur": "^4.1.5" }, - "pnpm": { - "patchedDependencies": { - "@steipete/sweet-cookie": "patches/@steipete__sweet-cookie.patch" - } - }, "devDependencies": { "@biomejs/biome": "^2.3.10", "@types/node": "^25.0.3", diff --git a/patches/@steipete__sweet-cookie.patch b/patches/@steipete__sweet-cookie.patch deleted file mode 100644 index 12ab8a5..0000000 --- a/patches/@steipete__sweet-cookie.patch +++ /dev/null @@ -1,76 +0,0 @@ -diff --git a/dist/providers/chromeSqliteMac.js b/dist/providers/chromeSqliteMac.js -index 71c815f77378d03e07061976ac372b3a55a61ac4..b21c15640955a8e7faa8f1d6ea6fed7ca8f04ddb 100644 ---- a/dist/providers/chromeSqliteMac.js -+++ b/dist/providers/chromeSqliteMac.js -@@ -4,19 +4,37 @@ import { decryptChromiumAes128CbcCookieValue, deriveAes128CbcKeyFromPassword, } - import { getCookiesFromChromeSqliteDb } from './chromeSqlite/shared.js'; - import { readKeychainGenericPasswordFirst } from './chromium/macosKeychain.js'; - import { resolveCookiesDbFromProfileOrRoots } from './chromium/paths.js'; -+ -+function resolveKeychainForDb(dbPath) { -+ const lower = dbPath.toLowerCase(); -+ if (lower.includes('bravesoftware') || lower.includes('brave-browser') || lower.includes('brave browser')) { -+ return { -+ account: 'Brave', -+ services: ['Brave Safe Storage'], -+ label: 'Brave Safe Storage', -+ }; -+ } -+ return { -+ account: 'Chrome', -+ services: ['Chrome Safe Storage'], -+ label: 'Chrome Safe Storage', -+ }; -+} -+ - export async function getCookiesFromChromeSqliteMac(options, origins, allowlistNames) { - const dbPath = resolveChromeCookiesDb(options.profile); - if (!dbPath) { - return { cookies: [], warnings: ['Chrome cookies database not found.'] }; - } - const warnings = []; -- // On macOS, Chrome stores its "Safe Storage" secret in Keychain. -+ // On macOS, Chromium stores its "Safe Storage" secret in Keychain. - // `security find-generic-password` is stable and avoids any native Node keychain modules. -+ const keychain = resolveKeychainForDb(dbPath); - const passwordResult = await readKeychainGenericPasswordFirst({ -- account: 'Chrome', -- services: ['Chrome Safe Storage'], -- timeoutMs: 3_000, -- label: 'Chrome Safe Storage', -+ account: keychain.account, -+ services: keychain.services, -+ timeoutMs: options.timeoutMs ?? 3_000, -+ label: keychain.label, - }); - if (!passwordResult.ok) { - warnings.push(passwordResult.error); -@@ -24,7 +42,7 @@ export async function getCookiesFromChromeSqliteMac(options, origins, allowlistN - } - const chromePassword = passwordResult.password.trim(); - if (!chromePassword) { -- warnings.push('macOS Keychain returned an empty Chrome Safe Storage password.'); -+ warnings.push(`macOS Keychain returned an empty ${keychain.label} password.`); - return { cookies: [], warnings }; - } - // Chromium uses PBKDF2(password, "saltysalt", 1003, 16, sha1) for AES-128-CBC cookie values on macOS. -@@ -46,14 +64,18 @@ export async function getCookiesFromChromeSqliteMac(options, origins, allowlistN - result.warnings.unshift(...warnings); - return result; - } -+ - function resolveChromeCookiesDb(profile) { - const home = homedir(); - /* c8 ignore next */ - const roots = process.platform === 'darwin' -- ? [path.join(home, 'Library', 'Application Support', 'Google', 'Chrome')] -+ ? [ -+ path.join(home, 'Library', 'Application Support', 'Google', 'Chrome'), -+ path.join(home, 'Library', 'Application Support', 'BraveSoftware', 'Brave-Browser'), -+ ] - : []; - const args = { roots }; - if (profile !== undefined) - args.profile = profile; - return resolveCookiesDbFromProfileOrRoots(args); - } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bf333b8..a2ceac9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1,21 +1,13 @@ lockfileVersion: '9.0' settings: - autoInstallPeers: false + autoInstallPeers: true excludeLinksFromLockfile: false -patchedDependencies: - '@steipete/sweet-cookie': - hash: 4ff44e9d3b5770a7b751c7a3470572bdf485763c28ead8055468dd0ae9a6e986 - path: patches/@steipete__sweet-cookie.patch - importers: .: dependencies: - '@steipete/sweet-cookie': - specifier: 0.1.0 - version: 0.1.0(patch_hash=4ff44e9d3b5770a7b751c7a3470572bdf485763c28ead8055468dd0ae9a6e986) commander: specifier: ^14.0.2 version: 14.0.2 @@ -96,24 +88,28 @@ packages: engines: {node: '>=14.21.3'} cpu: [arm64] os: [linux] + libc: [musl] '@biomejs/cli-linux-arm64@2.3.10': resolution: {integrity: sha512-hhPw2V3/EpHKsileVOFynuWiKRgFEV48cLe0eA+G2wO4SzlwEhLEB9LhlSrVeu2mtSn205W283LkX7Fh48CaxA==} engines: {node: '>=14.21.3'} cpu: [arm64] os: [linux] + libc: [glibc] '@biomejs/cli-linux-x64-musl@2.3.10': resolution: {integrity: sha512-QTfHZQh62SDFdYc2nfmZFuTm5yYb4eO1zwfB+90YxUumRCR171tS1GoTX5OD0wrv4UsziMPmrePMtkTnNyYG3g==} engines: {node: '>=14.21.3'} cpu: [x64] os: [linux] + libc: [musl] '@biomejs/cli-linux-x64@2.3.10': resolution: {integrity: sha512-wwAkWD1MR95u+J4LkWP74/vGz+tRrIQvr8kfMMJY8KOQ8+HMVleREOcPYsQX82S7uueco60L58Wc6M1I9WA9Dw==} engines: {node: '>=14.21.3'} cpu: [x64] os: [linux] + libc: [glibc] '@biomejs/cli-win32-arm64@2.3.10': resolution: {integrity: sha512-o7lYc9n+CfRbHvkjPhm8s9FgbKdYZu5HCcGVMItLjz93EhgJ8AM44W+QckDqLA9MKDNFrR8nPbO4b73VC5kGGQ==} @@ -337,21 +333,25 @@ packages: resolution: {integrity: sha512-EMx92X5q+hHc3olTuj/kgkx9+yP0p/AVs4yvHbUfzZhBekXNpUWxWvg4hIKmQWn+Ee2j4o80/0ACGO0hDYJ9mg==} cpu: [arm64] os: [linux] + libc: [glibc] '@oxlint/linux-arm64-musl@1.36.0': resolution: {integrity: sha512-7YCxtrPIctVYLqWrWkk8pahdCxch6PtsaucfMLC7TOlDt4nODhnQd4yzEscKqJ8Gjrw1bF4g+Ngob1gB+Qr9Fw==} cpu: [arm64] os: [linux] + libc: [musl] '@oxlint/linux-x64-gnu@1.36.0': resolution: {integrity: sha512-lnaJVlx5r3NWmoOMesfQXJSf78jHTn8Z+sdAf795Kgteo72+qGC1Uax2SToCJVN2J8PNG3oRV5bLriiCNR2i6Q==} cpu: [x64] os: [linux] + libc: [glibc] '@oxlint/linux-x64-musl@1.36.0': resolution: {integrity: sha512-AhuEU2Qdl66lSfTGu/Htirq8r/8q2YnZoG3yEXLMQWnPMn7efy8spD/N1NA7kH0Hll+cdfwgQkQqC2G4MS2lPQ==} cpu: [x64] os: [linux] + libc: [musl] '@oxlint/win32-arm64@1.36.0': resolution: {integrity: sha512-GlWCBjUJY2QgvBFuNRkiRJu7K/djLmM0UQKfZV8IN+UXbP/JbjZHWKRdd4LXlQmzoz7M5Hd6p+ElCej8/90FCg==} @@ -397,56 +397,67 @@ packages: resolution: {integrity: sha512-dV3T9MyAf0w8zPVLVBptVlzaXxka6xg1f16VAQmjg+4KMSTWDvhimI/Y6mp8oHwNrmnmVl9XxJ/w/mO4uIQONA==} cpu: [arm] os: [linux] + libc: [glibc] '@rollup/rollup-linux-arm-musleabihf@4.53.5': resolution: {integrity: sha512-wIGYC1x/hyjP+KAu9+ewDI+fi5XSNiUi9Bvg6KGAh2TsNMA3tSEs+Sh6jJ/r4BV/bx/CyWu2ue9kDnIdRyafcQ==} cpu: [arm] os: [linux] + libc: [musl] '@rollup/rollup-linux-arm64-gnu@4.53.5': resolution: {integrity: sha512-Y+qVA0D9d0y2FRNiG9oM3Hut/DgODZbU9I8pLLPwAsU0tUKZ49cyV1tzmB/qRbSzGvY8lpgGkJuMyuhH7Ma+Vg==} cpu: [arm64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-arm64-musl@4.53.5': resolution: {integrity: sha512-juaC4bEgJsyFVfqhtGLz8mbopaWD+WeSOYr5E16y+1of6KQjc0BpwZLuxkClqY1i8sco+MdyoXPNiCkQou09+g==} cpu: [arm64] os: [linux] + libc: [musl] '@rollup/rollup-linux-loong64-gnu@4.53.5': resolution: {integrity: sha512-rIEC0hZ17A42iXtHX+EPJVL/CakHo+tT7W0pbzdAGuWOt2jxDFh7A/lRhsNHBcqL4T36+UiAgwO8pbmn3dE8wA==} cpu: [loong64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-ppc64-gnu@4.53.5': resolution: {integrity: sha512-T7l409NhUE552RcAOcmJHj3xyZ2h7vMWzcwQI0hvn5tqHh3oSoclf9WgTl+0QqffWFG8MEVZZP1/OBglKZx52Q==} cpu: [ppc64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-riscv64-gnu@4.53.5': resolution: {integrity: sha512-7OK5/GhxbnrMcxIFoYfhV/TkknarkYC1hqUw1wU2xUN3TVRLNT5FmBv4KkheSG2xZ6IEbRAhTooTV2+R5Tk0lQ==} cpu: [riscv64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-riscv64-musl@4.53.5': resolution: {integrity: sha512-GwuDBE/PsXaTa76lO5eLJTyr2k8QkPipAyOrs4V/KJufHCZBJ495VCGJol35grx9xryk4V+2zd3Ri+3v7NPh+w==} cpu: [riscv64] os: [linux] + libc: [musl] '@rollup/rollup-linux-s390x-gnu@4.53.5': resolution: {integrity: sha512-IAE1Ziyr1qNfnmiQLHBURAD+eh/zH1pIeJjeShleII7Vj8kyEm2PF77o+lf3WTHDpNJcu4IXJxNO0Zluro8bOw==} cpu: [s390x] os: [linux] + libc: [glibc] '@rollup/rollup-linux-x64-gnu@4.53.5': resolution: {integrity: sha512-Pg6E+oP7GvZ4XwgRJBuSXZjcqpIW3yCBhK4BcsANvb47qMvAbCjR6E+1a/U2WXz1JJxp9/4Dno3/iSJLcm5auw==} cpu: [x64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-x64-musl@4.53.5': resolution: {integrity: sha512-txGtluxDKTxaMDzUduGP0wdfng24y1rygUMnmlUJ88fzCCULCLn7oE5kb2+tRB+MWq1QDZT6ObT5RrR8HFRKqg==} cpu: [x64] os: [linux] + libc: [musl] '@rollup/rollup-openharmony-arm64@4.53.5': resolution: {integrity: sha512-3DFiLPnTxiOQV993fMc+KO8zXHTcIjgaInrqlG8zDp1TlhYl6WgrOHuJkJQ6M8zHEcntSJsUp1XFZSY8C1DYbg==} @@ -476,10 +487,6 @@ packages: '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} - '@steipete/sweet-cookie@0.1.0': - resolution: {integrity: sha512-cF8hS6rTohAFI1NAm2/HM9omBlw6V1DpwF6q5e9FB+l274HjtyirCgCc6QK2Rtuh7uDoqWHshFQZPsceyJuVgw==} - engines: {node: '>=22'} - '@types/chai@5.2.3': resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} @@ -1056,8 +1063,6 @@ snapshots: '@standard-schema/spec@1.1.0': {} - '@steipete/sweet-cookie@0.1.0(patch_hash=4ff44e9d3b5770a7b751c7a3470572bdf485763c28ead8055468dd0ae9a6e986)': {} - '@types/chai@5.2.3': dependencies: '@types/deep-eql': 4.0.2 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index efc037a..09a02ca 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,2 +1,4 @@ +allowBuilds: + esbuild: true onlyBuiltDependencies: - esbuild diff --git a/src/cli/program.ts b/src/cli/program.ts index 39d9501..d1b5566 100644 --- a/src/cli/program.ts +++ b/src/cli/program.ts @@ -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 ', 'Twitter auth_token cookie') - .option('--ct0 ', 'Twitter ct0 cookie') - .option('--chrome-profile ', 'Chrome profile name for cookie extraction', ctx.config.chromeProfile) - .option('--firefox-profile ', 'Firefox profile name for cookie extraction', ctx.config.firefoxProfile) - .option('--cookie-timeout ', 'Cookie extraction timeout in milliseconds (keychain/OS helpers)') - .option('--cookie-source ', 'Cookie source for browser cookie extraction (repeatable)', collectCookieSource) + .option('--relay-base-url ', 'twitter safe relay base URL', ctx.config.relayBaseUrl) .option('--media ', 'Attach media file (repeatable, up to 4 images or 1 video)', collect) .option('--alt ', 'Alt text for the corresponding --media (repeatable)', collect) .option('--timeout ', 'Request timeout in milliseconds') diff --git a/src/cli/shared.ts b/src/cli/shared.ts index 0e2cd56..4aa150b 100644 --- a/src/cli/shared.ts +++ b/src/cli/shared.ts @@ -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; + 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): 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 { - 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, diff --git a/src/commands/bookmarks.ts b/src/commands/bookmarks.ts index abda8cb..b8a9bcf 100644 --- a/src/commands/bookmarks.ts +++ b/src/commands/bookmarks.ts @@ -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/.`); diff --git a/src/commands/check.ts b/src/commands/check.ts index 548d30b..7933ee8 100644 --- a/src/commands/check.ts +++ b/src/commands/check.ts @@ -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); } }); diff --git a/src/commands/home.ts b/src/commands/home.ts index 876cf35..190871d 100644 --- a/src/commands/home.ts +++ b/src/commands/home.ts @@ -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 diff --git a/src/commands/lists.ts b/src/commands/lists.ts index d7297b7..f67adef 100644 --- a/src/commands/lists.ts +++ b/src/commands/lists.ts @@ -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 }; diff --git a/src/commands/news.ts b/src/commands/news.ts index 853180a..0a6fb28 100644 --- a/src/commands/news.ts +++ b/src/commands/news.ts @@ -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; diff --git a/src/commands/post.ts b/src/commands/post.ts index e39401b..0c2de86 100644 --- a/src/commands/post.ts +++ b/src/commands/post.ts @@ -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); diff --git a/src/commands/read.ts b/src/commands/read.ts index 5a353d4..29938c7 100644 --- a/src/commands/read.ts +++ b/src/commands/read.ts @@ -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 diff --git a/src/commands/search.ts b/src/commands/search.ts index 0461b7f..f99f555 100644 --- a/src/commands/search.ts +++ b/src/commands/search.ts @@ -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(); diff --git a/src/commands/unbookmark.ts b/src/commands/unbookmark.ts index caef70e..f5dbe08 100644 --- a/src/commands/unbookmark.ts +++ b/src/commands/unbookmark.ts @@ -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) { diff --git a/src/commands/user-tweets.ts b/src/commands/user-tweets.ts index 001bc18..1bc7ef6 100644 --- a/src/commands/user-tweets.ts +++ b/src/commands/user-tweets.ts @@ -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}...`); diff --git a/src/commands/users.ts b/src/commands/users.ts index 00d7bba..d433294 100644 --- a/src/commands/users.ts +++ b/src/commands/users.ts @@ -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); diff --git a/src/lib/cookies.ts b/src/lib/cookies.ts deleted file mode 100644 index e9b0211..0000000 --- a/src/lib/cookies.ts +++ /dev/null @@ -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 { - 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 { - return readTwitterCookiesFromBrowser({ source: 'safari' }); -} - -export async function extractCookiesFromChrome(profile?: string): Promise { - return readTwitterCookiesFromBrowser({ source: 'chrome', chromeProfile: profile }); -} - -export async function extractCookiesFromFirefox(profile?: string): Promise { - 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 { - 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 }; -} diff --git a/src/lib/index.ts b/src/lib/index.ts index f642546..ca52ff5 100644 --- a/src/lib/index.ts +++ b/src/lib/index.ts @@ -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, diff --git a/src/lib/twitter-client-base.ts b/src/lib/twitter-client-base.ts index 2da5a3b..f586785 100644 --- a/src/lib/twitter-client-base.ts +++ b/src/lib/twitter-client-base.ts @@ -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 = new (...args: any[]) => T; // biome-ignore lint/suspicious/noExplicitAny: TS mixin base constructor requirement. @@ -13,9 +15,7 @@ export type Mixin, 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 { + 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 { const headers: Record = { 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/', diff --git a/src/lib/twitter-client-constants.ts b/src/lib/twitter-client-constants.ts index 5365b07..aa03079 100644 --- a/src/lib/twitter-client-constants.ts +++ b/src/lib/twitter-client-constants.ts @@ -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. diff --git a/src/lib/twitter-client-types.ts b/src/lib/twitter-client-types.ts index e5eb466..f1115bc 100644 --- a/src/lib/twitter-client-types.ts +++ b/src/lib/twitter-client-types.ts @@ -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. diff --git a/src/lib/twitter-client-users.ts b/src/lib/twitter-client-users.ts index b95ee42..dc53056 100644 --- a/src/lib/twitter-client-users.ts +++ b/src/lib/twitter-client-users.ts @@ -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>( } /** - * Fetch the account associated with the current cookies + * Fetch the account associated with the configured relay. */ async getCurrentUser(): Promise { const candidateUrls = [ @@ -234,48 +229,6 @@ export function withUsers>( } } - // 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>( } // 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>( } // 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) { diff --git a/tests/commands.bookmarks.test.ts b/tests/commands.bookmarks.test.ts index 37ac8e7..9432e7e 100644 --- a/tests/commands.bookmarks.test.ts +++ b/tests/commands.bookmarks.test.ts @@ -8,10 +8,7 @@ describe('bookmarks command', () => { const program = new Command(); const ctx = { resolveTimeoutFromOptions: () => undefined, - resolveCredentialsFromOptions: async () => ({ - cookies: { authToken: 'auth', ct0: 'ct0', cookieHeader: 'auth=auth; ct0=ct0' }, - warnings: [], - }), + resolveRelayBaseUrlFromOptions: () => 'https://relay.example', p: () => '', printTweets: () => undefined, } as unknown as CliContext; diff --git a/tests/commands.news.test.ts b/tests/commands.news.test.ts index bbaff3e..9d5096b 100644 --- a/tests/commands.news.test.ts +++ b/tests/commands.news.test.ts @@ -13,14 +13,7 @@ describe('news command', () => { mockContext = { resolveTimeoutFromOptions: () => 30000, resolveQuoteDepthFromOptions: () => undefined, - resolveCredentialsFromOptions: async () => ({ - cookies: { - authToken: 'auth', - ct0: 'ct0', - cookieHeader: 'auth=auth; ct0=ct0', - }, - warnings: [], - }), + resolveRelayBaseUrlFromOptions: () => 'https://relay.example', p: (type: string) => `[${type}] `, colors: { accent: (text: string) => text, @@ -128,31 +121,6 @@ describe('news command', () => { } }); - it('requires both authToken and ct0 credentials', async () => { - mockContext.resolveCredentialsFromOptions = async () => ({ - cookies: { - authToken: '', - ct0: '', - cookieHeader: '', - }, - warnings: [], - }); - - registerNewsCommand(program, mockContext as CliContext); - const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => { - throw new Error(`exit ${code}`); - }) as never); - const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); - - try { - await expect(program.parseAsync(['node', 'bird', 'news'])).rejects.toThrow('exit 1'); - expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Missing required credentials')); - } finally { - exitSpy.mockRestore(); - errorSpy.mockRestore(); - } - }); - it('limits related tweets to tweets-per-item in CLI output', async () => { registerNewsCommand(program, mockContext as CliContext); const getNewsSpy = vi.spyOn(TwitterClient.prototype, 'getNews').mockResolvedValue({ diff --git a/tests/commands.read.test.ts b/tests/commands.read.test.ts index 585eac0..13c2fd8 100644 --- a/tests/commands.read.test.ts +++ b/tests/commands.read.test.ts @@ -10,10 +10,7 @@ describe('replies command', () => { resolveTimeoutFromOptions: () => undefined, resolveQuoteDepthFromOptions: () => 1, extractTweetId: (input: string) => input, - resolveCredentialsFromOptions: async () => ({ - cookies: { authToken: 'auth', ct0: 'ct0', cookieHeader: 'auth=auth; ct0=ct0' }, - warnings: [], - }), + resolveRelayBaseUrlFromOptions: () => 'https://relay.example', p: () => '', printTweets: () => undefined, printTweetsResult: () => undefined, @@ -85,10 +82,7 @@ describe('thread command', () => { resolveTimeoutFromOptions: () => undefined, resolveQuoteDepthFromOptions: () => 1, extractTweetId: (input: string) => input, - resolveCredentialsFromOptions: async () => ({ - cookies: { authToken: 'auth', ct0: 'ct0', cookieHeader: 'auth=auth; ct0=ct0' }, - warnings: [], - }), + resolveRelayBaseUrlFromOptions: () => 'https://relay.example', p: () => '', printTweets: () => undefined, printTweetsResult: () => undefined, diff --git a/tests/commands.search.test.ts b/tests/commands.search.test.ts index 3163829..183d120 100644 --- a/tests/commands.search.test.ts +++ b/tests/commands.search.test.ts @@ -13,10 +13,7 @@ describe('search command', () => { mockContext = { resolveTimeoutFromOptions: () => undefined, resolveQuoteDepthFromOptions: () => undefined, - resolveCredentialsFromOptions: async () => ({ - cookies: { authToken: 'auth', ct0: 'ct0', cookieHeader: 'auth=auth; ct0=ct0' }, - warnings: [], - }), + resolveRelayBaseUrlFromOptions: () => 'https://relay.example', p: () => '', printTweetsResult: vi.fn(), }; diff --git a/tests/commands.users.test.ts b/tests/commands.users.test.ts index 03a5c82..61ab1d8 100644 --- a/tests/commands.users.test.ts +++ b/tests/commands.users.test.ts @@ -6,10 +6,7 @@ import { TwitterClient } from '../src/lib/twitter-client.js'; const baseCtx = { resolveTimeoutFromOptions: () => undefined, - resolveCredentialsFromOptions: async () => ({ - cookies: { authToken: 'auth', ct0: 'ct0', cookieHeader: 'auth=auth; ct0=ct0' }, - warnings: [], - }), + resolveRelayBaseUrlFromOptions: () => 'https://relay.example', p: () => '', printTweets: () => undefined, } as unknown as CliContext; diff --git a/tests/cookies.test.ts b/tests/cookies.test.ts deleted file mode 100644 index abbf370..0000000 --- a/tests/cookies.test.ts +++ /dev/null @@ -1,381 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; - -type SweetCookieResult = { cookies: Array<{ name: string; value: string; domain?: string }>; warnings: string[] }; - -const sweet = vi.hoisted(() => ({ - results: new Map(), - options: new Map(), -})); - -vi.mock('@steipete/sweet-cookie', () => ({ - getCookies: vi.fn(async (options: { browsers?: string[]; timeoutMs?: number }) => { - const browser = options.browsers?.[0] ?? 'unknown'; - sweet.options.set(browser, options); - return ( - sweet.results.get(browser) ?? { - cookies: [], - warnings: [], - } - ); - }), -})); - -describe('cookies', () => { - const originalEnv = process.env; - - beforeEach(() => { - vi.resetModules(); - sweet.results.clear(); - sweet.options.clear(); - process.env = { ...originalEnv }; - process.env.AUTH_TOKEN = undefined; - process.env.TWITTER_AUTH_TOKEN = undefined; - process.env.CT0 = undefined; - process.env.TWITTER_CT0 = undefined; - }); - - afterEach(() => { - process.env = originalEnv; - vi.restoreAllMocks(); - }); - - describe('resolveCredentials', () => { - it('honors cookieSource=firefox even when Safari has cookies', async () => { - sweet.results.set('safari', { - cookies: [ - { name: 'auth_token', value: 'safari_auth', domain: 'x.com' }, - { name: 'ct0', value: 'safari_ct0', domain: 'x.com' }, - ], - warnings: [], - }); - sweet.results.set('firefox', { - cookies: [ - { name: 'auth_token', value: 'firefox_auth', domain: 'x.com' }, - { name: 'ct0', value: 'firefox_ct0', domain: 'x.com' }, - ], - warnings: [], - }); - - const { resolveCredentials } = await import('../src/lib/cookies.js'); - const result = await resolveCredentials({ cookieSource: 'firefox' }); - - expect(result.cookies.authToken).toBe('firefox_auth'); - expect(result.cookies.ct0).toBe('firefox_ct0'); - expect(result.cookies.source).toContain('Firefox'); - }); - - it('honors cookieSource=safari', async () => { - if (process.platform !== 'darwin') { - return; - } - sweet.results.set('safari', { - cookies: [ - { name: 'auth_token', value: 'safari_auth', domain: 'x.com' }, - { name: 'ct0', value: 'safari_ct0', domain: 'x.com' }, - ], - warnings: [], - }); - - const { resolveCredentials } = await import('../src/lib/cookies.js'); - const result = await resolveCredentials({ cookieSource: 'safari' }); - - expect(result.cookies.authToken).toBe('safari_auth'); - expect(result.cookies.ct0).toBe('safari_ct0'); - expect(result.cookies.cookieHeader).toContain('auth_token=safari_auth'); - expect(result.cookies.cookieHeader).toContain('ct0=safari_ct0'); - expect(result.cookies.source).toBe('Safari'); - }); - - it('uses firefox when enabled and returns cookies', async () => { - sweet.results.set('firefox', { - cookies: [ - { name: 'auth_token', value: 'firefox_auth', domain: 'x.com' }, - { name: 'ct0', value: 'firefox_ct0', domain: 'x.com' }, - ], - warnings: [], - }); - - const { resolveCredentials } = await import('../src/lib/cookies.js'); - const result = await resolveCredentials({ cookieSource: 'firefox', firefoxProfile: 'abc.default-release' }); - - expect(result.cookies.authToken).toBe('firefox_auth'); - expect(result.cookies.ct0).toBe('firefox_ct0'); - expect(result.cookies.cookieHeader).toContain('auth_token=firefox_auth'); - expect(result.cookies.cookieHeader).toContain('ct0=firefox_ct0'); - expect(result.cookies.source).toContain('Firefox'); - }); - - it('should prioritize CLI arguments over env vars', async () => { - process.env.AUTH_TOKEN = 'env_auth'; - process.env.CT0 = 'env_ct0'; - - const { resolveCredentials } = await import('../src/lib/cookies.js'); - const result = await resolveCredentials({ - authToken: 'cli_auth', - ct0: 'cli_ct0', - }); - - expect(result.cookies.authToken).toBe('cli_auth'); - expect(result.cookies.ct0).toBe('cli_ct0'); - expect(result.cookies.cookieHeader).toBe('auth_token=cli_auth; ct0=cli_ct0'); - expect(result.cookies.source).toBe('CLI argument'); - }); - - it('should use AUTH_TOKEN env var', async () => { - process.env.AUTH_TOKEN = 'test_auth_token'; - process.env.CT0 = 'test_ct0'; - - const { resolveCredentials } = await import('../src/lib/cookies.js'); - const result = await resolveCredentials({ cookieSource: 'safari' }); - - expect(result.cookies.authToken).toBe('test_auth_token'); - expect(result.cookies.ct0).toBe('test_ct0'); - expect(result.cookies.source).toBe('env AUTH_TOKEN'); - }); - - it('should use TWITTER_AUTH_TOKEN env var as fallback', async () => { - process.env.TWITTER_AUTH_TOKEN = 'twitter_auth'; - process.env.TWITTER_CT0 = 'twitter_ct0'; - - const { resolveCredentials } = await import('../src/lib/cookies.js'); - const result = await resolveCredentials({ cookieSource: 'safari' }); - - expect(result.cookies.authToken).toBe('twitter_auth'); - expect(result.cookies.ct0).toBe('twitter_ct0'); - }); - - it('should trim whitespace from values', async () => { - process.env.AUTH_TOKEN = ' trimmed_auth '; - process.env.CT0 = ' trimmed_ct0 '; - - const { resolveCredentials } = await import('../src/lib/cookies.js'); - const result = await resolveCredentials({}); - - expect(result.cookies.authToken).toBe('trimmed_auth'); - expect(result.cookies.ct0).toBe('trimmed_ct0'); - }); - - it('should treat empty strings as null', async () => { - process.env.AUTH_TOKEN = ' '; - process.env.CT0 = ''; - - const { resolveCredentials } = await import('../src/lib/cookies.js'); - const result = await resolveCredentials({ cookieSource: 'safari' }); - - expect(result.cookies.authToken).toBeNull(); - expect(result.cookies.ct0).toBeNull(); - expect(result.warnings.length).toBeGreaterThan(0); - }); - - it('should warn when credentials are missing', async () => { - const { resolveCredentials } = await import('../src/lib/cookies.js'); - const result = await resolveCredentials({ cookieSource: 'safari' }); - - expect(result.warnings).toContain( - 'Missing auth_token - provide via --auth-token, AUTH_TOKEN env var, or login to x.com in Safari/Chrome/Firefox', - ); - expect(result.warnings).toContain( - 'Missing ct0 - provide via --ct0, CT0 env var, or login to x.com in Safari/Chrome/Firefox', - ); - }); - - it('falls back to Chrome when enabled and Firefox disabled', async () => { - sweet.results.set('chrome', { - cookies: [ - { name: 'auth_token', value: 'test_auth', domain: 'x.com' }, - { name: 'ct0', value: 'test_ct0', domain: 'x.com' }, - ], - warnings: [], - }); - - const { resolveCredentials } = await import('../src/lib/cookies.js'); - const result = await resolveCredentials({ - cookieSource: 'chrome', - chromeProfile: 'Default', - cookieTimeoutMs: 15000, - }); - - expect(result.cookies.authToken).toBe('test_auth'); - expect(result.cookies.ct0).toBe('test_ct0'); - expect(result.cookies.source).toContain('Chrome'); - expect(sweet.options.get('chrome')?.timeoutMs).toBe(15000); - }); - - it('defaults to a 30s cookie timeout on macOS', async () => { - if (process.platform !== 'darwin') { - return; - } - sweet.results.set('chrome', { - cookies: [ - { name: 'auth_token', value: 'test_auth', domain: 'x.com' }, - { name: 'ct0', value: 'test_ct0', domain: 'x.com' }, - ], - warnings: [], - }); - - const { resolveCredentials } = await import('../src/lib/cookies.js'); - const result = await resolveCredentials({ cookieSource: 'chrome' }); - - expect(result.cookies.authToken).toBe('test_auth'); - expect(result.cookies.ct0).toBe('test_ct0'); - expect(sweet.options.get('chrome')?.timeoutMs).toBe(30000); - }); - - it('uses default browser order when cookieSource is omitted', async () => { - sweet.results.set('safari', { cookies: [], warnings: [] }); - sweet.results.set('chrome', { cookies: [], warnings: [] }); - sweet.results.set('firefox', { - cookies: [ - { name: 'auth_token', value: 'firefox_auth', domain: 'x.com' }, - { name: 'ct0', value: 'firefox_ct0', domain: 'x.com' }, - ], - warnings: [], - }); - - const { resolveCredentials } = await import('../src/lib/cookies.js'); - const result = await resolveCredentials({}); - - expect(result.cookies.authToken).toBe('firefox_auth'); - expect(result.cookies.ct0).toBe('firefox_ct0'); - expect(result.cookies.source).toContain('Firefox'); - }); - - it('prefers twitter.com cookies when x.com is missing', async () => { - sweet.results.set('chrome', { - cookies: [ - { name: 'auth_token', value: 'twitter_auth', domain: 'twitter.com' }, - { name: 'ct0', value: 'twitter_ct0', domain: 'twitter.com' }, - ], - warnings: [], - }); - - const { resolveCredentials } = await import('../src/lib/cookies.js'); - const result = await resolveCredentials({ cookieSource: 'chrome' }); - - expect(result.cookies.authToken).toBe('twitter_auth'); - expect(result.cookies.ct0).toBe('twitter_ct0'); - }); - - it('falls back to the first cookie when no domain matches', async () => { - sweet.results.set('firefox', { - cookies: [ - { name: 'auth_token', value: 'first_auth', domain: 'example.com' }, - { name: 'ct0', value: 'first_ct0', domain: 'example.com' }, - ], - warnings: [], - }); - - const { resolveCredentials } = await import('../src/lib/cookies.js'); - const result = await resolveCredentials({ cookieSource: 'firefox' }); - - expect(result.cookies.authToken).toBe('first_auth'); - expect(result.cookies.ct0).toBe('first_ct0'); - }); - }); - - describe('extractCookiesFromSafari', () => { - it('returns cookies from Safari', async () => { - if (process.platform !== 'darwin') { - return; - } - sweet.results.set('safari', { - cookies: [ - { name: 'auth_token', value: 'safari_auth', domain: 'x.com' }, - { name: 'ct0', value: 'safari_ct0', domain: 'x.com' }, - ], - warnings: [], - }); - - const { extractCookiesFromSafari } = await import('../src/lib/cookies.js'); - const result = await extractCookiesFromSafari(); - - expect(result.cookies.authToken).toBe('safari_auth'); - expect(result.cookies.ct0).toBe('safari_ct0'); - expect(result.cookies.source).toBe('Safari'); - }); - - it('prefers Safari over Chrome when both are available', async () => { - if (process.platform !== 'darwin') { - return; - } - sweet.results.set('safari', { - cookies: [ - { name: 'auth_token', value: 'safari_auth', domain: 'x.com' }, - { name: 'ct0', value: 'safari_ct0', domain: 'x.com' }, - ], - warnings: [], - }); - sweet.results.set('chrome', { - cookies: [ - { name: 'auth_token', value: 'chrome_auth', domain: 'x.com' }, - { name: 'ct0', value: 'chrome_ct0', domain: 'x.com' }, - ], - warnings: [], - }); - - const { resolveCredentials } = await import('../src/lib/cookies.js'); - const result = await resolveCredentials({ cookieSource: ['safari', 'chrome'] }); - - expect(result.cookies.authToken).toBe('safari_auth'); - expect(result.cookies.ct0).toBe('safari_ct0'); - }); - }); - - describe('extractCookiesFromChrome', () => { - it('returns cookies when Chrome yields values', async () => { - sweet.results.set('chrome', { - cookies: [ - { name: 'auth_token', value: 'test_auth', domain: 'x.com' }, - { name: 'ct0', value: 'test_ct0', domain: 'x.com' }, - ], - warnings: [], - }); - - const { extractCookiesFromChrome } = await import('../src/lib/cookies.js'); - const result = await extractCookiesFromChrome('Default'); - - expect(result.cookies.authToken).toBe('test_auth'); - expect(result.cookies.ct0).toBe('test_ct0'); - expect(result.cookies.source).toContain('Chrome'); - expect(result.warnings).toHaveLength(0); - }); - - it('warns when Chrome returns no cookies', async () => { - sweet.results.set('chrome', { cookies: [], warnings: [] }); - - const { extractCookiesFromChrome } = await import('../src/lib/cookies.js'); - const result = await extractCookiesFromChrome('Default'); - - expect(result.cookies.authToken).toBeNull(); - expect(result.cookies.ct0).toBeNull(); - expect(result.warnings.some((w) => w.includes('No Twitter cookies found in Chrome'))).toBe(true); - }); - }); - - describe('extractCookiesFromFirefox', () => { - it('warns when Firefox cookies database is missing', async () => { - sweet.results.set('firefox', { - cookies: [], - warnings: ['Firefox cookies database not found.'], - }); - - const { extractCookiesFromFirefox } = await import('../src/lib/cookies.js'); - const result = await extractCookiesFromFirefox('missing-profile'); - - expect(result.cookies.authToken).toBeNull(); - expect(result.cookies.ct0).toBeNull(); - expect(result.warnings).toContain('Firefox cookies database not found.'); - }); - - it('warns when Firefox returns no cookies', async () => { - sweet.results.set('firefox', { cookies: [], warnings: [] }); - - const { extractCookiesFromFirefox } = await import('../src/lib/cookies.js'); - const result = await extractCookiesFromFirefox('abc.default-release'); - - expect(result.cookies.authToken).toBeNull(); - expect(result.cookies.ct0).toBeNull(); - expect(result.warnings.some((w) => w.includes('No Twitter cookies found in Firefox'))).toBe(true); - }); - }); -}); diff --git a/tests/help-output.test.ts b/tests/help-output.test.ts index 6abbd30..12bb432 100644 --- a/tests/help-output.test.ts +++ b/tests/help-output.test.ts @@ -45,8 +45,9 @@ describe('root help output', () => { cmd.outputHelp(); - expect(help).toContain('--auth-token'); - expect(help).toContain('--ct0'); + expect(help).toContain('--relay-base-url'); + expect(help).not.toContain('--auth-token'); + expect(help).not.toContain('--ct0'); expect(help).toContain('--timeout'); expect(help).toContain('--quote-depth'); }); diff --git a/tests/library-exports.test.ts b/tests/library-exports.test.ts index e4969ba..bdb1d7d 100644 --- a/tests/library-exports.test.ts +++ b/tests/library-exports.test.ts @@ -1,9 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { resolveCredentials, TwitterClient } from '../src/index.js'; +import { TwitterClient } from '../src/index.js'; describe('library exports', () => { it('exposes primary library surface', () => { expect(typeof TwitterClient).toBe('function'); - expect(typeof resolveCredentials).toBe('function'); }); }); diff --git a/tests/live/live-all.test.ts b/tests/live/live-all.test.ts index 51904e2..fcb3d20 100644 --- a/tests/live/live-all.test.ts +++ b/tests/live/live-all.test.ts @@ -7,8 +7,7 @@ type RunResult = { exitCode: number; stdout: string; stderr: string; signal: Nod const LIVE = process.env.BIRD_LIVE === '1'; -const authToken = (process.env.AUTH_TOKEN ?? process.env.TWITTER_AUTH_TOKEN ?? '').trim(); -const ct0 = (process.env.CT0 ?? process.env.TWITTER_CT0 ?? '').trim(); +const relayBaseUrl = (process.env.TWITTER_RELAY_BASE_URL ?? '').trim(); const CLI_PATH = path.resolve(process.cwd(), 'dist', 'cli.js'); @@ -27,8 +26,6 @@ function runBird(args: string[], options: { timeoutMs?: number } = {}): Promise< stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, - AUTH_TOKEN: authToken, - CT0: ct0, NODE_ENV: LIVE_NODE_ENV, }, }); @@ -76,7 +73,6 @@ const d = LIVE ? describe : describe.skip; d('live CLI (Twitter/X) all commands', () => { const timeoutArg = (process.env.BIRD_LIVE_TIMEOUT_MS ?? '20000').trim(); - const cookieTimeoutArg = (process.env.BIRD_LIVE_COOKIE_TIMEOUT_MS ?? '30000').trim(); const baseArgs = ['--plain', '--timeout', timeoutArg, '--quote-depth', '0']; let whoamiStdout = ''; @@ -92,19 +88,16 @@ d('live CLI (Twitter/X) all commands', () => { throw new Error(`Missing ${CLI_PATH}. Run: pnpm run build:dist`); } - if (!authToken || !ct0) { - const check = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'check'], { timeoutMs: 45_000 }); - if (check.exitCode !== 0) { - throw new Error( - 'Missing live credentials.\n' + - '- Option A: set AUTH_TOKEN + CT0 (or TWITTER_AUTH_TOKEN/TWITTER_CT0)\n' + - '- Option B: login to x.com in Safari/Chrome/Firefox for cookie extraction\n\n' + - `bird check output:\n${check.stdout}\n${check.stderr}`, - ); - } + if (!relayBaseUrl) { + throw new Error('Missing TWITTER_RELAY_BASE_URL for live tests.'); } - const who = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'whoami'], { timeoutMs: 45_000 }); + const check = await runBird([...baseArgs, 'check'], { timeoutMs: 45_000 }); + if (check.exitCode !== 0) { + throw new Error(`bird check failed:\n${check.stdout}\n${check.stderr}`); + } + + const who = await runBird([...baseArgs, 'whoami'], { timeoutMs: 45_000 }); if (who.exitCode !== 0) { throw new Error(`whoami failed (exit ${who.exitCode}, signal ${who.signal ?? 'none'}):\n${who.stderr}`); } @@ -132,12 +125,9 @@ d('live CLI (Twitter/X) all commands', () => { const searchQuery = ( process.env.BIRD_LIVE_SEARCH_QUERY ?? `from:${handle} -filter:replies -filter:retweets` ).trim(); - const search = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'search', searchQuery, '-n', '25', '--json'], - { - timeoutMs: 45_000, - }, - ); + const search = await runBird([...baseArgs, 'search', searchQuery, '-n', '25', '--json'], { + timeoutMs: 45_000, + }); if (search.exitCode !== 0) { throw new Error( `search failed (exit ${search.exitCode}, signal ${search.signal ?? 'none'}):\n${search.stderr}`, @@ -157,7 +147,7 @@ d('live CLI (Twitter/X) all commands', () => { listId = (process.env.BIRD_LIVE_LIST_ID ?? '').trim(); if (!listId) { - const lists = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'lists', '-n', '1', '--json'], { + const lists = await runBird([...baseArgs, 'lists', '-n', '1', '--json'], { timeoutMs: 45_000, }); if (lists.exitCode === 0) { @@ -166,12 +156,9 @@ d('live CLI (Twitter/X) all commands', () => { } } if (!listId) { - const lists = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'lists', '--member-of', '-n', '1', '--json'], - { - timeoutMs: 45_000, - }, - ); + const lists = await runBird([...baseArgs, 'lists', '--member-of', '-n', '1', '--json'], { + timeoutMs: 45_000, + }); if (lists.exitCode === 0) { const parsed = parseJson>(lists.stdout); listId = String(parsed[0]?.id ?? '').trim(); @@ -186,7 +173,7 @@ d('live CLI (Twitter/X) all commands', () => { }); it('check works', async () => { - const check = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'check'], { timeoutMs: 45_000 }); + const check = await runBird([...baseArgs, 'check'], { timeoutMs: 45_000 }); expect(check.exitCode).toBe(0); expect(check.stdout.length).toBeGreaterThan(0); }); @@ -199,17 +186,14 @@ d('live CLI (Twitter/X) all commands', () => { it('search returns JSON array', async () => { const search = searchStdout ? { exitCode: 0, stdout: searchStdout } - : await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'search', `from:${handle}`, '-n', '10', '--json'], - { timeoutMs: 45_000 }, - ); + : await runBird([...baseArgs, 'search', `from:${handle}`, '-n', '10', '--json'], { timeoutMs: 45_000 }); expect(search.exitCode).toBe(0); const tweets = parseJson>(search.stdout); expect(Array.isArray(tweets)).toBe(true); }); it('read returns tweet JSON', async () => { - const read = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'read', tweetId, '--json'], { + const read = await runBird([...baseArgs, 'read', tweetId, '--json'], { timeoutMs: 45_000, }); expect(read.exitCode).toBe(0); @@ -219,7 +203,7 @@ d('live CLI (Twitter/X) all commands', () => { }); it('tweet-id shorthand returns tweet JSON', async () => { - const shorthand = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, tweetId, '--json'], { + const shorthand = await runBird([...baseArgs, tweetId, '--json'], { timeoutMs: 45_000, }); expect(shorthand.exitCode).toBe(0); @@ -228,7 +212,7 @@ d('live CLI (Twitter/X) all commands', () => { }); it('replies returns JSON array', async () => { - const replies = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'replies', tweetId, '--json'], { + const replies = await runBird([...baseArgs, 'replies', tweetId, '--json'], { timeoutMs: 45_000, }); expect(replies.exitCode).toBe(0); @@ -237,7 +221,7 @@ d('live CLI (Twitter/X) all commands', () => { }); it('thread returns JSON array', async () => { - const thread = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'thread', tweetId, '--json'], { + const thread = await runBird([...baseArgs, 'thread', tweetId, '--json'], { timeoutMs: 45_000, }); expect(thread.exitCode).toBe(0); @@ -246,31 +230,25 @@ d('live CLI (Twitter/X) all commands', () => { }); it('mentions returns JSON array', async () => { - const mentions = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'mentions', '-n', '10', '--json'], - { - timeoutMs: 45_000, - }, - ); + const mentions = await runBird([...baseArgs, 'mentions', '-n', '10', '--json'], { + timeoutMs: 45_000, + }); expect(mentions.exitCode).toBe(0); const mentionTweets = parseJson>(mentions.stdout); expect(Array.isArray(mentionTweets)).toBe(true); }); it('bookmarks returns JSON array', async () => { - const bookmarks = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'bookmarks', '-n', '10', '--json'], - { - timeoutMs: 45_000, - }, - ); + const bookmarks = await runBird([...baseArgs, 'bookmarks', '-n', '10', '--json'], { + timeoutMs: 45_000, + }); expect(bookmarks.exitCode).toBe(0); const bookmarkTweets = parseJson>(bookmarks.stdout); expect(Array.isArray(bookmarkTweets)).toBe(true); }); it('likes returns JSON array', async () => { - const likes = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'likes', '-n', '10', '--json'], { + const likes = await runBird([...baseArgs, 'likes', '-n', '10', '--json'], { timeoutMs: 45_000, }); expect(likes.exitCode).toBe(0); @@ -279,24 +257,18 @@ d('live CLI (Twitter/X) all commands', () => { }); it('following returns JSON array', async () => { - const following = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'following', '--user', userId, '-n', '10', '--json'], - { - timeoutMs: 45_000, - }, - ); + const following = await runBird([...baseArgs, 'following', '--user', userId, '-n', '10', '--json'], { + timeoutMs: 45_000, + }); expect(following.exitCode).toBe(0); const followingUsers = parseJson>(following.stdout); expect(Array.isArray(followingUsers)).toBe(true); }); it('followers returns JSON array', async () => { - const followers = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'followers', '--user', userId, '-n', '10', '--json'], - { - timeoutMs: 45_000, - }, - ); + const followers = await runBird([...baseArgs, 'followers', '--user', userId, '-n', '10', '--json'], { + timeoutMs: 45_000, + }); expect(followers.exitCode).toBe(0); const followerUsers = parseJson>(followers.stdout); expect(Array.isArray(followerUsers)).toBe(true); @@ -304,12 +276,9 @@ d('live CLI (Twitter/X) all commands', () => { it('user-tweets returns JSON array', async () => { const testHandle = process.env.BIRD_LIVE_USER_TWEETS_HANDLE || 'X'; - const userTweets = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'user-tweets', testHandle, '-n', '5', '--json'], - { - timeoutMs: 45_000, - }, - ); + const userTweets = await runBird([...baseArgs, 'user-tweets', testHandle, '-n', '5', '--json'], { + timeoutMs: 45_000, + }); expect(userTweets.exitCode).toBe(0); const tweets = parseJson>(userTweets.stdout); expect(Array.isArray(tweets)).toBe(true); @@ -320,20 +289,7 @@ d('live CLI (Twitter/X) all commands', () => { const testHandle = process.env.BIRD_LIVE_USER_TWEETS_PAGED_HANDLE ?? process.env.BIRD_LIVE_USER_TWEETS_HANDLE ?? 'X'; const userTweets = await runBird( - [ - ...baseArgs, - '--cookie-timeout', - cookieTimeoutArg, - 'user-tweets', - testHandle, - '-n', - '50', - '--max-pages', - '3', - '--delay', - '0', - '--json', - ], + [...baseArgs, 'user-tweets', testHandle, '-n', '50', '--max-pages', '3', '--delay', '0', '--json'], { timeoutMs: 45_000, }, @@ -344,7 +300,7 @@ d('live CLI (Twitter/X) all commands', () => { }); it('lists returns JSON array', async () => { - const lists = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'lists', '-n', '10', '--json'], { + const lists = await runBird([...baseArgs, 'lists', '-n', '10', '--json'], { timeoutMs: 45_000, }); expect(lists.exitCode).toBe(0); @@ -356,17 +312,14 @@ d('live CLI (Twitter/X) all commands', () => { if (!listTimelineAvailable) { return; } - const timeline = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'list-timeline', listId, '-n', '5', '--json'], - { timeoutMs: 45_000 }, - ); + const timeline = await runBird([...baseArgs, 'list-timeline', listId, '-n', '5', '--json'], { timeoutMs: 45_000 }); expect(timeline.exitCode).toBe(0); const payload = parseJson>(timeline.stdout); expect(Array.isArray(payload)).toBe(true); }); it('home for-you returns JSON array', async () => { - const home = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'home', '-n', '5', '--json'], { + const home = await runBird([...baseArgs, 'home', '-n', '5', '--json'], { timeoutMs: 45_000, }); expect(home.exitCode).toBe(0); @@ -375,20 +328,14 @@ d('live CLI (Twitter/X) all commands', () => { }, 60_000); it('home following returns JSON array', async () => { - let home = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'home', '--following', '-n', '5', '--json'], - { - timeoutMs: 45_000, - }, - ); + let home = await runBird([...baseArgs, 'home', '--following', '-n', '5', '--json'], { + timeoutMs: 45_000, + }); if (home.exitCode !== 0 && home.stderr.includes('OverCapacity')) { await sleep(1500); - home = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'home', '--following', '-n', '5', '--json'], - { - timeoutMs: 45_000, - }, - ); + home = await runBird([...baseArgs, 'home', '--following', '-n', '5', '--json'], { + timeoutMs: 45_000, + }); } expect(home.exitCode).toBe(0); const payload = parseJson>(home.stdout); @@ -396,27 +343,21 @@ d('live CLI (Twitter/X) all commands', () => { }, 60_000); it('news returns JSON array', async () => { - const news = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'news', '-n', '5', '--ai-only', '--json'], - { timeoutMs: 45_000 }, - ); + const news = await runBird([...baseArgs, 'news', '-n', '5', '--ai-only', '--json'], { timeoutMs: 45_000 }); expect(news.exitCode).toBe(0); const payload = parseJson>(news.stdout); expect(Array.isArray(payload)).toBe(true); }); it('trending returns JSON array', async () => { - const trending = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'trending', '-n', '5', '--json'], - { timeoutMs: 45_000 }, - ); + const trending = await runBird([...baseArgs, 'trending', '-n', '5', '--json'], { timeoutMs: 45_000 }); expect(trending.exitCode).toBe(0); const payload = parseJson>(trending.stdout); expect(Array.isArray(payload)).toBe(true); }); it('query-ids returns JSON', async () => { - const queryIds = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'query-ids', '--json'], { + const queryIds = await runBird([...baseArgs, 'query-ids', '--json'], { timeoutMs: 60_000, }); expect(queryIds.exitCode).toBe(0); diff --git a/tests/live/live.test.ts b/tests/live/live.test.ts index 2addb2d..cc6ca38 100644 --- a/tests/live/live.test.ts +++ b/tests/live/live.test.ts @@ -7,8 +7,7 @@ type RunResult = { exitCode: number; stdout: string; stderr: string; signal: Nod const LIVE = process.env.BIRD_LIVE === '1'; -const authToken = (process.env.AUTH_TOKEN ?? process.env.TWITTER_AUTH_TOKEN ?? '').trim(); -const ct0 = (process.env.CT0 ?? process.env.TWITTER_CT0 ?? '').trim(); +const relayBaseUrl = (process.env.TWITTER_RELAY_BASE_URL ?? '').trim(); const CLI_PATH = path.resolve(process.cwd(), 'dist', 'cli.js'); @@ -27,8 +26,6 @@ function runBird(args: string[], options: { timeoutMs?: number } = {}): Promise< stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, - AUTH_TOKEN: authToken, - CT0: ct0, NODE_ENV: LIVE_NODE_ENV, }, }); @@ -72,7 +69,6 @@ const d = LIVE ? describe : describe.skip; d('live CLI (Twitter/X)', () => { const timeoutArg = (process.env.BIRD_LIVE_TIMEOUT_MS ?? '20000').trim(); - const cookieTimeoutArg = (process.env.BIRD_LIVE_COOKIE_TIMEOUT_MS ?? '30000').trim(); const baseArgs = ['--plain', '--timeout', timeoutArg, '--quote-depth', '0']; let whoamiStdout = ''; @@ -85,19 +81,16 @@ d('live CLI (Twitter/X)', () => { throw new Error(`Missing ${CLI_PATH}. Run: pnpm run build:dist`); } - if (!authToken || !ct0) { - const check = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'check'], { timeoutMs: 45_000 }); - if (check.exitCode !== 0) { - throw new Error( - 'Missing live credentials.\n' + - '- Option A: set AUTH_TOKEN + CT0 (or TWITTER_AUTH_TOKEN/TWITTER_CT0)\n' + - '- Option B: login to x.com in Safari/Chrome/Firefox for cookie extraction\n\n' + - `bird check output:\n${check.stdout}\n${check.stderr}`, - ); - } + if (!relayBaseUrl) { + throw new Error('Missing TWITTER_RELAY_BASE_URL for live tests.'); } - const who = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'whoami'], { timeoutMs: 45_000 }); + const check = await runBird([...baseArgs, 'check'], { timeoutMs: 45_000 }); + if (check.exitCode !== 0) { + throw new Error(`bird check failed:\n${check.stdout}\n${check.stderr}`); + } + + const who = await runBird([...baseArgs, 'whoami'], { timeoutMs: 45_000 }); if (who.exitCode !== 0) { throw new Error(`whoami failed (exit ${who.exitCode}, signal ${who.signal ?? 'none'}):\n${who.stderr}`); } @@ -127,12 +120,9 @@ d('live CLI (Twitter/X)', () => { const searchQuery = ( process.env.BIRD_LIVE_SEARCH_QUERY ?? `from:${handle} -filter:replies -filter:retweets` ).trim(); - const search = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'search', searchQuery, '-n', '25', '--json'], - { - timeoutMs: 45_000, - }, - ); + const search = await runBird([...baseArgs, 'search', searchQuery, '-n', '25', '--json'], { + timeoutMs: 45_000, + }); if (search.exitCode !== 0) { throw new Error(`search failed (exit ${search.exitCode}, signal ${search.signal ?? 'none'}):\n${search.stderr}`); } @@ -160,7 +150,7 @@ d('live CLI (Twitter/X)', () => { }); it('read returns tweet JSON', async () => { - const read = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'read', tweetId, '--json'], { + const read = await runBird([...baseArgs, 'read', tweetId, '--json'], { timeoutMs: 45_000, }); expect(read.exitCode).toBe(0); @@ -170,7 +160,7 @@ d('live CLI (Twitter/X)', () => { }); it('tweet-id shorthand returns tweet JSON', async () => { - const shorthand = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, tweetId, '--json'], { + const shorthand = await runBird([...baseArgs, tweetId, '--json'], { timeoutMs: 45_000, }); expect(shorthand.exitCode).toBe(0); @@ -179,7 +169,7 @@ d('live CLI (Twitter/X)', () => { }); it('replies returns JSON array', async () => { - const replies = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'replies', tweetId, '--json'], { + const replies = await runBird([...baseArgs, 'replies', tweetId, '--json'], { timeoutMs: 45_000, }); expect(replies.exitCode).toBe(0); @@ -188,7 +178,7 @@ d('live CLI (Twitter/X)', () => { }); it('thread returns JSON array', async () => { - const thread = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'thread', tweetId, '--json'], { + const thread = await runBird([...baseArgs, 'thread', tweetId, '--json'], { timeoutMs: 45_000, }); expect(thread.exitCode).toBe(0); @@ -198,24 +188,18 @@ d('live CLI (Twitter/X)', () => { }); it('mentions returns JSON array', async () => { - const mentions = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'mentions', '-n', '10', '--json'], - { - timeoutMs: 45_000, - }, - ); + const mentions = await runBird([...baseArgs, 'mentions', '-n', '10', '--json'], { + timeoutMs: 45_000, + }); expect(mentions.exitCode).toBe(0); const mentionTweets = parseJson>(mentions.stdout); expect(Array.isArray(mentionTweets)).toBe(true); }); it('bookmarks returns JSON array', async () => { - const bookmarks = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'bookmarks', '-n', '10', '--json'], - { - timeoutMs: 45_000, - }, - ); + const bookmarks = await runBird([...baseArgs, 'bookmarks', '-n', '10', '--json'], { + timeoutMs: 45_000, + }); expect(bookmarks.exitCode).toBe(0); const bookmarkTweets = parseJson>(bookmarks.stdout); expect(Array.isArray(bookmarkTweets)).toBe(true); @@ -226,17 +210,16 @@ d('live CLI (Twitter/X)', () => { if (!folderId) { return; } - const bookmarks = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'bookmarks', '--folder-id', folderId, '-n', '10', '--json'], - { timeoutMs: 45_000 }, - ); + const bookmarks = await runBird([...baseArgs, 'bookmarks', '--folder-id', folderId, '-n', '10', '--json'], { + timeoutMs: 45_000, + }); expect(bookmarks.exitCode).toBe(0); const bookmarkTweets = parseJson>(bookmarks.stdout); expect(Array.isArray(bookmarkTweets)).toBe(true); }); it('likes returns JSON array', async () => { - const likes = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'likes', '-n', '10', '--json'], { + const likes = await runBird([...baseArgs, 'likes', '-n', '10', '--json'], { timeoutMs: 45_000, }); expect(likes.exitCode).toBe(0); @@ -245,24 +228,18 @@ d('live CLI (Twitter/X)', () => { }); it('following returns JSON array', async () => { - const following = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'following', '--user', userId, '-n', '10', '--json'], - { - timeoutMs: 45_000, - }, - ); + const following = await runBird([...baseArgs, 'following', '--user', userId, '-n', '10', '--json'], { + timeoutMs: 45_000, + }); expect(following.exitCode).toBe(0); const followingUsers = parseJson>(following.stdout); expect(Array.isArray(followingUsers)).toBe(true); }); it('followers returns JSON array', async () => { - const followers = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'followers', '--user', userId, '-n', '10', '--json'], - { - timeoutMs: 45_000, - }, - ); + const followers = await runBird([...baseArgs, 'followers', '--user', userId, '-n', '10', '--json'], { + timeoutMs: 45_000, + }); expect(followers.exitCode).toBe(0); const followerUsers = parseJson>(followers.stdout); expect(Array.isArray(followerUsers)).toBe(true); @@ -271,12 +248,9 @@ d('live CLI (Twitter/X)', () => { it('user-tweets returns JSON array', async () => { // Use a known active account for reliable testing (authenticated user may have no tweets) const testHandle = process.env.BIRD_LIVE_USER_TWEETS_HANDLE || 'X'; - const userTweets = await runBird( - [...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'user-tweets', testHandle, '-n', '5', '--json'], - { - timeoutMs: 45_000, - }, - ); + const userTweets = await runBird([...baseArgs, 'user-tweets', testHandle, '-n', '5', '--json'], { + timeoutMs: 45_000, + }); expect(userTweets.exitCode).toBe(0); const tweets = parseJson>(userTweets.stdout); expect(Array.isArray(tweets)).toBe(true); @@ -289,20 +263,7 @@ d('live CLI (Twitter/X)', () => { const testHandle = process.env.BIRD_LIVE_USER_TWEETS_PAGED_HANDLE ?? process.env.BIRD_LIVE_USER_TWEETS_HANDLE ?? 'X'; const userTweets = await runBird( - [ - ...baseArgs, - '--cookie-timeout', - cookieTimeoutArg, - 'user-tweets', - testHandle, - '-n', - '50', - '--max-pages', - '3', - '--delay', - '0', - '--json', - ], + [...baseArgs, 'user-tweets', testHandle, '-n', '50', '--max-pages', '3', '--delay', '0', '--json'], { timeoutMs: 45_000, }, @@ -315,7 +276,7 @@ d('live CLI (Twitter/X)', () => { }); it('query-ids returns JSON', async () => { - const queryIds = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'query-ids', '--json'], { + const queryIds = await runBird([...baseArgs, 'query-ids', '--json'], { timeoutMs: 60_000, }); expect(queryIds.exitCode).toBe(0); @@ -340,7 +301,7 @@ d('live CLI (Twitter/X)', () => { // Skip unless explicitly provided - long-form tweets may be deleted/unavailable return; } - const read = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'read', longformTweetId, '--json'], { + const read = await runBird([...baseArgs, 'read', longformTweetId, '--json'], { timeoutMs: 45_000, }); expect(read.exitCode).toBe(0); diff --git a/tests/twitter-client-coverage.api.test.ts b/tests/twitter-client-coverage.api.test.ts index 503b7f6..3846805 100644 --- a/tests/twitter-client-coverage.api.test.ts +++ b/tests/twitter-client-coverage.api.test.ts @@ -1,12 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -const validCookies = { - authToken: 'test_auth_token', - ct0: 'test_ct0_token', - cookieHeader: 'auth_token=test_auth_token; ct0=test_ct0_token', - source: 'test', -}; +const testRelayBaseUrl = 'https://relay.example'; type ResponseLike = { ok: boolean; @@ -53,7 +48,7 @@ describe('TwitterClient API coverage', () => { .mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'boom' })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.tweet('hi'); expect(result.success).toBe(false); @@ -72,7 +67,7 @@ describe('TwitterClient API coverage', () => { ); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.tweet('hi'); expect(result.success).toBe(false); @@ -91,7 +86,7 @@ describe('TwitterClient API coverage', () => { ); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.tweet('hi'); expect(result.success).toBe(false); @@ -106,7 +101,7 @@ describe('TwitterClient API coverage', () => { .mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.search('test'); expect(result.success).toBe(false); @@ -121,7 +116,7 @@ describe('TwitterClient API coverage', () => { ); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.search('test'); expect(result.success).toBe(false); @@ -132,7 +127,7 @@ describe('TwitterClient API coverage', () => { const mockFetch = vi.fn().mockRejectedValue(new Error('boom')); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.search('test'); expect(result.success).toBe(false); @@ -143,7 +138,7 @@ describe('TwitterClient API coverage', () => { const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.search('test'); expect(result.success).toBe(false); @@ -160,7 +155,7 @@ describe('TwitterClient API coverage', () => { .mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getBookmarksQueryIds = async () => ['test']; const result = await client.getBookmarks(1); @@ -177,7 +172,7 @@ describe('TwitterClient API coverage', () => { ); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getBookmarksQueryIds = async () => ['test']; const result = await client.getBookmarks(1); @@ -190,7 +185,7 @@ describe('TwitterClient API coverage', () => { const mockFetch = vi.fn().mockRejectedValue(new Error('boom')); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getBookmarksQueryIds = async () => ['test']; const result = await client.getBookmarks(1); @@ -200,7 +195,7 @@ describe('TwitterClient API coverage', () => { }); it('returns unknown error when no query ids are available', async () => { - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getBookmarksQueryIds = async () => []; @@ -214,7 +209,7 @@ describe('TwitterClient API coverage', () => { const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getBookmarks(1); expect(result.success).toBe(false); @@ -229,7 +224,7 @@ describe('TwitterClient API coverage', () => { .mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getFollowingQueryIds = async () => ['test']; @@ -247,7 +242,7 @@ describe('TwitterClient API coverage', () => { ); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getFollowersQueryIds = async () => ['test']; @@ -258,7 +253,7 @@ describe('TwitterClient API coverage', () => { }); it('returns unknown error when no query ids are available', async () => { - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getFollowingQueryIds = async () => []; @@ -272,7 +267,7 @@ describe('TwitterClient API coverage', () => { const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getFollowersQueryIds = async () => ['test']; @@ -294,7 +289,7 @@ describe('TwitterClient API coverage', () => { .mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getCurrentUser = stubCurrentUser; clientPrivate.getLikesQueryIds = async () => ['test']; @@ -313,7 +308,7 @@ describe('TwitterClient API coverage', () => { ); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getCurrentUser = stubCurrentUser; clientPrivate.getLikesQueryIds = async () => ['test']; @@ -328,7 +323,7 @@ describe('TwitterClient API coverage', () => { const mockFetch = vi.fn().mockRejectedValue(new Error('boom')); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getCurrentUser = stubCurrentUser; clientPrivate.getLikesQueryIds = async () => ['test']; @@ -340,7 +335,7 @@ describe('TwitterClient API coverage', () => { }); it('returns unknown error when no query ids are available', async () => { - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getCurrentUser = stubCurrentUser; clientPrivate.getLikesQueryIds = async () => []; @@ -355,7 +350,7 @@ describe('TwitterClient API coverage', () => { const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getCurrentUser = stubCurrentUser; clientPrivate.getLikesQueryIds = async () => ['test']; @@ -375,7 +370,7 @@ describe('TwitterClient API coverage', () => { .mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getBookmarkFolderQueryIds = async () => ['test']; const result = await client.getBookmarkFolderTimeline('123', 1); @@ -392,7 +387,7 @@ describe('TwitterClient API coverage', () => { ); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getBookmarkFolderQueryIds = async () => ['test']; const result = await client.getBookmarkFolderTimeline('123', 1); @@ -405,7 +400,7 @@ describe('TwitterClient API coverage', () => { const mockFetch = vi.fn().mockRejectedValue(new Error('boom')); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getBookmarkFolderQueryIds = async () => ['test']; const result = await client.getBookmarkFolderTimeline('123', 1); @@ -415,7 +410,7 @@ describe('TwitterClient API coverage', () => { }); it('returns unknown error when no query ids are available', async () => { - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientApiPrivate; clientPrivate.getBookmarkFolderQueryIds = async () => []; @@ -429,7 +424,7 @@ describe('TwitterClient API coverage', () => { const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getBookmarkFolderTimeline('123', 1); expect(result.success).toBe(false); diff --git a/tests/twitter-client-coverage.core.test.ts b/tests/twitter-client-coverage.core.test.ts index 63326cf..6c7a71b 100644 --- a/tests/twitter-client-coverage.core.test.ts +++ b/tests/twitter-client-coverage.core.test.ts @@ -2,12 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { runtimeQueryIds } from '../src/lib/runtime-query-ids.js'; import { TwitterClient } from '../src/lib/twitter-client.js'; -const validCookies = { - authToken: 'test_auth_token', - ct0: 'test_ct0_token', - cookieHeader: 'auth_token=test_auth_token; ct0=test_ct0_token', - source: 'test', -}; +const testRelayBaseUrl = 'https://relay.example'; type ResponseLike = { ok: boolean; @@ -46,7 +41,7 @@ describe('TwitterClient core coverage', () => { }); it('refreshQueryIds calls runtime refresh outside test env', async () => { - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const refreshSpy = vi.spyOn(runtimeQueryIds, 'refresh').mockResolvedValue(null); process.env.NODE_ENV = 'production'; @@ -63,11 +58,15 @@ describe('TwitterClient core coverage', () => { }); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies, timeoutMs: 5 }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl, timeoutMs: 5 }); const clientPrivate = client as unknown as TwitterClientPrivate; - await clientPrivate.fetchWithTimeout('https://example.com', { method: 'GET' }); + await clientPrivate.fetchWithTimeout('https://x.com/i/api/test', { method: 'GET' }); expect(mockFetch).toHaveBeenCalledTimes(1); + expect(mockFetch).toHaveBeenCalledWith( + 'https://relay.example/i/api/test', + expect.objectContaining({ method: 'GET' }), + ); }); it('returns a not found error when tweet data is missing', async () => { @@ -102,7 +101,7 @@ describe('TwitterClient core coverage', () => { ); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getTweet('123'); expect(result.success).toBe(false); @@ -110,7 +109,7 @@ describe('TwitterClient core coverage', () => { }); it('adds client user id header after ensureClientUserId', async () => { - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); process.env.NODE_ENV = 'production'; vi.spyOn(client, 'getCurrentUser').mockResolvedValue({ @@ -130,7 +129,7 @@ describe('TwitterClient core coverage', () => { const mockFetch = vi.fn().mockResolvedValueOnce(makeResponse({ ok: false, status: 500 })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; const result = await clientPrivate.fetchUserArticlePlainText('user', 'tweet'); @@ -141,7 +140,7 @@ describe('TwitterClient core coverage', () => { const mockFetch = vi.fn().mockRejectedValueOnce(new Error('boom')); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; const result = await clientPrivate.fetchUserArticlePlainText('user', 'tweet'); @@ -160,7 +159,7 @@ describe('TwitterClient core coverage', () => { ); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; const result = await clientPrivate.fetchUserArticlePlainText('user', 'tweet'); @@ -177,7 +176,7 @@ describe('TwitterClient core coverage', () => { ); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; const result = await clientPrivate.fetchTweetDetail('1'); @@ -210,7 +209,7 @@ describe('TwitterClient core coverage', () => { ); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; const result = await clientPrivate.fetchTweetDetail('1'); @@ -260,7 +259,7 @@ describe('TwitterClient core coverage', () => { ); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; const result = await clientPrivate.fetchTweetDetail('2'); @@ -295,7 +294,7 @@ describe('TwitterClient core coverage', () => { ); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; const result = await clientPrivate.fetchTweetDetail('1'); @@ -306,7 +305,7 @@ describe('TwitterClient core coverage', () => { const mockFetch = vi.fn().mockRejectedValueOnce(new Error('boom')); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; const result = await clientPrivate.fetchTweetDetail('1'); @@ -320,7 +319,7 @@ describe('TwitterClient core coverage', () => { const mockFetch = vi.fn().mockRejectedValueOnce(new Error('boom')); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; const result = await clientPrivate.postStatusUpdate({ text: 'hello' }); diff --git a/tests/twitter-client-coverage.news.test.ts b/tests/twitter-client-coverage.news.test.ts index a144480..8e8f677 100644 --- a/tests/twitter-client-coverage.news.test.ts +++ b/tests/twitter-client-coverage.news.test.ts @@ -1,12 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -const validCookies = { - authToken: 'test_auth_token', - ct0: 'test_ct0_token', - cookieHeader: 'auth_token=test_auth_token; ct0=test_ct0_token', - source: 'test', -}; +const testRelayBaseUrl = 'https://relay.example'; type ResponseLike = { ok: boolean; @@ -99,7 +94,7 @@ describe('TwitterClient news API coverage', () => { global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getNews(1); expect(result.success).toBe(true); @@ -125,7 +120,7 @@ describe('TwitterClient news API coverage', () => { global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getNews(1, { includeRaw: true }); expect(result.success).toBe(true); @@ -154,7 +149,7 @@ describe('TwitterClient news API coverage', () => { global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getNews(10, { aiOnly: true }); expect(result.success).toBe(true); @@ -180,7 +175,7 @@ describe('TwitterClient news API coverage', () => { global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getNews(1, { tabs: ['news'] }); expect(result.success).toBe(true); @@ -195,7 +190,7 @@ describe('TwitterClient news API coverage', () => { global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getNews(10); expect(result.success).toBe(false); @@ -214,7 +209,7 @@ describe('TwitterClient news API coverage', () => { global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getNews(10); expect(result.success).toBe(false); @@ -226,7 +221,7 @@ describe('TwitterClient news API coverage', () => { global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getNews(10); expect(result.success).toBe(false); @@ -262,7 +257,7 @@ describe('TwitterClient news API coverage', () => { global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getNews(10); expect(result.success).toBe(true); @@ -296,7 +291,7 @@ describe('TwitterClient news API coverage', () => { global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getNews(2); expect(result.success).toBe(true); @@ -326,7 +321,7 @@ describe('TwitterClient news API coverage', () => { global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getNews(1); expect(result.success).toBe(true); @@ -360,7 +355,7 @@ describe('TwitterClient news API coverage', () => { global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getNews(2); expect(result.success).toBe(true); @@ -387,7 +382,7 @@ describe('TwitterClient news API coverage', () => { global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getNews(1); expect(result.success).toBe(true); diff --git a/tests/twitter-client-coverage.upload.test.ts b/tests/twitter-client-coverage.upload.test.ts index 10091e5..2166bf1 100644 --- a/tests/twitter-client-coverage.upload.test.ts +++ b/tests/twitter-client-coverage.upload.test.ts @@ -2,12 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; import { extractArticleText } from '../src/lib/twitter-client-utils.js'; -const validCookies = { - authToken: 'test_auth_token', - ct0: 'test_ct0_token', - cookieHeader: 'auth_token=test_auth_token; ct0=test_ct0_token', - source: 'test', -}; +const testRelayBaseUrl = 'https://relay.example'; type ResponseLike = { ok: boolean; @@ -40,7 +35,7 @@ describe('TwitterClient upload coverage', () => { describe('uploadMedia error paths', () => { it('rejects unsupported media types', async () => { global.fetch = vi.fn() as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.uploadMedia({ data: new Uint8Array([1, 2, 3]), mimeType: 'application/pdf' }); expect(result.success).toBe(false); @@ -53,7 +48,7 @@ describe('TwitterClient upload coverage', () => { .mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'nope' })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png' }); expect(result.success).toBe(false); @@ -67,7 +62,7 @@ describe('TwitterClient upload coverage', () => { .mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'nope' })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png' }); expect(result.success).toBe(false); @@ -82,7 +77,7 @@ describe('TwitterClient upload coverage', () => { .mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'nope' })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png' }); expect(result.success).toBe(false); @@ -101,7 +96,7 @@ describe('TwitterClient upload coverage', () => { ); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'video/mp4' }); expect(result.success).toBe(false); @@ -121,7 +116,7 @@ describe('TwitterClient upload coverage', () => { .mockResolvedValueOnce(makeResponse({ ok: false, status: 503, text: async () => 'down' })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientUploadPrivate; clientPrivate.sleep = vi.fn().mockResolvedValue(undefined); @@ -149,7 +144,7 @@ describe('TwitterClient upload coverage', () => { .mockResolvedValueOnce(makeResponse({ json: async () => ({ processing_info: { state: 'succeeded' } }) })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientUploadPrivate; clientPrivate.sleep = vi.fn().mockResolvedValue(undefined); @@ -167,7 +162,7 @@ describe('TwitterClient upload coverage', () => { .mockResolvedValueOnce(makeResponse({ ok: false, status: 400, text: async () => 'bad' })); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png', alt: 'alt' }); expect(result.success).toBe(false); @@ -178,7 +173,7 @@ describe('TwitterClient upload coverage', () => { const mockFetch = vi.fn().mockRejectedValueOnce(new Error('boom')); global.fetch = mockFetch as unknown as typeof fetch; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png' }); expect(result.success).toBe(false); diff --git a/tests/twitter-client-fixtures.ts b/tests/twitter-client-fixtures.ts index 953547e..736f4e6 100644 --- a/tests/twitter-client-fixtures.ts +++ b/tests/twitter-client-fixtures.ts @@ -1,11 +1,6 @@ import type { TwitterClient } from '../src/lib/twitter-client.js'; -export const validCookies = { - authToken: 'test_auth_token', - ct0: 'test_ct0_token', - cookieHeader: 'auth_token=test_auth_token; ct0=test_ct0_token', - source: 'test', -}; +export const testRelayBaseUrl = 'https://relay.example'; export type TwitterClientPrivate = TwitterClient & { getCurrentUser: () => Promise<{ diff --git a/tests/twitter-client.constructor-tweet-reply.test.ts b/tests/twitter-client.constructor-tweet-reply.test.ts index 36e90a1..ba2175d 100644 --- a/tests/twitter-client.constructor-tweet-reply.test.ts +++ b/tests/twitter-client.constructor-tweet-reply.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { validCookies } from './twitter-client-fixtures.js'; +import { testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -10,26 +10,22 @@ afterEach(() => { }); describe('TwitterClient constructor', () => { - it('should throw if authToken is missing', () => { - expect( - () => - new TwitterClient({ - cookies: { authToken: null, ct0: 'test', cookieHeader: null, source: null }, - }), - ).toThrow('Both authToken and ct0 cookies are required'); + it('throws if relay base URL is missing', () => { + const originalRelayBaseUrl = process.env.TWITTER_RELAY_BASE_URL; + delete process.env.TWITTER_RELAY_BASE_URL; + try { + expect(() => new TwitterClient({})).toThrow('TWITTER_RELAY_BASE_URL is required'); + } finally { + if (originalRelayBaseUrl === undefined) { + delete process.env.TWITTER_RELAY_BASE_URL; + } else { + process.env.TWITTER_RELAY_BASE_URL = originalRelayBaseUrl; + } + } }); - it('should throw if ct0 is missing', () => { - expect( - () => - new TwitterClient({ - cookies: { authToken: 'test', ct0: null, cookieHeader: null, source: null }, - }), - ).toThrow('Both authToken and ct0 cookies are required'); - }); - - it('should create client with valid cookies', () => { - const client = new TwitterClient({ cookies: validCookies }); + it('creates client with relay base URL', () => { + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); expect(client).toBeInstanceOf(TwitterClient); }); }); @@ -61,7 +57,7 @@ describe('TwitterClient tweet', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.tweet('Hello world!'); expect(result.success).toBe(true); @@ -69,8 +65,12 @@ describe('TwitterClient tweet', () => { expect(mockFetch).toHaveBeenCalledTimes(1); const [url, options] = mockFetch.mock.calls[0]; - expect(url).toContain('CreateTweet'); + expect(String(url)).toContain(`${testRelayBaseUrl}/i/api/graphql/`); + expect(String(url)).toContain('CreateTweet'); expect(options.method).toBe('POST'); + expect(options.headers).not.toHaveProperty('cookie'); + expect(options.headers).not.toHaveProperty('authorization'); + expect(options.headers).not.toHaveProperty('x-csrf-token'); const body = JSON.parse(options.body); expect(body.variables.tweet_text).toBe('Hello world!'); @@ -94,7 +94,7 @@ describe('TwitterClient tweet', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.tweet('Hello world!', ['111', '222']); expect(result.success).toBe(true); @@ -136,7 +136,7 @@ describe('TwitterClient tweet', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.tweet('Hello world!'); expect(result.success).toBe(true); @@ -146,7 +146,7 @@ describe('TwitterClient tweet', () => { const [firstUrl] = mockFetch.mock.calls[0]; const [thirdUrl] = mockFetch.mock.calls[2]; expect(String(firstUrl)).toContain('/CreateTweet'); - expect(String(thirdUrl)).toBe('https://x.com/i/api/graphql'); + expect(String(thirdUrl)).toBe(`${testRelayBaseUrl}/i/api/graphql`); }); it('should handle API errors', async () => { @@ -157,7 +157,7 @@ describe('TwitterClient tweet', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.tweet('Test'); expect(result.success).toBe(false); @@ -184,7 +184,7 @@ describe('TwitterClient tweet', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.tweet('Hello world!'); expect(result.success).toBe(true); @@ -212,7 +212,7 @@ describe('TwitterClient tweet', () => { text: async () => 'Forbidden', }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.tweet('Hello world!'); expect(result.success).toBe(false); @@ -242,7 +242,7 @@ describe('TwitterClient tweet', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.tweet('Hello world!'); expect(result.success).toBe(false); @@ -268,7 +268,7 @@ describe('TwitterClient tweet', () => { json: async () => ({}), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.tweet('Hello world!'); expect(result.success).toBe(false); @@ -283,7 +283,7 @@ describe('TwitterClient tweet', () => { text: async () => 'Forbidden', }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.tweet('Test'); expect(result.success).toBe(false); @@ -293,7 +293,7 @@ describe('TwitterClient tweet', () => { it('should handle network errors', async () => { mockFetch.mockRejectedValueOnce(new Error('Network error')); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.tweet('Test'); expect(result.success).toBe(false); @@ -316,7 +316,7 @@ describe('TwitterClient tweet', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.tweet('Hello world!'); expect(result.success).toBe(false); @@ -348,7 +348,7 @@ describe('TwitterClient reply', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.reply('This is a reply', '1234567890'); expect(result.success).toBe(true); @@ -382,7 +382,7 @@ describe('TwitterClient reply', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.reply('This is a reply', '1234567890', ['111', '222']); expect(result.success).toBe(true); diff --git a/tests/twitter-client.conversations.test.ts b/tests/twitter-client.conversations.test.ts index 12f47e2..6128009 100644 --- a/tests/twitter-client.conversations.test.ts +++ b/tests/twitter-client.conversations.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { validCookies } from './twitter-client-fixtures.js'; +import { testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -78,7 +78,7 @@ describe('TwitterClient conversation helpers', () => { json: async () => makeConversationPayload(), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getReplies('1'); expect(result.success).toBe(true); @@ -102,7 +102,7 @@ describe('TwitterClient conversation helpers', () => { json: async () => payload, }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getThread('2'); expect(result.success).toBe(true); @@ -147,7 +147,7 @@ describe('TwitterClient conversation helpers', () => { json: async () => payload, }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getThread('1'); expect(result.success).toBe(true); @@ -161,7 +161,7 @@ describe('TwitterClient conversation helpers', () => { text: async () => 'oops', }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getThread('1'); expect(result.success).toBe(false); diff --git a/tests/twitter-client.current-user.test.ts b/tests/twitter-client.current-user.test.ts index ebd3bd8..47de3f8 100644 --- a/tests/twitter-client.current-user.test.ts +++ b/tests/twitter-client.current-user.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { validCookies } from './twitter-client-fixtures.js'; +import { testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -28,7 +28,7 @@ describe('TwitterClient getCurrentUser', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getCurrentUser(); expect(result.success).toBe(true); @@ -44,7 +44,7 @@ describe('TwitterClient getCurrentUser', () => { text: async () => '{"language":"en"}', })); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getCurrentUser(); expect(result.success).toBe(false); @@ -58,32 +58,26 @@ describe('TwitterClient getCurrentUser', () => { text: async () => 'Unauthorized', })); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getCurrentUser(); expect(result.success).toBe(false); expect(result.error).toContain('HTTP 401'); }); - it('uses HTML fallback when API endpoints 404', async () => { + it('returns error when API endpoints 404', async () => { mockFetch .mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' }) .mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' }) .mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' }) - .mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' }) - .mockResolvedValueOnce({ - ok: true, - status: 200, - text: async () => '"screen_name":"fallback","user_id":"999"', - }); + .mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getCurrentUser(); - expect(result.success).toBe(true); - expect(result.user?.username).toBe('fallback'); - expect(result.user?.id).toBe('999'); - expect(mockFetch).toHaveBeenCalledTimes(5); + expect(result.success).toBe(false); + expect(result.error).toContain('HTTP 404'); + expect(mockFetch).toHaveBeenCalledTimes(4); }); it('skips an endpoint when JSON parsing fails', async () => { @@ -105,7 +99,7 @@ describe('TwitterClient getCurrentUser', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getCurrentUser(); expect(result.success).toBe(true); @@ -113,24 +107,26 @@ describe('TwitterClient getCurrentUser', () => { expect(mockFetch).toHaveBeenCalledTimes(2); }); - it('continues on fetch errors and still succeeds via HTML fallback', async () => { + it('continues on fetch errors and still succeeds via later API endpoint', async () => { mockFetch .mockRejectedValueOnce(new Error('boom')) .mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' }) - .mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' }) - .mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' }) - .mockRejectedValueOnce(new Error('settings boom')) .mockResolvedValueOnce({ ok: true, status: 200, - text: async () => '"screen_name":"fallback","user_id":"999"', + json: async () => ({ + user_id: '999', + screen_name: 'fallback', + name: 'Fallback User', + }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getCurrentUser(); expect(result.success).toBe(true); expect(result.user?.username).toBe('fallback'); expect(result.user?.id).toBe('999'); + expect(mockFetch).toHaveBeenCalledTimes(3); }); }); diff --git a/tests/twitter-client.following-pagination.test.ts b/tests/twitter-client.following-pagination.test.ts index ef076f0..9725a9a 100644 --- a/tests/twitter-client.following-pagination.test.ts +++ b/tests/twitter-client.following-pagination.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; import type { TwitterClientPrivate } from './twitter-client-fixtures.js'; -import { validCookies } from './twitter-client-fixtures.js'; +import { testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -69,7 +69,7 @@ describe('TwitterClient following pagination', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getFollowingQueryIds = async () => ['q1']; clientPrivate.getFollowingViaRest = vi.fn(); @@ -109,7 +109,7 @@ describe('TwitterClient following pagination', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getFollowingQueryIds = async () => ['q1']; clientPrivate.getFollowingViaRest = vi.fn(); @@ -147,7 +147,7 @@ describe('TwitterClient following pagination', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getFollowingQueryIds = async () => ['q1']; clientPrivate.getFollowingViaRest = vi.fn(); @@ -165,7 +165,7 @@ describe('TwitterClient following pagination', () => { text: async () => 'boom', }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getFollowingQueryIds = async () => ['q1']; clientPrivate.getFollowingViaRest = vi.fn().mockResolvedValue({ success: false, error: 'rest fail' }); diff --git a/tests/twitter-client.following.test.ts b/tests/twitter-client.following.test.ts index bc07f6a..9e52686 100644 --- a/tests/twitter-client.following.test.ts +++ b/tests/twitter-client.following.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { validCookies } from './twitter-client-fixtures.js'; +import { testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -84,7 +84,7 @@ describe('TwitterClient following/followers', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClient & { getFollowingQueryIds: () => Promise }; clientPrivate.getFollowingQueryIds = async () => ['test']; @@ -138,7 +138,7 @@ describe('TwitterClient following/followers', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClient & { getFollowersQueryIds: () => Promise }; clientPrivate.getFollowersQueryIds = async () => ['test']; @@ -183,7 +183,7 @@ describe('TwitterClient following/followers', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClient & { getFollowingQueryIds: () => Promise; refreshQueryIds: () => Promise; @@ -225,7 +225,7 @@ describe('TwitterClient following/followers', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClient & { getFollowingQueryIds: () => Promise }; clientPrivate.getFollowingQueryIds = async () => ['test']; @@ -265,7 +265,7 @@ describe('TwitterClient following/followers', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClient & { getFollowersQueryIds: () => Promise }; clientPrivate.getFollowersQueryIds = async () => ['test']; @@ -320,7 +320,7 @@ describe('TwitterClient following/followers', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClient & { getFollowersQueryIds: () => Promise }; clientPrivate.getFollowersQueryIds = async () => ['test']; @@ -368,7 +368,7 @@ describe('TwitterClient following/followers', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClient & { getFollowersQueryIds: () => Promise }; clientPrivate.getFollowersQueryIds = async () => ['test']; diff --git a/tests/twitter-client.get-tweet.test.ts b/tests/twitter-client.get-tweet.test.ts index 5babe2f..5303145 100644 --- a/tests/twitter-client.get-tweet.test.ts +++ b/tests/twitter-client.get-tweet.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; import { mapTweetResult } from '../src/lib/twitter-client-utils.js'; -import { validCookies } from './twitter-client-fixtures.js'; +import { testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -49,7 +49,7 @@ describe('TwitterClient getTweet', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getTweet('12345'); expect(result.success).toBe(true); @@ -103,7 +103,7 @@ describe('TwitterClient getTweet', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getTweet('6789'); expect(result.success).toBe(true); @@ -118,7 +118,7 @@ describe('TwitterClient getTweet', () => { text: async () => 'Not Found', }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getTweet('missing'); expect(result.success).toBe(false); @@ -168,7 +168,7 @@ describe('TwitterClient getTweet', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getTweet('article123'); expect(result.success).toBe(true); @@ -252,7 +252,7 @@ describe('TwitterClient getTweet', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getTweet('article123'); expect(result.success).toBe(true); @@ -295,7 +295,7 @@ describe('TwitterClient getTweet', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getTweet('note123'); expect(result.success).toBe(true); @@ -326,7 +326,7 @@ describe('TwitterClient getTweet', () => { .mockResolvedValueOnce({ ok: false, status: 404, text: async () => '' }) .mockResolvedValueOnce({ ok: true, status: 200, json: async () => payload }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getTweet('1'); expect(result.success).toBe(true); @@ -366,7 +366,7 @@ describe('TwitterClient quoted tweets', () => { const root = makeTweetResult('1', 'root'); root.quoted_status_result = { result: quoted }; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const mapped = mapTweetResult(root, (client as { quoteDepth: number }).quoteDepth); expect(mapped?.quotedTweet?.id).toBe('2'); @@ -378,7 +378,7 @@ describe('TwitterClient quoted tweets', () => { const root = makeTweetResult('1', 'root'); root.quoted_status_result = { result: quoted }; - const client = new TwitterClient({ cookies: validCookies, quoteDepth: 0 }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl, quoteDepth: 0 }); const mapped = mapTweetResult(root, (client as { quoteDepth: number }).quoteDepth); expect(mapped?.quotedTweet).toBeUndefined(); @@ -391,7 +391,7 @@ describe('TwitterClient quoted tweets', () => { const root = makeTweetResult('1', 'root'); root.quoted_status_result = { result: quoted1 }; - const client = new TwitterClient({ cookies: validCookies, quoteDepth: 2 }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl, quoteDepth: 2 }); const mapped = mapTweetResult(root, (client as { quoteDepth: number }).quoteDepth); expect(mapped?.quotedTweet?.id).toBe('2'); @@ -409,7 +409,7 @@ describe('TwitterClient quoted tweets', () => { }, }; - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const mapped = mapTweetResult(root, (client as { quoteDepth: number }).quoteDepth); expect(mapped?.quotedTweet?.id).toBe('2'); diff --git a/tests/twitter-client.home-timeline.test.ts b/tests/twitter-client.home-timeline.test.ts index 607e82a..c20e439 100644 --- a/tests/twitter-client.home-timeline.test.ts +++ b/tests/twitter-client.home-timeline.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { validCookies } from './twitter-client-fixtures.js'; +import { testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -72,7 +72,7 @@ describe('TwitterClient home timeline', () => { json: async () => makeHomeTimelineResponse('123456', 'Hello from For You feed!', 'testuser'), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getHomeTimeline(1); expect(result.success).toBe(true); @@ -89,7 +89,7 @@ describe('TwitterClient home timeline', () => { text: async () => 'Unauthorized', }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getHomeTimeline(1); expect(result.success).toBe(false); @@ -104,7 +104,7 @@ describe('TwitterClient home timeline', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getHomeTimeline(1); expect(result.success).toBe(false); @@ -119,7 +119,7 @@ describe('TwitterClient home timeline', () => { json: async () => makeHomeTimelineResponse('789012', 'Hello from Following feed!', 'chronouser'), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getHomeLatestTimeline(1); expect(result.success).toBe(true); @@ -136,7 +136,7 @@ describe('TwitterClient home timeline', () => { text: async () => 'Forbidden', }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getHomeLatestTimeline(1); expect(result.success).toBe(false); @@ -241,7 +241,7 @@ describe('TwitterClient home timeline', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getHomeTimeline(2); expect(result.success).toBe(true); @@ -333,7 +333,7 @@ describe('TwitterClient home timeline', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getHomeTimeline(5); expect(result.success).toBe(true); diff --git a/tests/twitter-client.json-full.test.ts b/tests/twitter-client.json-full.test.ts index 8cbb69a..23f6d1f 100644 --- a/tests/twitter-client.json-full.test.ts +++ b/tests/twitter-client.json-full.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; import { mapTweetResult, parseTweetsFromInstructions } from '../src/lib/twitter-client-utils.js'; -import { validCookies } from './twitter-client-fixtures.js'; +import { testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -207,7 +207,7 @@ describe('TwitterClient getTweet with includeRaw option', () => { json: async () => mockTweetResponse, }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getTweet('12345'); expect(result.success).toBe(true); @@ -220,7 +220,7 @@ describe('TwitterClient getTweet with includeRaw option', () => { json: async () => mockTweetResponse, }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getTweet('12345', { includeRaw: true }); expect(result.success).toBe(true); @@ -280,7 +280,7 @@ describe('TwitterClient getReplies with includeRaw option', () => { json: async () => mockRepliesResponse, }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getReplies('12345', { includeRaw: true }); expect(result.success).toBe(true); @@ -340,7 +340,7 @@ describe('TwitterClient getThread with includeRaw option', () => { json: async () => mockThreadResponse, }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getThread('12345', { includeRaw: true }); expect(result.success).toBe(true); @@ -402,7 +402,7 @@ describe('TwitterClient search with includeRaw option', () => { json: async () => mockSearchResponse, }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.search('test query', 10, { includeRaw: true }); expect(result.success).toBe(true); @@ -417,7 +417,7 @@ describe('TwitterClient search with includeRaw option', () => { json: async () => mockSearchResponse, }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.search('test query', 10); expect(result.success).toBe(true); @@ -462,7 +462,7 @@ describe('--json-full flag behavior (without --json)', () => { json: async () => mockTweetResponse, }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); // Only passing includeRaw: true, simulating --json-full without --json const result = await client.getTweet('12345', { includeRaw: true }); diff --git a/tests/twitter-client.json-full.timelines.test.ts b/tests/twitter-client.json-full.timelines.test.ts index 4b10b62..8bbb43d 100644 --- a/tests/twitter-client.json-full.timelines.test.ts +++ b/tests/twitter-client.json-full.timelines.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { type TwitterClientPrivate, validCookies } from './twitter-client-fixtures.js'; +import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -60,7 +60,7 @@ describe('TwitterClient timelines includeRaw', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getBookmarks(1, { includeRaw: true }); expect(result.success).toBe(true); @@ -112,7 +112,7 @@ describe('TwitterClient timelines includeRaw', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getBookmarkFolderTimeline('123', 1, { includeRaw: true }); expect(result.success).toBe(true); @@ -168,7 +168,7 @@ describe('TwitterClient timelines includeRaw', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, @@ -229,7 +229,7 @@ describe('TwitterClient timelines includeRaw', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getListTimelineQueryIds = async () => ['test']; diff --git a/tests/twitter-client.likes.test.ts b/tests/twitter-client.likes.test.ts index 06c066c..b2889f5 100644 --- a/tests/twitter-client.likes.test.ts +++ b/tests/twitter-client.likes.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { type TwitterClientPrivate, validCookies } from './twitter-client-fixtures.js'; +import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -67,7 +67,7 @@ describe('TwitterClient likes', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, @@ -198,7 +198,7 @@ describe('TwitterClient likes', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, @@ -275,7 +275,7 @@ describe('TwitterClient likes', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, @@ -292,7 +292,7 @@ describe('TwitterClient likes', () => { }); it('returns an error when current user is unavailable', async () => { - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: false, error: 'no user' }); diff --git a/tests/twitter-client.lists.memberships.test.ts b/tests/twitter-client.lists.memberships.test.ts index 136782a..b302f6d 100644 --- a/tests/twitter-client.lists.memberships.test.ts +++ b/tests/twitter-client.lists.memberships.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { type TwitterClientPrivate, validCookies } from './twitter-client-fixtures.js'; +import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -61,7 +61,7 @@ describe('TwitterClient lists memberships', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, @@ -118,7 +118,7 @@ describe('TwitterClient lists memberships', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, diff --git a/tests/twitter-client.lists.owned.errors.test.ts b/tests/twitter-client.lists.owned.errors.test.ts index 9e1cd6c..afbbb32 100644 --- a/tests/twitter-client.lists.owned.errors.test.ts +++ b/tests/twitter-client.lists.owned.errors.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { type TwitterClientPrivate, validCookies } from './twitter-client-fixtures.js'; +import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -27,7 +27,7 @@ describe('TwitterClient lists owned errors', () => { text: async () => 'Internal Server Error', }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, @@ -42,7 +42,7 @@ describe('TwitterClient lists owned errors', () => { }); it('returns error when getCurrentUser fails', async () => { - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: false, @@ -65,7 +65,7 @@ describe('TwitterClient lists owned errors', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, @@ -88,7 +88,7 @@ describe('TwitterClient lists owned errors', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, @@ -143,7 +143,7 @@ describe('TwitterClient lists owned errors', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, @@ -223,7 +223,7 @@ describe('TwitterClient lists owned errors', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, @@ -274,7 +274,7 @@ describe('TwitterClient lists owned errors', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, diff --git a/tests/twitter-client.lists.owned.test.ts b/tests/twitter-client.lists.owned.test.ts index 865fe9d..6a7ea21 100644 --- a/tests/twitter-client.lists.owned.test.ts +++ b/tests/twitter-client.lists.owned.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { type TwitterClientPrivate, validCookies } from './twitter-client-fixtures.js'; +import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -65,7 +65,7 @@ describe('TwitterClient lists owned', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, @@ -105,7 +105,7 @@ describe('TwitterClient lists owned', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, @@ -160,7 +160,7 @@ describe('TwitterClient lists owned', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, @@ -209,7 +209,7 @@ describe('TwitterClient lists owned', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, @@ -258,7 +258,7 @@ describe('TwitterClient lists owned', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, @@ -291,7 +291,7 @@ describe('TwitterClient lists owned', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getCurrentUser = async () => ({ success: true, diff --git a/tests/twitter-client.lists.pagination.edges.test.ts b/tests/twitter-client.lists.pagination.edges.test.ts index b2aa1b6..9124e15 100644 --- a/tests/twitter-client.lists.pagination.edges.test.ts +++ b/tests/twitter-client.lists.pagination.edges.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { type TwitterClientPrivate, validCookies } from './twitter-client-fixtures.js'; +import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -68,7 +68,7 @@ describe('TwitterClient lists pagination (continued)', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getListTimelineQueryIds = async () => ['test']; @@ -213,7 +213,7 @@ describe('TwitterClient lists pagination (continued)', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getListTimelineQueryIds = async () => ['test']; @@ -334,7 +334,7 @@ describe('TwitterClient lists pagination (continued)', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getListTimelineQueryIds = async () => ['test']; @@ -449,7 +449,7 @@ describe('TwitterClient lists pagination (continued)', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getListTimelineQueryIds = async () => ['test']; diff --git a/tests/twitter-client.lists.pagination.test.ts b/tests/twitter-client.lists.pagination.test.ts index 347243f..33224f5 100644 --- a/tests/twitter-client.lists.pagination.test.ts +++ b/tests/twitter-client.lists.pagination.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { type TwitterClientPrivate, validCookies } from './twitter-client-fixtures.js'; +import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -123,7 +123,7 @@ describe('TwitterClient lists pagination', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getListTimelineQueryIds = async () => ['test']; @@ -250,7 +250,7 @@ describe('TwitterClient lists pagination', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getListTimelineQueryIds = async () => ['test']; diff --git a/tests/twitter-client.lists.timeline.test.ts b/tests/twitter-client.lists.timeline.test.ts index be84842..f393893 100644 --- a/tests/twitter-client.lists.timeline.test.ts +++ b/tests/twitter-client.lists.timeline.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { type TwitterClientPrivate, validCookies } from './twitter-client-fixtures.js'; +import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -69,7 +69,7 @@ describe('TwitterClient lists timeline', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getListTimelineQueryIds = async () => ['test']; @@ -98,7 +98,7 @@ describe('TwitterClient lists timeline', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getListTimelineQueryIds = async () => ['test']; @@ -115,7 +115,7 @@ describe('TwitterClient lists timeline', () => { text: async () => 'Forbidden', }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getListTimelineQueryIds = async () => ['test']; @@ -134,7 +134,7 @@ describe('TwitterClient lists timeline', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getListTimelineQueryIds = async () => ['test']; @@ -199,7 +199,7 @@ describe('TwitterClient lists timeline', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as unknown as TwitterClientPrivate; clientPrivate.getListTimelineQueryIds = async () => ['test']; clientPrivate.refreshQueryIds = async () => {}; diff --git a/tests/twitter-client.media.test.ts b/tests/twitter-client.media.test.ts index 60a2dd5..bd2acde 100644 --- a/tests/twitter-client.media.test.ts +++ b/tests/twitter-client.media.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { validCookies } from './twitter-client-fixtures.js'; +import { testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -34,7 +34,7 @@ describe('TwitterClient uploadMedia', () => { ok: true, }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const data = new Uint8Array([1, 2, 3, 4]); const result = await client.uploadMedia({ data, mimeType: 'image/png', alt: 'alt text' }); @@ -43,7 +43,7 @@ describe('TwitterClient uploadMedia', () => { expect(mockFetch).toHaveBeenCalledTimes(4); const [initUrl, initOptions] = mockFetch.mock.calls[0]; - expect(String(initUrl)).toContain('upload.twitter.com'); + expect(String(initUrl)).toBe(`${testRelayBaseUrl}/i/media/upload.json`); expect(initOptions.method).toBe('POST'); expect(initOptions.body).toBeInstanceOf(URLSearchParams); expect((initOptions.body as URLSearchParams).get('command')).toBe('INIT'); @@ -87,7 +87,7 @@ describe('TwitterClient uploadMedia', () => { json: async () => ({ processing_info: { state: 'succeeded' } }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const data = new Uint8Array([1, 2, 3, 4, 5]); const result = await client.uploadMedia({ data, mimeType: 'video/mp4', alt: 'ignored' }); diff --git a/tests/twitter-client.pagination.test.ts b/tests/twitter-client.pagination.test.ts index 9595dd5..18ba98b 100644 --- a/tests/twitter-client.pagination.test.ts +++ b/tests/twitter-client.pagination.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { validCookies } from './twitter-client-fixtures.js'; +import { testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -75,7 +75,7 @@ describe('TwitterClient pagination for thread and replies', () => { json: async () => makeConversationPayload(['2', '3'], undefined, '1'), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getRepliesPaged('1'); expect(result.success).toBe(true); @@ -98,7 +98,7 @@ describe('TwitterClient pagination for thread and replies', () => { json: async () => makeConversationPayload(['4', '5'], undefined, '1'), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getRepliesPaged('1', { pageDelayMs: 0 }); expect(result.success).toBe(true); @@ -121,7 +121,7 @@ describe('TwitterClient pagination for thread and replies', () => { json: async () => makeConversationPayload(['4', '5'], 'cursor-page-3', '1'), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getRepliesPaged('1', { maxPages: 2, pageDelayMs: 0 }); expect(result.success).toBe(true); @@ -137,7 +137,7 @@ describe('TwitterClient pagination for thread and replies', () => { json: async () => makeConversationPayload(['4', '5'], undefined, '1'), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getRepliesPaged('1', { cursor: 'resume-cursor', pageDelayMs: 0 }); expect(result.success).toBe(true); @@ -161,7 +161,7 @@ describe('TwitterClient pagination for thread and replies', () => { json: async () => makeConversationPayload(['3', '4'], undefined, '1'), // '3' is duplicate }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getRepliesPaged('1', { pageDelayMs: 0 }); expect(result.success).toBe(true); @@ -182,7 +182,7 @@ describe('TwitterClient pagination for thread and replies', () => { text: async () => 'Internal Server Error', }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getRepliesPaged('1', { pageDelayMs: 0 }); expect(result.success).toBe(false); @@ -209,7 +209,7 @@ describe('TwitterClient pagination for thread and replies', () => { json: async () => makeConversationPayload(['3'], undefined, '1'), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getRepliesPaged('1', { pageDelayMs: 0 }); expect(result.success).toBe(true); @@ -227,7 +227,7 @@ describe('TwitterClient pagination for thread and replies', () => { json: async () => makeConversationPayload(['1', '2', '3'], undefined, undefined, '1'), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getThreadPaged('1'); expect(result.success).toBe(true); @@ -248,7 +248,7 @@ describe('TwitterClient pagination for thread and replies', () => { json: async () => makeConversationPayload(['3', '4'], undefined, undefined, '1'), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getThreadPaged('1', { pageDelayMs: 0 }); expect(result.success).toBe(true); @@ -320,7 +320,7 @@ describe('TwitterClient pagination for thread and replies', () => { json: async () => payload, }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getThreadPaged('1'); expect(result.success).toBe(true); @@ -391,7 +391,7 @@ describe('TwitterClient pagination for thread and replies', () => { json: async () => payload, }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getThreadPaged('1'); expect(result.success).toBe(true); @@ -412,7 +412,7 @@ describe('TwitterClient pagination for thread and replies', () => { json: async () => makeConversationPayload(['3', '4'], 'cursor-page-3', undefined, '1'), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getThreadPaged('1', { maxPages: 2, pageDelayMs: 0 }); expect(result.success).toBe(true); diff --git a/tests/twitter-client.search-bookmarks.test.ts b/tests/twitter-client.search-bookmarks.test.ts index 688b165..83a0bee 100644 --- a/tests/twitter-client.search-bookmarks.test.ts +++ b/tests/twitter-client.search-bookmarks.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { validCookies } from './twitter-client-fixtures.js'; +import { testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -69,7 +69,7 @@ describe('TwitterClient search', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.search('needle', 1); expect(result.success).toBe(true); @@ -109,7 +109,7 @@ describe('TwitterClient search', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.search('hello', 5); expect(result.success).toBe(true); @@ -117,7 +117,7 @@ describe('TwitterClient search', () => { }); it('returns an unknown error when no query IDs are available', async () => { - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); (client as unknown as { getSearchTimelineQueryIds: () => Promise }).getSearchTimelineQueryIds = async () => []; @@ -185,7 +185,7 @@ describe('TwitterClient search', () => { json: async () => makeResponse(['2', '3']), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.search('needle', 3); expect(result.success).toBe(true); @@ -260,7 +260,7 @@ describe('TwitterClient search', () => { json: async () => makeResponse(['3'], 'same-cursor'), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.search('needle', 4); expect(result.success).toBe(true); @@ -334,7 +334,7 @@ describe('TwitterClient search', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.search('needle', 3); expect(result.success).toBe(true); @@ -411,7 +411,7 @@ describe('TwitterClient search', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getAllSearchResults('query', { maxPages: 1 }); expect(result.success).toBe(true); @@ -466,7 +466,7 @@ describe('TwitterClient search', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getAllSearchResults('query', { cursor: 'old-cursor' }); expect(result.success).toBe(true); @@ -533,7 +533,7 @@ describe('TwitterClient bookmarks', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getBookmarks(2); expect(result.success).toBe(true); @@ -648,7 +648,7 @@ describe('TwitterClient bookmarks', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getAllBookmarks(); expect(result.success).toBe(true); @@ -760,7 +760,7 @@ describe('TwitterClient bookmarks', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getAllBookmarks({ maxPages: 1 }); expect(result.success).toBe(true); @@ -816,7 +816,7 @@ describe('TwitterClient bookmarks', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getAllBookmarks({ cursor: 'cursor-1' }); expect(result.success).toBe(true); @@ -931,7 +931,7 @@ describe('TwitterClient bookmarks', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getAllBookmarks(); expect(result.success).toBe(true); @@ -988,7 +988,7 @@ describe('TwitterClient bookmarks', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getAllBookmarks({ maxPages: 1 }); expect(result.success).toBe(true); @@ -1051,7 +1051,7 @@ describe('TwitterClient bookmark folders', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getBookmarkFolderTimeline('123', 2); expect(result.success).toBe(true); @@ -1123,7 +1123,7 @@ describe('TwitterClient bookmark folders', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const clientPrivate = client as TwitterClient & { getBookmarkFolderQueryIds: () => Promise }; clientPrivate.getBookmarkFolderQueryIds = async () => ['test']; diff --git a/tests/twitter-client.user-lookup.test.ts b/tests/twitter-client.user-lookup.test.ts index 06683bf..2564182 100644 --- a/tests/twitter-client.user-lookup.test.ts +++ b/tests/twitter-client.user-lookup.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { validCookies } from './twitter-client-fixtures.js'; +import { testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -37,7 +37,7 @@ describe('TwitterClient getUserIdByUsername', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserIdByUsername('@testuser'); expect(result.success).toBe(true); @@ -66,7 +66,7 @@ describe('TwitterClient getUserIdByUsername', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserIdByUsername('anotheruser'); expect(result.success).toBe(true); @@ -74,7 +74,7 @@ describe('TwitterClient getUserIdByUsername', () => { }); it('returns error for invalid username format', async () => { - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserIdByUsername('invalid handle with spaces'); @@ -84,7 +84,7 @@ describe('TwitterClient getUserIdByUsername', () => { }); it('returns error for empty username', async () => { - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserIdByUsername(''); @@ -94,7 +94,7 @@ describe('TwitterClient getUserIdByUsername', () => { }); it('returns error for username exceeding 15 characters', async () => { - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserIdByUsername('thisusernameiswaytoolong'); @@ -118,7 +118,7 @@ describe('TwitterClient getUserIdByUsername', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserIdByUsername('suspended'); expect(result.success).toBe(false); @@ -156,7 +156,7 @@ describe('TwitterClient getUserIdByUsername', () => { }), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserIdByUsername('founduser'); expect(result.success).toBe(true); diff --git a/tests/twitter-client.user-tweets.test.ts b/tests/twitter-client.user-tweets.test.ts index 57524c1..326a308 100644 --- a/tests/twitter-client.user-tweets.test.ts +++ b/tests/twitter-client.user-tweets.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TwitterClient } from '../src/lib/twitter-client.js'; -import { validCookies } from './twitter-client-fixtures.js'; +import { testRelayBaseUrl } from './twitter-client-fixtures.js'; const originalFetch = global.fetch; @@ -91,7 +91,7 @@ describe('TwitterClient getUserTweets', () => { makeTimelineResponse([makeTweetResult('1', 'First tweet'), makeTweetResult('2', 'Second tweet')]), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserTweets('12345', 10); expect(result.success).toBe(true); @@ -114,7 +114,7 @@ describe('TwitterClient getUserTweets', () => { ]), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserTweets('12345', 2); expect(result.success).toBe(true); @@ -128,7 +128,7 @@ describe('TwitterClient getUserTweets', () => { json: async () => makeTimelineResponse([]), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserTweets('12345', 10); expect(result.success).toBe(true); @@ -142,7 +142,7 @@ describe('TwitterClient getUserTweets', () => { json: async () => makeTimelineResponse([makeTweetResult('1', 'Tweet')], 'next-cursor-abc'), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserTweetsPaged('12345', 20, { maxPages: 1 }); expect(result.success).toBe(true); @@ -156,7 +156,7 @@ describe('TwitterClient getUserTweets', () => { text: async () => 'Internal Server Error', }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserTweets('12345', 10); expect(result.success).toBe(false); @@ -249,7 +249,7 @@ describe('TwitterClient getUserTweetsPaged', () => { ), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserTweetsPaged('12345', 5, { pageDelayMs: 0 }); expect(result.success).toBe(true); @@ -275,7 +275,7 @@ describe('TwitterClient getUserTweetsPaged', () => { }); } - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserTweetsPaged('12345', 9999, { pageDelayMs: 0 }); expect(result.success).toBe(true); @@ -285,7 +285,7 @@ describe('TwitterClient getUserTweetsPaged', () => { }); it('returns error for invalid limit', async () => { - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserTweetsPaged('12345', 0); expect(result.success).toBe(false); @@ -306,7 +306,7 @@ describe('TwitterClient getUserTweetsPaged', () => { json: async () => makeTimelineResponse([makeTweetResult('2', 'Page 2 Tweet')], 'cursor-page-3'), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserTweetsPaged('12345', 40, { maxPages: 2, pageDelayMs: 0, // No delay for tests @@ -333,7 +333,7 @@ describe('TwitterClient getUserTweetsPaged', () => { json: async () => makeTimelineResponse([makeTweetResult('2', 'Tweet 2')], 'cursor-3'), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserTweetsPaged('12345', 40, { maxPages: 2, pageDelayMs: 0, @@ -357,7 +357,7 @@ describe('TwitterClient getUserTweetsPaged', () => { json: async () => makeTimelineResponse([makeTweetResult('2', 'Tweet 2')]), // No cursor = end }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserTweetsPaged('12345', 100, { maxPages: 5, pageDelayMs: 0, @@ -386,7 +386,7 @@ describe('TwitterClient getUserTweetsPaged', () => { ]), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserTweetsPaged('12345', 40, { maxPages: 2, pageDelayMs: 0, @@ -404,7 +404,7 @@ describe('TwitterClient getUserTweetsPaged', () => { json: async () => makeTimelineResponse([makeTweetResult('5', 'Resumed Tweet')]), }); - const client = new TwitterClient({ cookies: validCookies }); + const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const result = await client.getUserTweetsPaged('12345', 20, { maxPages: 1, cursor: 'resume-cursor-xyz', From 6503bb1b7685398b04fd1a0339f885538e822864 Mon Sep 17 00:00:00 2001 From: yuta Date: Wed, 24 Jun 2026 03:52:16 +0900 Subject: [PATCH 2/2] Simplify relay request headers --- src/lib/twitter-client-base.ts | 44 ++----------------- src/lib/twitter-client-bookmarks.ts | 7 ++- src/lib/twitter-client-posting.ts | 14 +++--- src/lib/twitter-client-search.ts | 2 +- src/lib/twitter-client-tweet-detail.ts | 2 +- src/lib/twitter-client-types.ts | 1 - tests/twitter-client-coverage.core.test.ts | 8 ++-- ...ter-client.constructor-tweet-reply.test.ts | 13 +++--- 8 files changed, 23 insertions(+), 68 deletions(-) diff --git a/src/lib/twitter-client-base.ts b/src/lib/twitter-client-base.ts index f586785..f9d0ec4 100644 --- a/src/lib/twitter-client-base.ts +++ b/src/lib/twitter-client-base.ts @@ -1,4 +1,3 @@ -import { randomBytes, randomUUID } from 'node:crypto'; import { runtimeQueryIds } from './runtime-query-ids.js'; import { type OperationName, QUERY_IDS, TARGET_QUERY_ID_OPERATIONS } from './twitter-client-constants.js'; import type { CurrentUserResult, TwitterClientOptions } from './twitter-client-types.js'; @@ -16,22 +15,14 @@ export type Mixin, TAdded> export abstract class TwitterClientBase { protected relayBaseUrl: string; - protected userAgent: string; protected timeoutMs?: number; protected quoteDepth: number; - protected clientUuid: string; - protected clientDeviceId: string; protected clientUserId?: string; constructor(options: TwitterClientOptions) { 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'; this.timeoutMs = options.timeoutMs; this.quoteDepth = normalizeQuoteDepth(options.quoteDepth); - this.clientUuid = randomUUID(); - this.clientDeviceId = randomUUID(); } protected abstract getCurrentUser(): Promise; @@ -82,11 +73,7 @@ export abstract class TwitterClientBase { } protected getHeaders(): Record { - return this.getJsonHeaders(); - } - - protected createTransactionId(): string { - return randomBytes(16).toString('hex'); + return {}; } private normalizeRelayBaseUrl(value: string | undefined): string { @@ -105,37 +92,12 @@ export abstract class TwitterClientBase { return `${this.relayBaseUrl}${parsed.pathname}${parsed.search}`; } - protected getBaseHeaders(): Record { - const headers: Record = { - accept: '*/*', - 'accept-language': 'en-US,en;q=0.9', - '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(), - 'user-agent': this.userAgent, - origin: 'https://x.com', - referer: 'https://x.com/', - }; - - if (this.clientUserId) { - headers['x-twitter-client-user-id'] = this.clientUserId; - } - - return headers; - } - protected getJsonHeaders(): Record { - return { - ...this.getBaseHeaders(), - 'content-type': 'application/json', - }; + return { 'content-type': 'application/json' }; } protected getUploadHeaders(): Record { - // Note: do not set content-type; URLSearchParams/FormData need to set it (incl boundary) themselves. - return this.getBaseHeaders(); + return {}; } protected async ensureClientUserId(): Promise { diff --git a/src/lib/twitter-client-bookmarks.ts b/src/lib/twitter-client-bookmarks.ts index 49830a3..b16f38a 100644 --- a/src/lib/twitter-client-bookmarks.ts +++ b/src/lib/twitter-client-bookmarks.ts @@ -22,7 +22,6 @@ export function withBookmarks JSON.stringify({ variables, queryId }); - const buildHeaders = () => ({ ...this.getHeaders(), referer: `https://x.com/i/status/${tweetId}` }); let body = buildBody(); const parseResponse = async (response: Response): Promise => { @@ -42,7 +41,7 @@ export function withBookmarks let body = buildBody(); try { - const headers = { ...this.getHeaders(), referer: 'https://x.com/compose/post' }; + const headers = this.getJsonHeaders(); let response = await this.fetchWithTimeout(urlWithOperation, { method: 'POST', headers, @@ -88,14 +88,14 @@ export function withPosting response = await this.fetchWithTimeout(urlWithOperation, { method: 'POST', - headers: { ...this.getHeaders(), referer: 'https://x.com/compose/post' }, + headers, body, }); if (response.status === 404) { const retry = await this.fetchWithTimeout(TWITTER_GRAPHQL_POST_URL, { method: 'POST', - headers: { ...this.getHeaders(), referer: 'https://x.com/compose/post' }, + headers, body, }); @@ -224,12 +224,8 @@ export function withPosting try { const response = await this.fetchWithTimeout(TWITTER_STATUS_UPDATE_URL, { method: 'POST', - headers: { - ...this.getBaseHeaders(), - 'content-type': 'application/x-www-form-urlencoded', - referer: 'https://x.com/compose/post', - }, - body: params.toString(), + headers: this.getHeaders(), + body: params, }); if (!response.ok) { diff --git a/src/lib/twitter-client-search.ts b/src/lib/twitter-client-search.ts index 7848d69..d096643 100644 --- a/src/lib/twitter-client-search.ts +++ b/src/lib/twitter-client-search.ts @@ -105,7 +105,7 @@ export function withSearch> try { const response = await this.fetchWithTimeout(url, { method: 'POST', - headers: this.getHeaders(), + headers: this.getJsonHeaders(), body: JSON.stringify({ features, queryId }), }); diff --git a/src/lib/twitter-client-tweet-detail.ts b/src/lib/twitter-client-tweet-detail.ts index a70884c..db63b22 100644 --- a/src/lib/twitter-client-tweet-detail.ts +++ b/src/lib/twitter-client-tweet-detail.ts @@ -251,7 +251,7 @@ export function withTweetDetails Promise; fetchWithTimeout: (url: string, init: RequestInit) => Promise; ensureClientUserId: () => Promise; - getBaseHeaders: () => Record; + getHeaders: () => Record; fetchUserArticlePlainText: (userId: string, tweetId: string) => Promise<{ title?: string; plainText?: string }>; fetchTweetDetail: (tweetId: string) => Promise<{ success: true } | { success: false; error: string }>; postStatusUpdate: (input: { text: string }) => Promise<{ success: boolean; error?: string }>; @@ -108,7 +108,7 @@ describe('TwitterClient core coverage', () => { expect(result.error).toBe('Tweet not found in response'); }); - it('adds client user id header after ensureClientUserId', async () => { + it('does not add Twitter headers after ensureClientUserId', async () => { const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); process.env.NODE_ENV = 'production'; @@ -119,9 +119,9 @@ describe('TwitterClient core coverage', () => { const clientPrivate = client as unknown as TwitterClientPrivate; await clientPrivate.ensureClientUserId(); - const headers = clientPrivate.getBaseHeaders(); + const headers = clientPrivate.getHeaders(); - expect(headers['x-twitter-client-user-id']).toBe('42'); + expect(headers).toEqual({}); }); describe('fetchUserArticlePlainText failures', () => { diff --git a/tests/twitter-client.constructor-tweet-reply.test.ts b/tests/twitter-client.constructor-tweet-reply.test.ts index ba2175d..c74c319 100644 --- a/tests/twitter-client.constructor-tweet-reply.test.ts +++ b/tests/twitter-client.constructor-tweet-reply.test.ts @@ -68,9 +68,7 @@ describe('TwitterClient tweet', () => { expect(String(url)).toContain(`${testRelayBaseUrl}/i/api/graphql/`); expect(String(url)).toContain('CreateTweet'); expect(options.method).toBe('POST'); - expect(options.headers).not.toHaveProperty('cookie'); - expect(options.headers).not.toHaveProperty('authorization'); - expect(options.headers).not.toHaveProperty('x-csrf-token'); + expect(options.headers).toEqual({ 'content-type': 'application/json' }); const body = JSON.parse(options.body); expect(body.variables.tweet_text).toBe('Hello world!'); @@ -392,9 +390,10 @@ describe('TwitterClient reply', () => { const [, options] = mockFetch.mock.calls[1]; expect(String(mockFetch.mock.calls[1][0])).toContain('statuses/update.json'); expect(options.method).toBe('POST'); - expect(options.body).toContain('status=This+is+a+reply'); - expect(options.body).toContain('in_reply_to_status_id=1234567890'); - expect(options.body).toContain('auto_populate_reply_metadata=true'); - expect(options.body).toContain('media_ids=111%2C222'); + const body = String(options.body); + expect(body).toContain('status=This+is+a+reply'); + expect(body).toContain('in_reply_to_status_id=1234567890'); + expect(body).toContain('auto_populate_reply_metadata=true'); + expect(body).toContain('media_ids=111%2C222'); }); });