| 1 | """agentcookie sidecar reader — an X cookie source for the bird backend. |
| 2 | |
| 3 | ``agentcookie`` is an external, user-installed CLI that can deliver browser |
| 4 | cookies on Linux (where Chrome's SQLite cookie store cannot be decrypted by |
| 5 | this engine's stdlib extractor). This module shells out to it and pulls the |
| 6 | ``auth_token`` + ``ct0`` pair that the bird backend needs. |
| 7 | |
| 8 | Deliberate constraints (see docs/plans/2026-08-31 X plan): |
| 9 | |
| 10 | * **Soft dependency, explicit consent.** Activation requires ``AGENTCOOKIE=on`` |
| 11 | or affirmative ``BROWSER_CONSENT``, plus ``shutil.which("agentcookie")`` |
| 12 | resolving on the agent subprocess PATH. A binary that is absent is not an error. |
| 13 | * **``AGENTCOOKIE=off`` disables it** regardless of PATH. |
| 14 | * **Explicit cookie refusal wins.** ``BROWSER_CONSENT=false`` or |
| 15 | ``FROM_BROWSER=off`` disables this source, even with ``AGENTCOOKIE=on``. |
| 16 | A native ``FROM_BROWSER`` selection alone does not authorize the sidecar. |
| 17 | * We call ``agentcookie cookies --domain .x.com --json`` and parse its stdout. |
| 18 | We never open ``cookies-plain.db`` directly, never import an ``agentcookie`` |
| 19 | Python package, and never add a Python dependency on it. |
| 20 | * Cookie **values are never logged**. Only counts / names are ever emitted. |
| 21 | * First complete pair wins: a lone ``auth_token`` or a lone ``ct0`` is not a |
| 22 | usable result — both must be present. |
| 23 | """ |
| 24 | |
| 25 | from __future__ import annotations |
| 26 | |
| 27 | import json |
| 28 | import os |
| 29 | import shutil |
| 30 | import subprocess |
| 31 | from pathlib import Path |
| 32 | from typing import Any, Dict, List, Optional |
| 33 | |
| 34 | from . import log |
| 35 | |
| 36 | AGENTCOOKIE_BIN = "agentcookie" |
| 37 | X_COOKIE_DOMAIN = ".x.com" |
| 38 | X_COOKIE_NAMES = ("auth_token", "ct0") |
| 39 | |
| 40 | # agentcookie writes its config (including its role: "source" or "sink") here. |
| 41 | # A SINK receives cookies delivered from another machine; on Darwin, a sink is |
| 42 | # an "extra host" that gets the extra cookie lookups even though it is not a |
| 43 | # Mac mini. Reading this file is a plain filesystem read — NEVER a subprocess — |
| 44 | # so a MacBook (source/unknown role) never spawns agentcookie just to be |
| 45 | # classified (see the AE8 no-subprocess contract). Override the path for tests |
| 46 | # or non-default installs with AGENTCOOKIE_CONFIG. |
| 47 | _DEFAULT_CONFIG_PATH = Path.home() / ".config" / "agentcookie" / "config.json" |
| 48 | |
| 49 | # The sidecar read shells out to another process; keep it bounded so a hung |
| 50 | # agentcookie never stalls config loading. |
| 51 | _TIMEOUT_SECONDS = 10 |
| 52 | |
| 53 | |
| 54 | def _log(msg: str) -> None: |
| 55 | log.source_log("agentcookie", msg, tty_only=False) |
| 56 | |
| 57 | |
| 58 | def _has_pinned_browser_selection(from_browser: Any) -> bool: |
| 59 | """True when FROM_BROWSER pins specific browser(s) rather than unset/'auto'/'off'.""" |
| 60 | value = str(from_browser or "").strip().lower() |
| 61 | return bool(value) and value not in {"auto", "off"} |
| 62 | |
| 63 | |
| 64 | def is_disabled(config: Optional[Dict[str, Any]] = None) -> bool: |
| 65 | """True when sidecar consent is absent, explicitly refused, or bypassed by a browser pin.""" |
| 66 | from . import env |
| 67 | |
| 68 | env_consent = { |
| 69 | name: env.read_secret_env(name) |
| 70 | for name in ("BROWSER_CONSENT", "FROM_BROWSER") |
| 71 | } |
| 72 | # Explicit refusal in either config or process environment always vetoes the sidecar. |
| 73 | if env.cookie_access_denied(env_consent): |
| 74 | return True |
| 75 | if config is not None and env.cookie_access_denied(config): |
| 76 | return True |
| 77 | |
| 78 | env_setting = str(env.read_secret_env("AGENTCOOKIE") or "").strip().lower() |
| 79 | cfg_setting = ( |
| 80 | str(config.get("AGENTCOOKIE") or "").strip().lower() |
| 81 | if config is not None |
| 82 | else "" |
| 83 | ) |
| 84 | if env_setting == "off" or cfg_setting == "off": |
| 85 | return True |
| 86 | |
| 87 | if config is not None: |
| 88 | setting = cfg_setting or env_setting |
| 89 | consent = ( |
| 90 | config["BROWSER_CONSENT"] |
| 91 | if config.get("BROWSER_CONSENT") is not None |
| 92 | else env_consent["BROWSER_CONSENT"] |
| 93 | ) |
| 94 | from_browser = ( |
| 95 | config.get("FROM_BROWSER") |
| 96 | if (config.get("FROM_BROWSER") or "").strip() |
| 97 | else env_consent["FROM_BROWSER"] |
| 98 | ) |
| 99 | else: |
| 100 | setting = env_setting |
| 101 | consent = env_consent["BROWSER_CONSENT"] |
| 102 | from_browser = env_consent["FROM_BROWSER"] |
| 103 | |
| 104 | if setting == "on": |
| 105 | return False |
| 106 | # Do not auto-enable the sidecar ahead of an explicit browser pin unless |
| 107 | # the user explicitly opted into AGENTCOOKIE=on. |
| 108 | if _has_pinned_browser_selection(from_browser): |
| 109 | return True |
| 110 | # Host eligibility and binary presence are not permission to read cookies. |
| 111 | # Keep prediction and acquisition behind this same positive admission gate. |
| 112 | return not env._truthy(consent) |
| 113 | |
| 114 | |
| 115 | def is_available(config: Optional[Dict[str, Any]] = None) -> bool: |
| 116 | """True when the sidecar could be used: consented, on PATH, not refused. |
| 117 | |
| 118 | PATH-only, side-effect free (no subprocess). Safe for the doctor / |
| 119 | preflight prediction path — it reads no cookies, only whether the binary |
| 120 | would be reachable at run time. |
| 121 | """ |
| 122 | if is_disabled(config): |
| 123 | return False |
| 124 | return shutil.which(AGENTCOOKIE_BIN) is not None |
| 125 | |
| 126 | |
| 127 | def _config_path(config: Optional[Dict[str, Any]] = None) -> Path: |
| 128 | """Path to agentcookie's config file (AGENTCOOKIE_CONFIG override wins).""" |
| 129 | override = "" |
| 130 | if config is not None: |
| 131 | override = config.get("AGENTCOOKIE_CONFIG") or "" |
| 132 | override = override or os.environ.get("AGENTCOOKIE_CONFIG") or "" |
| 133 | return Path(override) if override else _DEFAULT_CONFIG_PATH |
| 134 | |
| 135 | |
| 136 | def role(config: Optional[Dict[str, Any]] = None) -> Optional[str]: |
| 137 | """agentcookie's configured role ("source"/"sink"), or None. |
| 138 | |
| 139 | Reads and parses the config FILE only — no subprocess, so it is safe on a |
| 140 | MacBook that must not spawn agentcookie. Any failure (missing file, bad |
| 141 | JSON, no ``role`` key, wrong type) returns None. "parse failure = not sink". |
| 142 | """ |
| 143 | path = _config_path(config) |
| 144 | try: |
| 145 | data = json.loads(path.read_text(encoding="utf-8")) |
| 146 | except (OSError, ValueError): |
| 147 | return None |
| 148 | if not isinstance(data, dict): |
| 149 | return None |
| 150 | raw = data.get("role") |
| 151 | return raw.strip().lower() if isinstance(raw, str) else None |
| 152 | |
| 153 | |
| 154 | def role_is_sink(config: Optional[Dict[str, Any]] = None) -> bool: |
| 155 | """True only when agentcookie's configured role parses as ``sink``.""" |
| 156 | return role(config) == "sink" |
| 157 | |
| 158 | |
| 159 | def _consume_cookie_list(items: List[Any], names: tuple, found: Dict[str, str]) -> None: |
| 160 | """Collect ``name -> value`` for wanted cookie names from a cookie list.""" |
| 161 | for item in items: |
| 162 | if not isinstance(item, dict): |
| 163 | continue |
| 164 | name = item.get("name") |
| 165 | value = item.get("value") |
| 166 | if name in names and isinstance(value, str) and value and name not in found: |
| 167 | found[name] = value |
| 168 | |
| 169 | |
| 170 | def _pair_from_json(data: Any, names: tuple) -> Dict[str, str]: |
| 171 | """Extract wanted cookies from agentcookie JSON, tolerant of its shape. |
| 172 | |
| 173 | Accepts a list of ``{"name","value",...}`` objects, a ``{"cookies": [...]}`` |
| 174 | wrapper, or a flat ``{name: value}`` / ``{name: {"value": ...}}`` mapping. |
| 175 | """ |
| 176 | found: Dict[str, str] = {} |
| 177 | if isinstance(data, list): |
| 178 | _consume_cookie_list(data, names, found) |
| 179 | elif isinstance(data, dict): |
| 180 | cookies = data.get("cookies") |
| 181 | if isinstance(cookies, list): |
| 182 | _consume_cookie_list(cookies, names, found) |
| 183 | else: |
| 184 | for name in names: |
| 185 | raw = data.get(name) |
| 186 | if isinstance(raw, str) and raw: |
| 187 | found[name] = raw |
| 188 | elif isinstance(raw, dict) and isinstance(raw.get("value"), str) and raw["value"]: |
| 189 | found[name] = raw["value"] |
| 190 | return found |
| 191 | |
| 192 | |
| 193 | def read_x_cookies(config: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, str]]: |
| 194 | """Return the complete X cookie pair from agentcookie, or None. |
| 195 | |
| 196 | Returns ``{"auth_token": ..., "ct0": ...}`` only when BOTH cookies are |
| 197 | present (no half-pair). Any failure (binary absent, disabled, non-zero |
| 198 | exit, unparsable JSON, timeout, incomplete pair) returns None so the |
| 199 | caller falls through to the next cookie source. Never raises. |
| 200 | """ |
| 201 | if is_disabled(config): |
| 202 | return None |
| 203 | binary = shutil.which(AGENTCOOKIE_BIN) |
| 204 | if binary is None: |
| 205 | return None |
| 206 | |
| 207 | try: |
| 208 | result = subprocess.run( |
| 209 | [binary, "cookies", "--domain", X_COOKIE_DOMAIN, "--json"], |
| 210 | capture_output=True, |
| 211 | text=True, |
| 212 | timeout=_TIMEOUT_SECONDS, |
| 213 | ) |
| 214 | except subprocess.TimeoutExpired: |
| 215 | _log(f"timed out after {_TIMEOUT_SECONDS}s; skipping") |
| 216 | return None |
| 217 | except OSError as exc: |
| 218 | _log(f"could not run agentcookie: {type(exc).__name__}") |
| 219 | return None |
| 220 | |
| 221 | if result.returncode != 0: |
| 222 | # stderr may carry a reason; do not echo it (it can contain values). |
| 223 | _log(f"exited {result.returncode}; skipping") |
| 224 | return None |
| 225 | |
| 226 | output = (result.stdout or "").strip() |
| 227 | if not output: |
| 228 | return None |
| 229 | try: |
| 230 | data = json.loads(output) |
| 231 | except json.JSONDecodeError: |
| 232 | _log("returned non-JSON output; skipping") |
| 233 | return None |
| 234 | |
| 235 | found = _pair_from_json(data, X_COOKIE_NAMES) |
| 236 | if all(name in found for name in X_COOKIE_NAMES): |
| 237 | _log(f"delivered a complete X cookie pair ({len(found)} of {len(X_COOKIE_NAMES)} names)") |
| 238 | return {name: found[name] for name in X_COOKIE_NAMES} |
| 239 | if found: |
| 240 | _log(f"returned an incomplete pair ({sorted(found)}); ignoring per no-half-pair rule") |
| 241 | return None |
| 242 |