diff --git a/pyproject.toml b/pyproject.toml index de8f3dc..94fd3fa 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,7 +25,7 @@ dependencies = [ "rich>=13.0", "PyYAML>=6.0", "curl_cffi>=0.7", - "xclienttransaction>=1.0.1", + "xclienttransaction>=1.0.3", "beautifulsoup4>=4.12", ] diff --git a/tests/test_client.py b/tests/test_client.py index c1393d3..e24f363 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1545,3 +1545,140 @@ def mock_post(operation_name, variables, features=None): assert captured.get("product") == "Latest" assert captured.get("querySource") == "typed_query" + + +# ── ClientTransaction bootstrap (x-client-transaction-id) ─────────────── + +# Synthetic x.com/home page in the layout X ships since Sept 2026: +# - webpack numeric module map ("59924:\"ondemand.s\"") +# - separate numeric index -> hash map +# - twitter-site-verification meta + loading-x-anim frames +# The key is a valid base64 blob (16 bytes) so get_key_bytes() can decode it. +_CT_HOME_HTML = ( + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' +) + +# The current ondemand.s bundle content shape (fetched 2026-09-29). The +# INDICES pattern the library extracts from it is embedded here so the test +# runs without a network call. Note the required space after each comma — +# the INDICES_REGEX is `(x[<1-2 digits>], 16)`-shaped. The real bundle yields +# >=2 matches (row index + frame-time bytes), so this fixture does too. +_CT_ONDEMAND_JS = ( + "var a=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25," + "26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45];" + "var b=function(c){return(a[(c[0], 16)],(a[(c[1], 17)]),(a[(c[2], 18)])," + "(a[(c[3], 19)]),(a[(c[4], 20)]));};var d=b(a);" +) + + +class TestClientTransactionBootstrap: + """Regression: CT must bootstrap from /home (with the session cookie), + not from the stripped root page, and must send the cookie on the + bootstrap request.""" + + def _make_client(self, cookie_string=None): + client = TwitterClient.__new__(TwitterClient) + client._auth_token = "auth_tok" + client._ct0 = "ct0_val" + client._cookie_string = cookie_string + client._client_transaction = None + client._ct_init_attempted = False + client._load_ct_cache = MagicMock(return_value=False) + client._save_ct_cache = MagicMock() + return client + + @patch("twitter_cli.client._update_features_from_html") + @patch("twitter_cli.client.ClientTransaction") + @patch("twitter_cli.client._gen_ct_headers", return_value={"Referer": "https://x.com"}) + @patch("twitter_cli.client._get_cffi_session") + def test_bootstraps_from_home_with_cookie( + self, mock_session, mock_ct_headers, mock_tx, mock_features + ): + """First request must be x.com/home carrying the session cookie, and + the second must be the resolved ondemand.s bundle URL.""" + import bs4 + + home_page = MagicMock( + content=_CT_HOME_HTML.encode("utf-8"), text=_CT_HOME_HTML + ) + ondemand_page = MagicMock(text=_CT_ONDEMAND_JS) + + mock_session.return_value.get.side_effect = [home_page, ondemand_page] + + client = self._make_client(cookie_string="auth_token=auth_tok; ct0=ct0_val") + client._ensure_client_transaction() + + first = mock_session.return_value.get.call_args_list[0] + second = mock_session.return_value.get.call_args_list[1] + # 1. The bootstrap hit the responsive /home route, not the root shell. + assert first.args[0] == "https://x.com/home" + # 2. The session cookie was sent on the bootstrap request. + headers = first.kwargs.get("headers", {}) + assert headers.get("Cookie") == "auth_token=auth_tok; ct0=ct0_val" + # 3. The ondemand bundle URL was resolved from the /home page + # (only possible because the module + hash maps are present). + assert second.args[0] == ( + "https://abs.twimg.com/responsive-web/client-web/" + "ondemand.s.38289b77fa31a72ca.js" + ) + # 4. The ClientTransaction object was constructed from the /home page. + mock_tx.assert_called_once() + constructed_page = mock_tx.call_args.kwargs["home_page_response"] + assert isinstance(constructed_page, bs4.BeautifulSoup) + + @patch("twitter_cli.client._update_features_from_html") + @patch("twitter_cli.client.ClientTransaction") + @patch("twitter_cli.client._gen_ct_headers", return_value={"Referer": "https://x.com"}) + @patch("twitter_cli.client._get_cffi_session") + def test_falls_back_to_auth_token_cookie( + self, mock_session, mock_ct_headers, mock_tx, mock_features + ): + """When no full browser cookie string exists, the bootstrap still + sends auth_token+ct0 so the /home page is not stripped.""" + home_page = MagicMock( + content=_CT_HOME_HTML.encode("utf-8"), text=_CT_HOME_HTML + ) + home_page.content = _CT_HOME_HTML.encode("utf-8") + ondemand_page = MagicMock(text=_CT_ONDEMAND_JS) + mock_session.return_value.get.side_effect = [home_page, ondemand_page] + + client = self._make_client(cookie_string=None) + client._ensure_client_transaction() + + headers = mock_session.return_value.get.call_args_list[0].kwargs.get("headers", {}) + assert headers.get("Cookie") == "auth_token=auth_tok; ct0=ct0_val" + + @patch("twitter_cli.client._update_features_from_html") + @patch("twitter_cli.client.ClientTransaction") + @patch("twitter_cli.client._gen_ct_headers", return_value={"Referer": "https://x.com"}) + @patch("twitter_cli.client._get_cffi_session") + def test_real_parser_resolves_ondemand_from_current_layout( + self, mock_session, mock_ct_headers, mock_tx, mock_features + ): + """The real (unmocked) x_client_transaction parser must resolve the + ondemand.s URL from a page in the current numeric-module layout. + + This is the exact call that raised AttributeError under the pinned + xclienttransaction 1.0.1 (its regex expects the old + '"ondemand.s": ""' name->hash map, not the numeric index + layout X ships since Sept 2026). The floor bump in pyproject.toml + (>=1.0.3) is what makes this pass. + """ + from x_client_transaction.utils import get_ondemand_file_url + import bs4 + + soup = bs4.BeautifulSoup(_CT_HOME_HTML, "html.parser") + url = get_ondemand_file_url(response=soup) + assert url == ( + "https://abs.twimg.com/responsive-web/client-web/" + "ondemand.s.38289b77fa31a72ca.js" + ) diff --git a/tests/test_smoke.py b/tests/test_smoke.py index d7cec04..20b7524 100644 --- a/tests/test_smoke.py +++ b/tests/test_smoke.py @@ -83,3 +83,25 @@ def test_feed(self): result, payload = _invoke("feed", "--max", "3") assert result.exit_code == 0, f"feed failed: {result.output}" assert payload["ok"] is True + + +@smoke +class TestCTGatedReads: + """Endpoints that 404 without the x-client-transaction-id header. + + These were broken (HTTP 404 on SearchTimeline/Followers/Following/Likes) + because the CT bootstrap fetched the stripped root page. They are the + live regression guard for the /home+cookie bootstrap. + """ + + def test_followers(self): + result, payload = _invoke("followers", "elonmusk", "--max", "3") + assert result.exit_code == 0, f"followers failed: {result.output}" + assert payload["ok"] is True + assert len(payload["data"]) >= 1 + + def test_following(self): + result, payload = _invoke("following", "elonmusk", "--max", "3") + assert result.exit_code == 0, f"following failed: {result.output}" + assert payload["ok"] is True + assert len(payload["data"]) >= 1 diff --git a/twitter_cli/client.py b/twitter_cli/client.py index 0436c8e..44696d1 100644 --- a/twitter_cli/client.py +++ b/twitter_cli/client.py @@ -1103,8 +1103,20 @@ def _ensure_client_transaction(self): # a different TLS fingerprint on the same IP — a detection vector. cffi_session = _get_cffi_session() ct_headers = _gen_ct_headers() + # The root path serves a lightweight logged-out shell without the + # ondemand.s bundle. The responsive /home route exposes it, but + # only when a session cookie is sent (verified 2026-09-29: + # /home without a cookie is a 17KB stripped shell, with a cookie + # it is a 305KB page containing the module + hash maps). + # The generated transaction id is derived from public page data, + # so sending the cookie here does not weaken it — it is only the + # difference between a header that works and a 404 on every + # header-gated GET (SearchTimeline, Followers, Following, Likes). + ct_headers["Cookie"] = self._cookie_string or ( + "auth_token=%s; ct0=%s" % (self._auth_token, self._ct0) + ) home_page = cffi_session.get( - "https://x.com", headers=ct_headers, timeout=10, + "https://x.com/home", headers=ct_headers, timeout=10, ) home_page_response = bs4.BeautifulSoup(home_page.content, "html.parser") ondemand_url = get_ondemand_file_url(response=home_page_response) diff --git a/twitter_cli/graphql.py b/twitter_cli/graphql.py index d34ea35..c82d04c 100644 --- a/twitter_cli/graphql.py +++ b/twitter_cli/graphql.py @@ -120,13 +120,35 @@ def _scan_bundles(url_fetch_fn): try: from .constants import get_user_agent html = url_fetch_fn("https://x.com", {"user-agent": get_user_agent()}) + # Match both the legacy responsive-web/client-web layout and the new + # x-web/x-web layout (X moved the web build to /x-web/ in 2026). script_pattern = re.compile( r'(?:src|href)=["\']' - r'(https://abs\.twimg\.com/responsive-web/client-web[^"\']+' + r'(https://abs\.twimg\.com/(?:responsive-web/client-web|x-web/x-web)[^"\']+' r'\.js)' r'["\']' ) script_urls = script_pattern.findall(html) + # The x-web entry bundle references its code as relative ./assets/*.js + # chunks — follow those so any queryId/operationName pairs stay + # reachable as the build layout evolves. + if script_urls: + try: + from curl_cffi import requests as _cc_requests + + _sess: Any = _cc_requests.Session(impersonate="chrome") + for script_url in list(script_urls): + if "/x-web/x-web/" not in script_url: + continue + entry = _sess.get(script_url, timeout=20).text + for rel in re.findall( + r'["\']\./assets/([a-zA-Z0-9._\-]+\.js)["\']', entry + ): + full = script_url.rsplit("/", 1)[0] + "/" + rel + if full not in script_urls: + script_urls.append(full) + except Exception as _exc: + logger.debug("x-web asset follow-up scan failed: %s", _exc) except Exception as exc: # pragma: no cover - network-dependent branch logger.warning("Failed to scan JS bundles: %s", exc) return diff --git a/uv.lock b/uv.lock index 5c2ba17..5dab4dd 100644 --- a/uv.lock +++ b/uv.lock @@ -170,7 +170,7 @@ name = "exceptiongroup" version = "1.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } wheels = [ @@ -641,7 +641,7 @@ requires-dist = [ { name = "rich", specifier = ">=13.0" }, { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.8" }, { name = "types-pyyaml", marker = "extra == 'dev'", specifier = ">=6.0.12" }, - { name = "xclienttransaction", specifier = ">=1.0.1" }, + { name = "xclienttransaction", specifier = ">=1.0.3" }, ] provides-extras = ["dev"] @@ -677,12 +677,12 @@ wheels = [ [[package]] name = "xclienttransaction" -version = "1.0.1" +version = "1.0.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "beautifulsoup4" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/eb/c7/c841afe6759567cf29e36196dff65c935682b69ae38e986bd14e7decf74e/xclienttransaction-1.0.1.tar.gz", hash = "sha256:e4e032ff27e76ab927c0a7f57ad3630e06b7100c113bdf22b03cdde9584756f3", size = 9062, upload-time = "2025-10-09T10:38:31.485Z" } +sdist = { url = "https://files.pythonhosted.org/packages/1b/11/6f5a55df6d464fe6f839fe96c3863fa2338005ed8e83e89b0a9db5716b5a/xclienttransaction-1.0.3.tar.gz", hash = "sha256:1eeb5d48cec6a224189bbd8a6021c40486fa3aff650478672bccf82b3436cedc", size = 10609, upload-time = "2026-06-26T10:47:39.664Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/fe/b8/b953828e2f0f658f7f2d6354525728c9569c83937ebe4903f2391f02a702/xclienttransaction-1.0.1-py3-none-any.whl", hash = "sha256:0280e021129a38f8ee2ebede6406d4c065a599430bd4c8aa0c122f2e42f9f0f0", size = 10724, upload-time = "2025-10-09T10:38:30.098Z" }, + { url = "https://files.pythonhosted.org/packages/fa/a1/be735112ebe49916065e6f80017b93e92fc8880789c3f4f17380db7f531a/xclienttransaction-1.0.3-py3-none-any.whl", hash = "sha256:f73dd2a4b6856f98fa45f0cd26c9a0fdc0b2ceba0e79b5523cdf8aac7efc59fe", size = 10778, upload-time = "2026-06-26T10:47:38.401Z" }, ]