How Agent Reach Securely Stores and Manages Cookies for Twitter and Xiaohongshu
Agent Reach stores authentication cookies in owner-only files (mode 0600) with atomic writes, extracting Twitter data automatically from Chromium browsers while requiring manual Cookie-Editor exports for Xiaohongshu.
Agent Reach is an open-source automation framework that handles social media credential management with a security-first design. This article examines how the codebase extracts, validates, and persists cookies for Twitter/X and Xiaohongshu (XHS), with specific attention to file permissions, domain validation, and platform-specific extraction policies. All implementation details are drawn directly from the Panniantong/Agent-Reach source code.
Cookie Extraction Architecture
Agent Reach centralizes cookie handling in [agent_reach/cookie_extract.py](/blob/main/agent_reach/cookie_extract.py). The module distinguishes between automatic browser extraction and manual import workflows, enforcing strict security boundaries for each.
Platform Specifications Define Extraction Rules
The PLATFORM_SPECS dictionary controls which cookies are extracted per platform:
# From agent_reach/cookie_extract.py lines 32-45
PLATFORM_SPECS = {
"twitter": {
"required_cookies": ["auth_token", "ct0"],
"domains": [".twitter.com", ".x.com"],
"browser_extractable": True,
},
"xiaohongshu": {
"required_cookies": ["web_session", "a1", "webId"],
"domains": [".xiaohongshu.com"],
"browser_extractable": False, # Manual only
},
}
Twitter supports automatic extraction from Chrome, Edge, Brave, or Opera via the rookiepy or browser-cookie3 libraries. Xiaohongshu is explicitly marked non-extractable, forcing users through a manual export flow.
Why Xiaohongshu Requires Manual Export
The _COOKIE_EDITOR_ONLY set enforces this restriction:
_COOKIE_EDITOR_ONLY = {"xiaohongshu"}
When _require_browser_extractable() encounters a platform in this set, it raises:
raise ValueError(
f"Platform '{platform}' requires manual cookie export via Cookie-Editor extension. "
f"Automatic browser extraction is disabled for security compliance."
)
This design prevents accidental credential leakage through browser automation on platforms with stricter anti-bot measures.
Secure Storage Implementation
Atomic Writes with Strict Permissions
All cookie files are persisted through atomic_write_private_text(), which guarantees owner-only access (mode 0600). The implementation in [agent_reach/utils/paths.py](/blob/main/agent_reach/utils/paths.py) follows this pattern:
- Create parent directory with
0700permissions viamake_private_dir() - Write to a temporary file in the same directory
fsync()to ensure data reaches disk- Atomic rename to final path
- Explicit
chmod 0600on the result
Twitter: Multi-Destination Sync with Fail-Safe Behavior
The extract_all() function handles Twitter extraction and propagates credentials to legacy compatibility layers:
def extract_all(browser: str = "chrome", platform: str = None) -> dict:
"""Extract cookies for specified platform from browser database."""
spec = _platform_spec(platform)
cookies = _extract_from_browser(browser, spec)
# Domain validation before return
for name, value in cookies.items():
if not _domain_matches(value["domain"], spec["domains"]):
raise SecurityError(f"Cookie '{name}' domain mismatch")
return {platform: _sanitize_for_storage(cookies)}
Post-extraction, _sync_xfetch_session() and _sync_bird_env() write to:
~/.config/xfetch/session.json— XFetch legacy compatibility~/.config/bird/credentials.env— Bird tool compatibility
Both sync operations use atomic_write_private_text() and fail silently (lines 73-77 and 104-107), ensuring the primary Agent Reach configuration remains intact even if legacy directories are inaccessible.
Xiaohongshu: CLI-Managed Manual Import
For XHS, users run the dedicated CLI command handled in [agent_reach/cli.py](/blob/main/agent_reach/cli.py) around line 1308:
agent-reach configure xhs-cookies '{"web_session":"abc123","a1":"def456","webId":"xyz789"}'
The CLI validates JSON structure, then writes to:
from pathlib import Path
from agent_reach.utils.paths import atomic_write_private_text
xhs_path = Path.home() / ".agent-reach" / "xhs-cookies.json"
atomic_write_private_text(xhs_path, json.dumps(validated_cookies))
Resulting file permissions:
$ ls -la ~/.agent-reach/xhs-cookies.json
-rw------- 1 user user 156 Jan 15 09:23 xhs-cookies.json
Domain Validation and Least-Privilege Design
Explicit Platform Targeting
The extract_all() function requires an explicit platform argument. No default fallback exists—callers must intentionally specify "twitter", "xiaohongshu", or another supported platform. This prevents accidental extraction of unrelated session data.
Post-Extraction Domain Verification
Even after browser library retrieval, each cookie undergoes domain_matches() validation:
def domain_matches(cookie_domain: str, allowed_domains: list) -> bool:
"""Verify cookie domain is within allowed set."""
cookie_domain = cookie_domain.lstrip(".")
return any(
cookie_domain == allowed.lstrip(".") or
cookie_domain.endswith(allowed)
for allowed in allowed_domains
)
This blocks supply-chain attacks where a compromised browser extension or malicious local process might inject cookies for unrelated domains into the extraction results.
Channel Integration: How Cookies Are Consumed
Twitter Channel ([agent_reach/channels/twitter.py](/blob/main/agent_reach/channels/twitter.py))
The Twitter channel retrieves stored credentials from the synced locations or direct config:
from agent_reach.cookie_extract import get_credentials
def authenticate_request(self):
creds = get_credentials("twitter")
headers = {
"authorization": f"Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4p{self._bearer_suffix}",
"x-csrf-token": creds["ct0"],
"Cookie": f"auth_token={creds['auth_token']}; ct0={creds['ct0']}"
}
return headers
Xiaohongshu Channel ([agent_reach/channels/xiaohongshu.py](/blob/main/agent_reach/channels/xiaohongshu.py))
The XHS channel loads from the manually-managed JSON file:
import json
from pathlib import Path
def load_session(self):
cookie_path = Path.home() / ".agent-reach" / "xhs-cookies.json"
if not cookie_path.exists():
raise ConfigurationError(
"XHS cookies not configured. Run: agent-reach configure xhs-cookies"
)
with open(cookie_path, 'r', encoding='utf-8') as f:
self._cookies = json.load(f)
Testing Security Guarantees
The repository includes dedicated test coverage for file permissions:
| Test File | Validation Purpose |
|---|---|
[test_private_file_writes.py](/blob/main/tests/unit/test_private_file_writes.py) |
Verifies atomic_write_private_text creates files with mode 0600 |
[test_cookie_extract_perms.py](/blob/main/tests/unit/test_cookie_extract_perms.py) |
Confirms synced cookie files are tightened after creation |
[test_domain_validation.py](/blob/main/tests/unit/test_domain_validation.py) |
Ensures domain_matches rejects invalid cookie domains |
Summary
- Twitter cookies are extracted automatically from Chromium browsers, filtered to only
auth_tokenandct0, validated against.twitter.com/.x.com, and synced to legacy locations with0600permissions. - Xiaohongshu cookies require manual export via Cookie-Editor, enforced by the
_COOKIE_EDITOR_ONLYrestriction, and are stored in~/.agent-reach/xhs-cookies.jsonwith identical permission hardening. - All file writes use
atomic_write_private_textfor atomicity and owner-only access, with0700parent directories. - Domain validation runs post-extraction to prevent cross-site cookie injection.
- Fail-safe behavior ensures legacy sync failures don't corrupt primary configuration.
Frequently Asked Questions
How does Agent Reach prevent other users from reading my Twitter cookies?
Agent Reach calls atomic_write_private_text() which explicitly sets file mode 0600 (owner read/write only) and creates parent directories with 0700. This is tested in [test_private_file_writes.py](/blob/main/tests/unit/test_private_file_writes.py). Even if your home directory is world-readable, the cookie files themselves are inaccessible to other system users.
Why can't I auto-extract Xiaohongshu cookies like Twitter?
Xiaohongshu is listed in _COOKIE_EDITOR_ONLY due to stricter anti-automation measures on the platform. The _require_browser_extractable() function enforces this by raising a ValueError if automatic extraction is attempted, forcing deliberate manual export through the Cookie-Editor browser extension.
What happens if the legacy sync to xfetch or bird fails?
Both _sync_xfetch_session() and _sync_bird_env() wrap file operations in try/except blocks that log warnings but do not propagate errors. Your primary Agent Reach configuration remains the source of truth, ensuring extraction succeeds even when legacy directories are missing or permission-restricted.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →