Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,15 @@ twitter unretweet 1234567890
twitter bookmark 1234567890
twitter unbookmark 1234567890
twitter follow elonmusk --json

# Timestamps: relative (default), absolute, or ISO
twitter feed --time absolute
twitter feed --time iso

# Shell completions (bash / zsh / fish)
twitter completion bash >> ~/.bashrc
twitter completion zsh > "${fpath[1]}/_twitter"
twitter completion fish > ~/.config/fish/completions/twitter.fish
```

### Authentication
Expand Down
5 changes: 4 additions & 1 deletion config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
fetch:
count: 50

display:
time: relative # relative | absolute | iso (overridable with --time)

filter:
mode: "topN"
topN: 20
Expand All @@ -18,4 +21,4 @@ rateLimit:
requestDelay: 1.5 # seconds between paginated requests
maxRetries: 3 # retry count on 429 / rate-limit errors
retryBaseDelay: 5.0 # base delay for exponential backoff (seconds)
maxCount: 200 # hard cap for single fetch
maxCount: 200 # default cap for a single fetch; an explicit --max may exceed it
72 changes: 72 additions & 0 deletions tests/test_completion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"""Shell completion script generation (issue #36).

Click can emit completion scripts itself, so this needs no extra dependency
(the issue suggested shtab). These tests assert each shell actually produces a
script for `twitter`, not merely that the command succeeds.
"""

from __future__ import annotations

import pytest
from click.testing import CliRunner

from twitter_cli.cli import cli


def _run(*args: str):
return CliRunner().invoke(cli, list(args))


@pytest.mark.parametrize("shell", ["bash", "zsh", "fish"])
def test_completion_script_is_emitted(shell: str) -> None:
result = _run("completion", shell)

assert result.exit_code == 0, result.output
script = result.output
assert len(script) > 100, "expected a real script, got %r" % script
# Each shell's script must register a twitter completion entry point.
assert "twitter" in script


def test_bash_script_defines_completion_function() -> None:
result = _run("completion", "bash")

assert result.exit_code == 0
assert "_twitter_completion" in result.output
assert "complete" in result.output


def test_zsh_script_is_a_compdef() -> None:
result = _run("completion", "zsh")

assert result.exit_code == 0
assert result.output.lstrip().startswith("#compdef")


def test_fish_script_defines_function() -> None:
result = _run("completion", "fish")

assert result.exit_code == 0
assert "function" in result.output


def test_unknown_shell_is_rejected() -> None:
result = _run("completion", "powershell")

assert result.exit_code != 0
assert "powershell" in result.output


def test_completion_requires_a_shell_argument() -> None:
result = _run("completion")

assert result.exit_code != 0


def test_completion_lists_known_subcommands() -> None:
"""The generated script should drive completion from the CLI's own tree."""
result = _run("completion", "zsh")

assert result.exit_code == 0
# Click's zsh template shells out to the CLI's completion protocol.
assert "_TWITTER_COMPLETE" in result.output
123 changes: 123 additions & 0 deletions tests/test_issue_mitigations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
"""Mitigations for account-safety and Windows-cookie issues (#72, #28/#66/#46).

Both are advisory rather than behavioural: we do not refuse to run, we make the
cause and the workaround visible instead of leaving users with a silent 404 or a
generic "decryption failed".
"""

from __future__ import annotations

import pytest

from twitter_cli import auth
from twitter_cli.client import TwitterClient

# ── #28 / #66 / #46: Windows App-Bound Encryption ────────────────────────

ABC_DIAGNOSTIC = [
"chrome in-process extraction failed: Unable to get key for cookie decryption"
]


@pytest.fixture()
def windows(monkeypatch):
"""Pin the platform to Windows so these assertions are host-independent.

`_diagnose_keychain_issues` branches on `sys.platform`; without this they
only hold when the suite happens to run on Windows.
"""
monkeypatch.setattr(auth.sys, "platform", "win32")
for var in ("SSH_CLIENT", "SSH_TTY", "SSH_CONNECTION"):
monkeypatch.delenv(var, raising=False)
return monkeypatch


def test_windows_abc_failure_names_app_bound_encryption(windows) -> None:
hint = auth._diagnose_keychain_issues(ABC_DIAGNOSTIC)

assert hint is not None
assert "App-Bound Encryption" in hint
# Must not send people down the admin rabbit hole.
assert "not a permissions issue" in hint


def test_windows_abc_hint_gives_actionable_workarounds(windows) -> None:
hint = auth._diagnose_keychain_issues(ABC_DIAGNOSTIC)

assert hint is not None
assert "TWITTER_AUTH_TOKEN" in hint
assert "TWITTER_CT0" in hint
assert "TWITTER_BROWSER=firefox" in hint


def test_windows_generic_failure_keeps_generic_hint(windows) -> None:
hint = auth._diagnose_keychain_issues(["chrome: Safe Storage unavailable"])

assert hint is not None
assert "App-Bound Encryption" not in hint


def test_windows_hint_retains_dpapi_advice(windows) -> None:
"""The non-ABC causes (Chrome lock / VSS shadowcopy) stay documented."""
hint = auth._diagnose_keychain_issues(ABC_DIAGNOSTIC)
assert hint is not None
assert "VSS shadowcopy" in hint


def test_non_matching_diagnostic_returns_none(windows) -> None:
assert auth._diagnose_keychain_issues(["browser not found"]) is None


# ── #72: writing without x-client-transaction-id ─────────────────────────


def _unsigned_client():
client = TwitterClient.__new__(TwitterClient)
client._auth_token = "tok"
client._ct0 = "ct0"
client._cookie_string = None
client._client_transaction = None # bootstrap failed
return client


def test_unsigned_write_logs_a_prominent_warning(caplog) -> None:
client = _unsigned_client()

with caplog.at_level("WARNING"):
headers = client._build_headers("https://x.com/i/api/graphql/q/CreateTweet", method="POST")

assert "X-Client-Transaction-Id" not in headers
assert "UNSIGNED" in caplog.text
assert "automation" in caplog.text


def test_signed_write_does_not_warn(caplog) -> None:
client = _unsigned_client()
client._client_transaction = type(
"CT", (), {"generate_transaction_id": staticmethod(lambda method, path: "tid-123")}
)()

with caplog.at_level("WARNING"):
headers = client._build_headers("https://x.com/i/api/graphql/q/CreateTweet", method="POST")

assert headers["X-Client-Transaction-Id"] == "tid-123"
assert "UNSIGNED" not in caplog.text


def test_unsigned_read_does_not_warn(caplog) -> None:
"""Reads without the header mostly just 404; warning would be noise."""
client = _unsigned_client()

with caplog.at_level("WARNING"):
client._build_headers("https://x.com/i/api/graphql/q/HomeTimeline", method="GET")

assert "UNSIGNED" not in caplog.text


def test_write_does_not_raise(caplog) -> None:
"""The warning must not turn into a hard failure."""
client = _unsigned_client()
with caplog.at_level("WARNING"):
headers = client._build_headers("https://x.com/i/api/graphql/q/CreateTweet", method="POST")

assert isinstance(headers, dict)
134 changes: 134 additions & 0 deletions tests/test_pagination_cap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
"""Followers/following pagination must honour an explicit --max (issue #50).

`_fetch_user_list` used to clamp the requested count to ``self._max_count``,
which is derived from the ``rateLimit.maxCount`` config (default 200) and was
additionally bounded by a hard 500 ceiling. The pagination loop itself was
correct, so large accounts were silently truncated regardless of ``--max``.
"""

from __future__ import annotations

from types import SimpleNamespace

from twitter_cli import client as client_mod
from twitter_cli.client import _ABSOLUTE_MAX_COUNT, TwitterClient


class _StubClient(TwitterClient):
"""Client whose GraphQL calls are fully stubbed."""

def __init__(self):
self._auth_token = "t"
self._ct0 = "c"
self._cookie_string = None
self._client_transaction = None
self._ct_init_attempted = True
self._max_count = 200 # the configured default that used to clamp
self._request_delay = 0.0
self._max_retries = 0
self.pages_requested = 0


def _instructions(user_ids, cursor=None):
"""One page of user entries plus an optional bottom cursor."""
entries = []
for index, uid in enumerate(user_ids):
entries.append(
{
"content": {
"entryType": "TimelineTimelineItem",
"itemContent": {"user_results": {"result": {"rest_id": uid}}},
}
}
)
if cursor:
entries.append(
{
"content": {
"entryType": "TimelineTimelineCursor",
"cursorType": "Bottom",
"value": cursor,
}
}
)
return [{"entries": entries}]


def _make_paged_client(monkeypatch, page_size=20, total_pages=40):
"""Return a client that serves `total_pages` full pages then stops."""
stub = _StubClient()
state = {"page": 0}

def fake_graphql_get(operation_name, variables, features, field_toggles=None):
index = state["page"]
state["page"] += 1
stub.pages_requested += 1
ids = ["u%d" % (index * page_size + i) for i in range(page_size)]
has_more = index + 1 < total_pages
return {
"instructions": _instructions(
ids, cursor="cursor-%d" % (index + 1) if has_more else None
)
}

monkeypatch.setattr(stub, "_graphql_get", fake_graphql_get)
monkeypatch.setattr(stub, "_graphql_post", fake_graphql_get)
monkeypatch.setattr(
client_mod,
"parse_user_result",
lambda result: SimpleNamespace(id=result.get("rest_id")) if result.get("rest_id") else None,
)
return stub


def test_explicit_max_beyond_old_500_cap_is_fetched(monkeypatch) -> None:
"""600 users must be retrievable; the old ceiling stopped at 500."""
stub = _make_paged_client(monkeypatch, page_size=20, total_pages=40)

users = stub._fetch_user_list(
"Followers", "123", 600, lambda data: data.get("instructions")
)

assert len(users) == 600
assert stub.pages_requested >= 30


def test_explicit_max_ignores_configured_default(monkeypatch) -> None:
"""A config default of 200 must not truncate an explicit --max of 300."""
stub = _make_paged_client(monkeypatch, page_size=20, total_pages=40)

users = stub._fetch_user_list(
"Following", "123", 300, lambda data: data.get("instructions")
)

assert len(users) == 300


def test_safety_ceiling_still_applies(monkeypatch, caplog) -> None:
"""An absurd request is capped at the safety ceiling, not unbounded."""
stub = _StubClient()
requested = {}

def fake_graphql_get(operation_name, variables, features, field_toggles=None):
requested["count"] = requested.get("count", 0) + 1
# Single page then stop, so we observe the clamp without 500 pages.
return {"instructions": _instructions(["u1"])}

monkeypatch.setattr(stub, "_graphql_get", fake_graphql_get)
monkeypatch.setattr(client_mod, "parse_user_result", lambda r: SimpleNamespace(id="u1"))

with caplog.at_level("WARNING"):
stub._fetch_user_list("Followers", "1", _ABSOLUTE_MAX_COUNT + 5000, lambda d: d["instructions"])

assert "exceeds the safety ceiling" in caplog.text


def test_zero_or_negative_count_returns_empty(monkeypatch) -> None:
stub = _make_paged_client(monkeypatch)
assert stub._fetch_user_list("Followers", "1", 0, lambda d: d["instructions"]) == []
assert stub._fetch_user_list("Followers", "1", -5, lambda d: d["instructions"]) == []


def test_ceiling_is_large_enough_for_real_accounts() -> None:
"""Regression guard: the ceiling must stay well above the old 500."""
assert _ABSOLUTE_MAX_COUNT >= 5000
Loading