From d9cc8ae828820c0959dbeec42475053f13f78b21 Mon Sep 17 00:00:00 2001 From: Kage Date: Thu, 29 Oct 2026 09:35:29 +0700 Subject: [PATCH] fix: refuse GraphQL writes when x-client-transaction-id is unavailable When ClientTransaction fails to initialise, _build_headers() silently omits the x-client-transaction-id header and every GraphQL POST goes out as a bare API client. X answers those with a misleading `344 "You have reached your daily limit"` even on accounts that have never posted, and accounts whose writes do get through are suspended shortly afterwards. Fail closed instead: if no transaction id could be produced, refuse POST requests with an explicit error, and make the init failure loud in the log. GET requests are unaffected (they do not require the header). Escape hatch for deliberate unsigned writes: TWITTER_ALLOW_UNSIGNED=1. The media-upload test fixture now supplies a transaction id, since INIT/APPEND /FINALIZE are POSTs too. --- tests/test_client.py | 65 ++++++++++++++++++++++++++++++++++++++++++- twitter_cli/client.py | 29 +++++++++++++++++-- 2 files changed, 90 insertions(+), 4 deletions(-) diff --git a/tests/test_client.py b/tests/test_client.py index c1393d3..ad698b9 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1356,7 +1356,9 @@ def _make_client(self): client._max_retries = 3 client._retry_base_delay = 5.0 client._max_count = 200 - client._client_transaction = None + # media upload is a POST: it needs a transaction id like any other write + client._client_transaction = MagicMock() + client._client_transaction.generate_transaction_id.return_value = "tid-media" client._ct_init_attempted = True return client @@ -1545,3 +1547,64 @@ def mock_post(operation_name, variables, features=None): assert captured.get("product") == "Latest" assert captured.get("querySource") == "typed_query" + + +# ── Fail-closed guard for unsigned writes ──────────────────────────────── + + +class TestUnsignedWriteGuard: + """X gates GraphQL writes on `x-client-transaction-id`. + + A POST sent without that header is treated as automation by X: it either + fails with a misleading `344 "daily limit"` on accounts that never posted, + or it goes through and the account is suspended shortly after. When the + ClientTransaction bootstrap fails we must refuse the write instead of + sending it unsigned. + """ + + @staticmethod + def _client(): + client = TwitterClient.__new__(TwitterClient) + client._auth_token = "test_token" + client._ct0 = "test_ct0" + client._cookie_string = None + client._client_transaction = None + client._ct_init_attempted = True + return client + + def test_post_without_transaction_id_is_refused(self): + client = self._client() + with pytest.raises(TwitterAPIError) as exc: + client._build_headers("https://x.com/i/api/graphql/qid/CreateTweet", "POST") + assert "REFUSING unsigned write" in str(exc.value) + + def test_override_env_allows_unsigned_post(self, monkeypatch): + monkeypatch.setenv("TWITTER_ALLOW_UNSIGNED", "1") + client = self._client() + headers = client._build_headers( + "https://x.com/i/api/graphql/qid/CreateTweet", "POST") + assert "X-Client-Transaction-Id" not in headers + + def test_get_without_transaction_id_is_allowed(self): + client = self._client() + headers = client._build_headers( + "https://x.com/i/api/graphql/qid/HomeTimeline", "GET") + assert "X-Client-Transaction-Id" not in headers + assert "Authorization" in headers + + def test_post_with_transaction_id_sets_header(self): + client = self._client() + transaction = MagicMock() + transaction.generate_transaction_id.return_value = "tid-123" + client._client_transaction = transaction + headers = client._build_headers( + "https://x.com/i/api/graphql/qid/CreateTweet", "POST") + assert headers["X-Client-Transaction-Id"] == "tid-123" + + def test_failing_generator_also_refuses(self): + client = self._client() + transaction = MagicMock() + transaction.generate_transaction_id.side_effect = RuntimeError("boom") + client._client_transaction = transaction + with pytest.raises(TwitterAPIError): + client._build_headers("https://x.com/i/api/graphql/qid/CreateTweet", "POST") diff --git a/twitter_cli/client.py b/twitter_cli/client.py index 0436c8e..d789f1c 100644 --- a/twitter_cli/client.py +++ b/twitter_cli/client.py @@ -1125,7 +1125,13 @@ def _ensure_client_transaction(self): # Save to cache for future use self._save_ct_cache(home_page.text, ondemand_file.text) except Exception as exc: - logger.warning("Failed to init ClientTransaction: %s", exc) + logger.warning( + "Failed to init ClientTransaction: %s — x-client-transaction-id is " + "UNAVAILABLE. Write requests will be REFUSED (unsigned POSTs get " + "accounts suspended). Fix the bootstrap, or set " + "TWITTER_ALLOW_UNSIGNED=1 to override.", + exc, + ) def _build_headers(self, url="", method="GET"): # type: (str, str) -> Dict[str, str] @@ -1159,14 +1165,31 @@ def _build_headers(self, url="", method="GET"): headers["Content-Type"] = "application/json" headers["Referer"] = "https://x.com/compose/post" headers["Priority"] = "u=1, i" - # Generate x-client-transaction-id if available + # Generate x-client-transaction-id. X gates GraphQL writes on this header: + # a POST without it is treated as automation (silent fake `344 daily + # limit`, or a suspension within ~24-48h). Fail CLOSED instead of + # sending an unsigned write. + tid = None if self._client_transaction and url: try: path = urllib.parse.urlparse(url).path tid = self._client_transaction.generate_transaction_id( method=method, path=path, ) - headers["X-Client-Transaction-Id"] = tid except Exception as exc: logger.debug("Failed to generate transaction id: %s", exc) + if tid: + headers["X-Client-Transaction-Id"] = tid + elif method == "POST": + msg = ( + "REFUSING unsigned write: x-client-transaction-id is not available " + "(ClientTransaction failed to init). X treats unsigned writes as " + "automation and can suspend the account. Fix the ClientTransaction " + "bootstrap, or set TWITTER_ALLOW_UNSIGNED=1 to override at your own risk." + ) + if os.environ.get("TWITTER_ALLOW_UNSIGNED") == "1": + logger.warning("%s [overridden by TWITTER_ALLOW_UNSIGNED=1]", msg) + else: + logger.error("%s", msg) + raise TwitterAPIError(0, msg) return headers