Security Best Practices for Cookie-Based Platform Authentication in Agent Reach
Agent Reach secures cookie-based authentication by extracting credentials only from closed local browsers, storing them with 0600 file permissions, and never exposing them in logs or stdout.
Agent Reach is an open-source automation framework that authenticates with platforms lacking first-party API keys—such as Twitter/X, XiaoHongShu, Bilibili, and Xueqiu—using browser cookies as session credentials. Because cookies are equivalent to long-lived passwords, the library implements defense-in-depth measures across agent_reach/cookie_extract.py, agent_reach/config.py, and agent_reach/cli.py to minimize exposure and prevent credential leakage.
Extract Cookies Only from Closed Local Browsers
The library treats browser cookies as sensitive secrets that must never be read while the browser process is active. This prevents other processes from intercepting session data during extraction.
Validate Browser State Before Reading
In agent_reach/cookie_extract.py, the extract_all() function validates that the requested browser is one of the supported variants (chrome, firefox, edge, brave, opera). If the browser is unsupported or the user lacks permission, the function raises a ValueError and aborts immediately. This check occurs at lines 71–75, ensuring the extraction process only proceeds in a controlled local environment.
from agent_reach.cookie_extract import configure_from_browser
from agent_reach.config import Config
cfg = Config()
result = configure_from_browser(browser="chrome", config=cfg)
for platform, ok, msg in result:
print(f"{platform}: {'✅' if ok else '❌'} – {msg}")
The function automatically writes the appropriate keys to ~/.agent-reach/config.yaml with 0600 permissions.
Prefer Sandboxed Extraction Libraries
Agent Reach prioritizes the Rust-based rookiepy extractor over the pure-Python browser-cookie3 alternative. The selection logic in extract_all() (lines 55–66) attempts rookiepy first because it runs in a sandboxed binary with reduced attack surface. The fallback to browser-cookie3 only occurs when rookiepy is unavailable, ensuring the most robust isolation path is used by default.
Secure Storage with Restrictive Permissions
Once extracted, cookies are never written to standard output or committed to repositories. Instead, they are persisted using operating-system-level protections that enforce owner-only access.
Configuration File Permissions
The Config.save() method in agent_reach/config.py (lines 52–60) creates the configuration file using os.open with flags stat.S_IRUSR | stat.S_IWUSR. This ensures the file is created with mode 0600 (read/write for owner only), preventing group or world access even during the brief window between file creation and data write.
Legacy Sync File Protection
For legacy tool integration, the _open_owner_only() helper in agent_reach/cookie_extract.py (lines 51–68) opens files with mode 0o600 before writing any credential data. This atomic approach eliminates the race condition where a file might temporarily be world-readable between creation and permission modification.
Prevent Command Injection and Credential Leakage
When writing shell-sourceable files for the legacy bird CLI, the _sync_bird_env function uses shlex.quote to escape cookie values (lines 100–105 of cookie_extract.py). This prevents shell metacharacters in cookie strings from breaking out of their context and executing arbitrary commands when the file is later sourced.
The library also enforces platform-specific storage keys (twitter_auth_token, twitter_ct0, xhs_cookie, bilibili_cookie, xueqiu_cookie) via config.set() calls in configure_from_browser() (lines 45–84). This isolation limits the blast radius of a single compromised credential and simplifies revocation by allowing users to delete individual keys without affecting other platforms.
Operational Safety and User Consent
Graceful Failure Handling
If extraction fails—whether due to an open browser, permission denial, or missing required cookies—the configure_from_browser() function returns a concise error message and does not store partial or malformed credentials (see error handling at lines 33–38 and 52–58). This prevents the accidental persistence of incomplete data that could leak session fragments.
Explicit CLI Flags
Cookie extraction is only triggered when the user explicitly requests it via the --from-browser flag. The CLI entry point in agent_reach/cli.py (lines 272–298) checks needs_cookies against dry_run and safe-mode flags before invoking any import logic. To run without automatic credential extraction:
agent-reach install --env=auto --safe-mode
Because --safe-mode disables automatic cookie extraction, no credential files are created.
Logging Discipline
Agent Reach uses loguru for structured logging at the INFO level by default. The codebase contains no logger statements that output raw cookie strings, ensuring that diagnostic logs or crash reports never contain active session credentials.
Summary
- Validate browser state: The
extract_all()function incookie_extract.pyenforces closed-browser extraction and validates supported browsers (lines 71–75). - Use sandboxed extractors: Prefer
rookiepyoverbrowser-cookie3for reduced attack surface (lines 55–66). - Restrict file permissions: Both
Config.save()and_open_owner_only()enforce 0600 permissions usingos.openwithstat.S_IRUSR | stat.S_IWUSR(config.py lines 52–60, cookie_extract.py lines 51–68). - Sanitize shell output: Cookie values are passed through
shlex.quotebefore writing to environment files (lines 100–105). - Require explicit consent: Cookie import only occurs with
--from-browserand respects--safe-modeand--dry-runflags (cli.py lines 272–298). - Isolate platform keys: Separate configuration keys per platform prevent cross-contamination (lines 45–84).
- Suppress credential logging: No raw cookie values appear in logs or stdout.
Frequently Asked Questions
How does Agent Reach prevent cookies from leaking into process logs or shell history?
Agent Reach never writes raw cookie strings to standard output or logs. The configure_from_browser() function stores credentials immediately via config.set() to ~/.agent-reach/config.yaml, and the CLI only reports success or failure states. Additionally, the logging configuration uses loguru without including credential values in message templates, ensuring that log files and shell history remain free of session tokens.
What happens if I try to extract cookies while the browser is still running?
The extraction will abort with a clear error message. In cookie_extract.py, the extract_all() function validates that the browser is supported and accessible, raising a ValueError if the browser process is active or if the user lacks permissions (lines 71–75). This prevents the library from reading cookies while they might be in use or exposed to other processes.
Can I use Agent Reach without automatically importing browser cookies?
Yes. Run the CLI with the --safe-mode flag to disable automatic cookie extraction. As implemented in agent_reach/cli.py (lines 272–298), safe-mode bypasses the needs_cookies check, preventing any credential files from being created or modified. You can then manually configure credentials or use API keys where available.
How are the configuration files protected from other users on the system?
The Config.save() method in agent_reach/config.py creates files using os.open with stat.S_IRUSR | stat.S_IWUSR flags (lines 52–60), which translates to octal permission 0600. This means only the file owner can read or write the configuration, and group or other users have no access. A similar protection applies to legacy sync files via the _open_owner_only() helper (lines 51–68 of cookie_extract.py).
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 →