How Agent Reach Extracts Cookies from Browsers for Platform Authentication

Agent Reach automatically extracts authentication cookies from Chrome, Firefox, Edge, Brave, or Opera using a dual-backend system in agent_reach/cookie_extract.py, then filters them by platform domain patterns to enable seamless Twitter/X, XiaoHongShu, Bilibili, and Xueqiu login.

The Panniantong/Agent-Reach project simplifies social media automation by eliminating manual cookie copying. Its cookie extraction module handles browser detection, SQLite cookie store reading, and platform-specific filtering in a single workflow. Understanding this process helps developers debug authentication failures and extend support for additional platforms.

Agent Reach prioritizes reliability through a fallback-based backend system. The module attempts to use rookiepy first, a Rust-based library that avoids many platform-specific edge cases. If rookiepy is unavailable, it falls back to browser_cookie3, a pure-Python alternative with broader compatibility but potentially slower performance.

In agent_reach/cookie_extract.py lines 55–62, the import logic appears as:

try:
    import rookiepy
    USE_ROOKIEPY = True
except ImportError:
    import browser_cookie3
    USE_ROOKIEPY = False

Both libraries locate browser profile directories and parse their SQLite cookie stores. The abstraction layer normalizes their outputs into a common _Cookie class with .name, .value, and .domain attributes, ensuring downstream code remains backend-agnostic.

Supported Browsers and Validation

Agent Reach supports five major browsers: Chrome, Firefox, Edge, Brave, and Opera. The extract_all() function validates incoming browser names against this whitelist, raising ValueError for unsupported inputs.

From lines 68–73 in agent_reach/cookie_extract.py:

supported = ["chrome", "firefox", "edge", "brave", "opera"]
browser = browser.lower()
if browser not in supported:
    raise ValueError(f"Unsupported browser: {browser}. Choose from {supported}")

Critical requirement: The target browser must be closed during extraction. Running browsers lock their SQLite cookie stores, causing read failures that surface as RuntimeError with guidance to close the application.

The PLATFORM_SPECS constant (lines 13–38) defines extraction rules for each supported platform:

Platform Domains Target Cookies
Twitter/X .x.com, .twitter.com auth_token, ct0
XiaoHongShu .xiaohongshu.com None (collect all)
Bilibili .bilibili.com SESSDATA, bili_jct
Xueqiu .xueqiu.com None (collect all)

Platforms with None for "cookies" receive header-style serialization: all domain-matching cookies concatenated as "name=value; name2=value2". Named cookie platforms return dictionaries mapping specific keys to values.

The filtering logic (lines 78–92 and 31–44) iterates through the normalized cookie jar:


# Normalization step

raw_cookies = browser_funcs[browser]()
cookie_jar = [_Cookie(c) for c in raw_cookies]

# Platform matching and extraction

for spec in PLATFORM_SPECS:
    matching = [c for c in cookie_jar if any(d in c.domain for d in spec["domains"])]
    if spec["cookies"] is None:
        results[spec["config_key"]] = {
            "cookie_string": "; ".join(f"{c.name}={c.value}" for c in matching)
        }
    else:
        results[spec["config_key"]] = {
            c.name: c.value for c in matching if c.name in spec["cookies"]
        }

Programmatic and CLI Usage Patterns

Direct Python API

Extract cookies from any supported browser:

from agent_reach.cookie_extract import extract_all

cookies = extract_all("chrome")
print(cookies)

# {

#   "twitter": {"auth_token": "...", "ct0": "..."},

#   "xhs": {"cookie_string": "sessionid=...; other=..."},

#   "bilibili": {"SESSDATA": "...", "bili_jct": "..."},

#   "xueqiu": {"cookie_string": "xq_a_token=...; ..."}

# }

Command-Line Configuration

The configure command wraps extraction with persistent storage:

agent-reach configure --from-browser chrome

Output shows per-platform success indicators:


  Twitter/X    ✓  auth_token + ct0
  XiaoHongShu  ✓  3 cookies
  Bilibili     ✓  SESSDATA + bili_jct
  Xueqiu       ✓  5 cookies (含 xq_a_token)

Integration with Config System

For custom tooling, configure_from_browser() handles extraction and persistence:

from agent_reach.config import Config
from agent_reach.cookie_extract import configure_from_browser

cfg = Config()
summary = configure_from_browser("firefox", cfg)
for platform, ok, msg in summary:
    print(f"{platform}: {'✓' if ok else '✗'} {msg}")

This writes discovered credentials to ~/.agent-reach and optionally syncs Twitter credentials to legacy tools (xfetch, bird).

Error Handling and Troubleshooting

Agent Reach provides specific error messages for common failure modes:

  • Missing backends: RuntimeError with installation commands (pip install rookiepy or pip install browser-cookie3)
  • Browser lock conflicts: Instructions to close the browser before retrying
  • Permission denials: Clear indication when OS-level file permissions block profile directory access

The test suite in tests/test_cookie_extract_perms.py verifies correct permission handling, ensuring the code respects security boundaries like owner-only directories.

Key Source Files

File Responsibility
agent_reach/cookie_extract.py Backend selection, cookie normalization, platform filtering, result shaping
agent_reach/config.py Persistent storage of extracted credentials to ~/.agent-reach
tests/test_cookie_extract_perms.py Permission handling and security boundary validation
tests/test_cli.py End-to-end CLI integration verification

Summary

  • Dual-backend design (rookiepy preferred, browser_cookie3 fallback) maximizes cross-platform compatibility in agent_reach/cookie_extract.py
  • Five browsers supported: Chrome, Firefox, Edge, Brave, Opera—all require closed state for SQLite access
  • Platform specs in PLATFORM_SPECS control domain matching and cookie selection (named keys vs. full header strings)
  • Three access patterns: direct extract_all() calls, CLI configure --from-browser, and programmatic configure_from_browser() with Config integration
  • Robust error handling guides users through missing dependencies, locked browsers, and permission issues

Frequently Asked Questions

Agent Reach supports Chrome, Firefox, Edge, Brave, and Opera. The extract_all() function validates browser names against this whitelist in agent_reach/cookie_extract.py lines 68–73. Any other browser name raises ValueError with the supported list.

Browsers lock their SQLite cookie stores with file-level locks while running. Agent Reach's backend libraries (rookiepy or browser_cookie3) cannot read locked databases. The code surfaces this as RuntimeError with explicit guidance to close the browser before retrying.

Yes. Import extract_all from agent_reach.cookie_extract for raw cookie dictionaries, or configure_from_browser for extraction plus persistent storage. Both functions accept a browser name string and return structured platform credentials programmatically.

What happens if neither rookiepy nor browser_cookie3 is installed?

Agent Reach raises RuntimeError with installation instructions for either dependency. The import logic in lines 55–62 attempts rookiepy first, catches ImportError, then attempts browser_cookie3. If both fail, the error message specifies pip install rookiepy or pip install browser-cookie3 as resolutions.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →