From 184e08a6c7a62e0792c7c48d886ed283aaac2872 Mon Sep 17 00:00:00 2001 From: Aditya Gupta Date: Sun, 4 Oct 2026 23:35:37 +0530 Subject: [PATCH] feat(auth): add Zen browser cookie extraction Discover Zen profiles across Linux, Flatpak, macOS, and Windows, including XDG config locations. Follow Firefox profile selection by preferring the install default from profiles.ini and supporting absolute profile paths. Read Zen cookies using the Firefox loader in both extraction paths. Add browser priority support, documentation, and regression coverage. --- README.md | 17 ++++++--- tests/test_auth.py | 91 +++++++++++++++++++++++++++++++++++++++++++++ twitter_cli/auth.py | 79 ++++++++++++++++++++++++++++++++++----- 3 files changed, 171 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index e033cd2..8753f74 100644 --- a/README.md +++ b/README.md @@ -174,7 +174,7 @@ twitter follow elonmusk --json twitter-cli uses this auth priority: 1. **Environment variables**: `TWITTER_AUTH_TOKEN` + `TWITTER_CT0` -2. **Browser cookies** (recommended): auto-extract from Arc/Chrome/Edge/Firefox/Brave +2. **Browser cookies** (recommended): auto-extract from Arc/Chrome/Edge/Firefox/Brave/Zen Browser extraction is recommended — it forwards ALL Twitter cookies (not just `auth_token` + `ct0`) and aligns request headers with your local runtime, which is closer to normal browser traffic than minimal cookie auth. @@ -184,10 +184,15 @@ Browser extraction is recommended — it forwards ALL Twitter cookies (not just TWITTER_CHROME_PROFILE="Profile 2" twitter feed ``` +Zen profiles are scanned automatically on Linux (including Flatpak), macOS, and Windows. +The default profile from `profiles.ini` is tried first; Linux discovery includes +`$XDG_CONFIG_HOME/zen` (or `~/.config/zen`) and `~/.zen`. +Use `TWITTER_BROWSER=zen twitter feed` to try Zen first. + **Browser priority:** If you have multiple browsers, set `TWITTER_BROWSER` to try a specific browser first: ```bash -TWITTER_BROWSER=chrome twitter feed # Supported: arc, chrome, edge, firefox, brave +TWITTER_BROWSER=chrome twitter feed # Supported: arc, chrome, edge, firefox, brave, zen ``` After loading cookies, the CLI performs lightweight verification. Commands that require account access fail fast on clear auth errors (`401/403`). @@ -278,7 +283,7 @@ Mode behavior: ### Troubleshooting - `No Twitter cookies found` - - Ensure you are logged in to `x.com` in a supported browser (Arc/Chrome/Edge/Firefox/Brave). + - Ensure you are logged in to `x.com` in a supported browser (Arc/Chrome/Edge/Firefox/Brave/Zen). - Or set `TWITTER_AUTH_TOKEN` and `TWITTER_CT0` manually. - Run with `-v` to see browser extraction diagnostics. @@ -497,7 +502,7 @@ twitter follow elonmusk --json 认证优先级: 1. **环境变量**:`TWITTER_AUTH_TOKEN` + `TWITTER_CT0` -2. **浏览器提取**(推荐):Arc/Chrome/Edge/Firefox/Brave 全量 Cookie 提取 +2. **浏览器提取**(推荐):Arc/Chrome/Edge/Firefox/Brave/Zen 全量 Cookie 提取 推荐使用浏览器提取方式,会转发所有 Twitter Cookie,并按本机运行环境生成语言和平台请求头;它比仅发送 `auth_token` + `ct0` 更接近普通浏览器流量,但不等于完整浏览器自动化。 @@ -510,7 +515,7 @@ TWITTER_CHROME_PROFILE="Profile 2" twitter feed **浏览器优先级**:如果有多个浏览器,可通过 `TWITTER_BROWSER` 指定优先尝试的浏览器: ```bash -TWITTER_BROWSER=chrome twitter feed # 支持: arc, chrome, edge, firefox, brave +TWITTER_BROWSER=chrome twitter feed # 支持: arc, chrome, edge, firefox, brave, zen ``` ### 代理支持 @@ -551,7 +556,7 @@ score = likes_w * likes ### 常见问题 -- 报错 `No Twitter cookies found`:请先登录 `x.com`,并确认浏览器为 Arc/Chrome/Edge/Firefox/Brave 之一,或手动设置环境变量。 +- 报错 `No Twitter cookies found`:请先登录 `x.com`,并确认浏览器为 Arc/Chrome/Edge/Firefox/Brave/Zen 之一,或手动设置环境变量。 - 如需查看浏览器提取细节,可加 `-v` 打开诊断日志。 - 报错 `Cookie expired or invalid`:Cookie 过期,重新登录后重试。 - 报错 `Unable to get key for cookie decryption`(macOS Keychain 问题): diff --git a/tests/test_auth.py b/tests/test_auth.py index 8010c08..5559087 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -412,3 +412,94 @@ class BrowserError(Exception): assert cookies is None assert any("cookie decryption" in d for d in diagnostics) + + +@pytest.mark.parametrize("platform,relative", [ + ("linux", ".zen/test/cookies.sqlite"), + ("linux", ".var/app/app.zen_browser.zen/zen/test/cookies.sqlite"), + ("linux", ".var/app/app.zen_browser.zen/.zen/test/cookies.sqlite"), + ("darwin", "Library/Application Support/zen/Profiles/test/cookies.sqlite"), + ("win32", "zen/Profiles/test/cookies.sqlite"), +]) +def test_zen_profile_discovery(monkeypatch, tmp_path, platform, relative) -> None: + monkeypatch.setattr(auth.sys, "platform", platform) + monkeypatch.setattr(auth.os.path, "expanduser", lambda _: str(tmp_path)) + monkeypatch.setenv("APPDATA", str(tmp_path)) + cookie_file = tmp_path / relative + cookie_file.parent.mkdir(parents=True) + cookie_file.touch() + assert auth._iter_zen_cookie_files() == [str(cookie_file)] + + +@pytest.mark.parametrize("subprocess_mode", [False, True]) +def test_zen_extracts_from_later_profile(monkeypatch, subprocess_mode) -> None: + monkeypatch.setenv("TWITTER_BROWSER", " ZEN ") + monkeypatch.setattr(auth, "_iter_zen_cookie_files", lambda: ["empty", "broken", "valid"]) + calls = [] + + def firefox(cookie_file=None): + calls.append(cookie_file) + if cookie_file == "broken": + raise RuntimeError("profile unreadable") + if cookie_file != "valid": + return [] + return [SimpleNamespace(domain=".x.com", name=name, value=value) + for name, value in [("auth_token", "token"), ("ct0", "csrf"), ("extra", "value")]] + + fake_module = SimpleNamespace(firefox=firefox) + for name in ("arc", "chrome", "edge", "brave"): + setattr(fake_module, name, lambda: pytest.fail("Zen should succeed first")) + monkeypatch.setitem(sys.modules, "browser_cookie3", fake_module) + if subprocess_mode: + import contextlib + import io + + def run(cmd, **kwargs): + output = io.StringIO() + with contextlib.redirect_stdout(output), pytest.raises(SystemExit) as exited: + exec(cmd[-1], {}) + assert exited.value.code == 0 + return SimpleNamespace(stdout=output.getvalue(), stderr="") + + monkeypatch.setattr(auth.subprocess, "run", run) + cookies, _ = auth._extract_via_subprocess() + else: + cookies, _ = auth._extract_in_process() + assert calls == ["empty", "broken", "valid"] + assert cookies == {"auth_token": "token", "ct0": "csrf", + "cookie_string": "auth_token=token; ct0=csrf; extra=value"} + + +def test_missing_zen_profiles_does_not_read_firefox(monkeypatch) -> None: + monkeypatch.setenv("TWITTER_BROWSER", "zen") + monkeypatch.setattr(auth, "_DEFAULT_BROWSER_ORDER", ["zen"]) + monkeypatch.setattr(auth, "_iter_zen_cookie_files", lambda: []) + fake_module = SimpleNamespace(**{name: lambda: pytest.fail("No profile should be read") + for name in ("arc", "chrome", "edge", "brave", "firefox")}) + monkeypatch.setitem(sys.modules, "browser_cookie3", fake_module) + assert auth._extract_in_process() == (None, []) + + +@pytest.mark.parametrize("custom_xdg", [False, True]) +def test_zen_prefers_install_default_and_reads_absolute_profiles(monkeypatch, tmp_path, custom_xdg): + monkeypatch.setattr(auth.sys, "platform", "linux") + monkeypatch.setattr(auth.os.path, "expanduser", lambda _: str(tmp_path)) + config_home = tmp_path / ("custom-config" if custom_xdg else ".config") + if custom_xdg: + monkeypatch.setenv("XDG_CONFIG_HOME", str(config_home)) + else: + monkeypatch.delenv("XDG_CONFIG_HOME", raising=False) + root = config_home / "zen" + installed = root / "release" / "cookies.sqlite" + legacy = root / "legacy" / "cookies.sqlite" + external = tmp_path / "external" / "cookies.sqlite" + for path in (installed, legacy, external): + path.parent.mkdir(parents=True, exist_ok=True) + path.touch() + (root / "profiles.ini").write_text( + "[Profile0]\nPath=legacy\nIsRelative=1\nDefault=1\n" + "[Profile1]\nPath=release\nIsRelative=1\n" + f"[Profile2]\nPath={external.parent}\nIsRelative=0\n" + "[InstallExample]\nDefault=release\n" + ) + assert auth._iter_zen_cookie_files() == [str(installed), str(legacy), str(external)] diff --git a/twitter_cli/auth.py b/twitter_cli/auth.py index 81dd44c..8a59e40 100644 --- a/twitter_cli/auth.py +++ b/twitter_cli/auth.py @@ -10,6 +10,7 @@ from __future__ import annotations +import configparser import glob import json import logging @@ -204,7 +205,7 @@ def _extract_cookies_from_jar(jar: Any, source: str = "unknown") -> Optional[Dic } # Default browser order for cookie extraction -_DEFAULT_BROWSER_ORDER = ["arc", "chrome", "edge", "firefox", "brave"] +_DEFAULT_BROWSER_ORDER = ["arc", "chrome", "edge", "firefox", "brave", "zen"] def _get_browser_order() -> List[str]: @@ -212,7 +213,7 @@ def _get_browser_order() -> List[str]: env = os.environ.get("TWITTER_BROWSER", "").strip().lower() if not env: return _DEFAULT_BROWSER_ORDER - if env not in {"arc", "chrome", "edge", "firefox", "brave"}: + if env not in _DEFAULT_BROWSER_ORDER: logger.warning("TWITTER_BROWSER='%s' is invalid, using default order", env) return _DEFAULT_BROWSER_ORDER return [env] + [b for b in _DEFAULT_BROWSER_ORDER if b != env] @@ -269,6 +270,52 @@ def _iter_chrome_cookie_files(browser_name: str) -> List[str]: return paths +def _iter_zen_cookie_files() -> List[str]: + """Discover Zen profiles, including both Linux Flatpak profile locations.""" + home = os.path.expanduser("~") + if sys.platform == "darwin": + roots = [os.path.join(home, "Library", "Application Support", "zen")] + elif sys.platform == "win32": + appdata = os.environ.get("APPDATA") + roots = [os.path.join(appdata, "zen")] if appdata else [] + else: + roots = [ + os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.join(home, ".config"), "zen"), + os.path.join(home, ".zen"), + os.path.join(home, ".var", "app", "app.zen_browser.zen", "zen"), + os.path.join(home, ".var", "app", "app.zen_browser.zen", ".zen"), + ] + paths: List[str] = [] + for root in roots: + config = configparser.ConfigParser(interpolation=None) + try: + config.read(os.path.join(root, "profiles.ini"), encoding="utf-8") + except (configparser.Error, OSError, UnicodeError) as exc: + logger.debug("Could not read Zen profiles.ini at %s: %s", root, exc) + config = configparser.ConfigParser(interpolation=None) + # Like Firefox, prefer the install default over the legacy Default=1 profile. + defaults = [config[section].get("Default", "") for section in config.sections() + if section.startswith("Install")] + profiles = [config[section] for section in config.sections() + if section.startswith("Profile") and config[section].get("Path")] + profiles.sort(key=lambda profile: ( + profile["Path"] not in defaults, profile.get("Default") != "1" + )) + candidates = [] + for profile in profiles: + directory = profile["Path"] + if profile.get("IsRelative", "1") != "0": + directory = os.path.join(root, directory) + candidates.append(os.path.join(directory, "cookies.sqlite")) + # Retain discovery for installations without a readable profiles.ini. + for pattern in ("*/cookies.sqlite", "Profiles/*/cookies.sqlite"): + candidates.extend(sorted(glob.glob(os.path.join(root, pattern)))) + for path in candidates: + if os.path.isfile(path) and path not in paths: + paths.append(path) + return paths + + def _extract_in_process() -> Tuple[Optional[Dict[str, str]], List[str]]: """Extract cookies in the main process (required on macOS for Keychain access). @@ -291,6 +338,7 @@ def _extract_in_process() -> Tuple[Optional[Dict[str, str]], List[str]]: "chrome": browser_cookie3.chrome, "edge": browser_cookie3.edge, "firefox": browser_cookie3.firefox, + "zen": browser_cookie3.firefox, "brave": browser_cookie3.brave, } attempts: List[str] = [] @@ -298,9 +346,13 @@ def _extract_in_process() -> Tuple[Optional[Dict[str, str]], List[str]]: for name in _get_browser_order(): fn = browser_fns[name] - if name in _CHROMIUM_BASE_DIRS: - # Chromium-based: iterate all profiles - cookie_files = _iter_chrome_cookie_files(name) + if name in _CHROMIUM_BASE_DIRS or name == "zen": + cookie_files = ( + _iter_zen_cookie_files() if name == "zen" else _iter_chrome_cookie_files(name) + ) + if name == "zen" and not cookie_files: + attempts.append("zen=no-profiles") + continue if not cookie_files: # No profile dirs found — try the default (no cookie_file arg) try: @@ -423,9 +475,10 @@ def extract_from_jar(jar, name, profile=""): return result return None -DEFAULT_ORDER = ["arc", "chrome", "edge", "firefox", "brave"] +ZEN_COOKIE_FILES = __ZEN_COOKIE_FILES__ +DEFAULT_ORDER = ["arc", "chrome", "edge", "firefox", "brave", "zen"] env_browser = os.environ.get("TWITTER_BROWSER", "").strip().lower() -if env_browser in {"arc", "chrome", "edge", "firefox", "brave"}: +if env_browser in DEFAULT_ORDER: browser_order = [env_browser] + [b for b in DEFAULT_ORDER if b != env_browser] else: browser_order = DEFAULT_ORDER @@ -434,14 +487,18 @@ def extract_from_jar(jar, name, profile=""): "chrome": browser_cookie3.chrome, "edge": browser_cookie3.edge, "firefox": browser_cookie3.firefox, + "zen": browser_cookie3.firefox, "brave": browser_cookie3.brave, } attempts = [] for name in browser_order: fn = browser_fns[name] - if name in CHROMIUM_BASE_DIRS: - cookie_files = iter_cookie_files(name) + if name in CHROMIUM_BASE_DIRS or name == "zen": + cookie_files = ZEN_COOKIE_FILES if name == "zen" else iter_cookie_files(name) + if name == "zen" and not cookie_files: + attempts.append("zen=no-profiles") + continue if not cookie_files: try: jar = fn() @@ -484,6 +541,8 @@ def extract_from_jar(jar, name, profile=""): })) sys.exit(1) ''' + # Pass discovery results so the standalone fallback uses the same profile paths. + extract_script = extract_script.replace("__ZEN_COOKIE_FILES__", repr(_iter_zen_cookie_files())) diagnostics: List[str] = [] @@ -614,7 +673,7 @@ def get_cookies() -> Dict[str, str]: lines.extend(" " + line for line in hint.splitlines()) lines.append("") lines.append("Option 1: Set TWITTER_AUTH_TOKEN and TWITTER_CT0 environment variables") - lines.append("Option 2: Make sure you are logged into x.com in your browser (Arc/Chrome/Edge/Firefox/Brave)") + lines.append("Option 2: Make sure you are logged into x.com in your browser (Arc/Chrome/Edge/Firefox/Brave/Zen)") lines.append("") lines.append("Run 'twitter -v ' for debug diagnostics.") raise AuthenticationError("\n".join(lines))