DEV Community

Wasabi
Wasabi

Posted on Originally published at wasabihu.github.io

Zero-Dependency Multi-Profile AI Browser Isolation in 1.18 MiB of Rust: Per-Context Proxy Guards, 42 MiB Moli Pools, and 2-Phase Human Handoff

Single-state headless browser setups work fine until your agents need multiple isolated accounts, per-profile proxy routing, external Python/CLI CDP orchestration, or a clean escape hatch when headless runs hit interactive SSO / 2FA walls.

Once you cross that line in production, four systems problems show up immediately:

  1. Shared state & prompt-injection proxy exfiltration: If all sessions share one storageState file—or if an MCP tool accepts arbitrary proxyServer URLs straight from LLM parameters—a single prompt-injected webpage can trick an agent into routing authenticated requests through an attacker-controlled proxy.
  2. Single-process FD_SETSIZE=1024 ceiling: During high-density probing on lightweight headless engines (see moli #3803), pushing a single moli process beyond 60 concurrent BrowserContexts pushed open file descriptors past 1,024 (1,063 observed via lsof), triggering net::ERR_CONNECTION_REFUSED on subsequent navigations.
  3. Shared-port CDP cross-session visibility: Even when browser contexts are state-isolated inside one Chromium daemon, exposing /json/list on a shared port lets external worker A inspect and attach to worker B's targets.
  4. Headless dead-ends on human-only verification: Complex MFA, device-bound SSO, and interactive checks cannot run headlessly—yet attaching directly to the user's daily Chrome profile breaks focus and mixes credentials.

In sessfork v0.4.1, we solved all four inside our 1,233,344-byte (~1.18 MiB) pure-std Rust binary with zero new Rust crates and zero Python runtime dependencies: named Profile Vaults with per-context proxy leak guards (P0-1), a loopback process-isolated CDP orchestrator (serve-api, P0-2), and a 2-phase non-blocking human takeover tool (browser_handoff, P0-3).


1. Ground-Truth CDP Engine Probes (moli 1.1.29 & Chromium)

Before writing isolation layers, we ran paired positive/negative CDP probes against moli 1.1.29 (over anonymous pipe FDs 3/4 --remote-debugging-pipe) and local Chromium (--cdp-url):

CDP Probe Observed Behavior (moli 1.1.29 / Chromium) Design Takeaway
createBrowserContext (proxyServer, bypass) Returns isolated browserContextId; parallel contexts hit only their own proxy (PROXY_HIT) Per-context proxy isolation works natively inside one engine process
Dead proxy (http / socks5 closed port) Immediately fails with ERR_CONNECTION_REFUSED (no silent direct fallback) Paired with preflight TCP checks, prevents accidental IP leakage
Invalid scheme (ftp://127.0.0.1:8080) createBrowserContext succeeds; navigation later fails (ERR_FAILED) Rust must validate schemes upfront via ProxySpec before context spawn
Emulation.*Override (TZ / Locale / UA / Geo) All return {}; timeZone & navigator.language update to America/New_York / en-US Apply deterministic timezone/locale/geo overrides on every attached tab

2. P0-1: Named Profile Vaults & Anti-Exfiltration Proxy Guards

Implemented across profile.rs, proxy.rs, and profiles.py, named vaults preserve 100% compatibility with ~/.sessfork/state.json while adding strict boundaries:

  • Pre-canonicalize symlink & permission checks (~/.sessfork/profiles/<name>/): Vault names enforce ^[a-z0-9][a-z0-9_-]{0,47}$ (blocking default, .., and hidden names). Both Rust and Python check for symlinks before resolving paths and write via O_NOFOLLOW + 0600 atomic rename.
  • No arbitrary MCP proxyServer arguments: browser_tabs rejects proxyServer, proxy, and proxyBypassList parameters outright. Only local 0600 pre-registered profile names are accepted, and named contexts hydrate only their own vault's state.json—never leaking default credentials into a proxied context.
  • Zero proxy passwords in ps aux: Authenticated proxies (http://user:pass@host:port) are parsed into ProxySpec, stripped of userinfo@ in every CLI argument, log line, and error receipt, and answered in memory via CDP Fetch.enable({ handleAuthRequests: true }) / Fetch.authRequired.
  • Two-stage preflight guard + zero default telemetry + --ephemeral: With requireProxy: true (default), a 3s loopback-safe TCP probe verifies proxy reachability before any context spawns. Optional outlet verification (preflightUrl / expectedCountry) executes only when explicitly configured (zero background telemetry by default). --ephemeral vaults keep auth state strictly in memory and never write state.json to disk.
# Create an ephemeral US vault with proxy + timezone/locale alignment
sessfork profile create us-qa \
  --domains example.com \
  --proxy socks5h://127.0.0.1:1080 \
  --timezone America/New_York \
  --locale en-US \
  --ephemeral

# Or fork specific domains from your active Chrome profile into a named vault
# (uses --vault so existing -p / --profile stays orthogonal for Chrome source directories)
sessfork github.com --vault work -p "Profile 4"
Enter fullscreen mode Exit fullscreen mode

3. P0-2: serve-api — A 3.1 MiB Pure-std Orchestrator for 42.2 MiB Isolated CDP Sessions

To bypass single-process FD limits and prevent one external worker from inspecting another worker's CDP targets on a shared port, sessfork-mcp serve-api (api_server.rs) acts as a lightweight OS-process orchestrator:

  • Loopback-only HTTP/1.1 with CSPRNG Bearer auth: Binds strictly to 127.0.0.1, generates a 0600 256-bit token (/dev/urandom on Unix, SystemFunction036 on Windows) compared in constant time, enforces strict Host / Origin / Sec-Fetch-Site anti-DNS-rebinding checks, and caps headers (16 KiB) and bodies (64 KiB).
  • One active process per profile + zero secret-read endpoints: Starting the same profile twice returns 409 Conflict with the owning activeSessionId. Routes like /cookies or /state are deliberately omitted. Every child moli or chrome-headless-shell process is reaped via Unix killpg or Win32 Job Objects when stopped or on SIGTERM.
  • Headerless standard CDP attach for external frameworks: Because each session returns a dedicated cdpWsUrl bound only to that profile's child process, zero-dependency Python api_client.py passes sess.cdp_ws_url straight into Playwright, browser-use (Browser(cdp_url=sess.cdp_ws_url)), or agent-browser --cdp ... without requiring custom WebSocket auth headers.
from sessfork.api_client import open_profile_session

# Start daemon once: sessfork-mcp serve-api --port 7331
with open_profile_session(
    "work",
    base_url="http://127.0.0.1:7331",
    engine="moli",  # or "chrome" when full WebGL/Blink fidelity is needed
) as sess:
    # Hand sess.cdp_ws_url directly to Playwright connect_over_cdp
    # or browser-use Browser(cdp_url=sess.cdp_ws_url)
    print("Isolated CDP endpoint:", sess.cdp_ws_url, sess.timezone, sess.locale)
# Context exit automatically calls /stop and reaps the child process (0 orphans)
Enter fullscreen mode Exit fullscreen mode

Measured on macOS 26.6.2 (Apple Silicon arm64) running sessfork-mcp 0.4.1 and 8 simultaneous process-isolated moli 1.1.29 sessions with distinct timezones/locales and seeded cookies (reproducible harness documented in docs/benchmarks.md):

Metric (serve-api --max-sessions 16, 8 Isolated moli 1.1.29 Processes) Measured Result
Cold serve-api ready latency 8.7 ms (includes 0600 256-bit token generation & JSON ready signal)
Per-session start latency (p50 / mean / max) 43.8 ms / 76.0 ms / 222.1 ms (process spawn + cookie hydration + Emulation.* overrides)
serve-api daemon RSS 3.1 MiB
Total stack RSS (daemon + 8 isolated moli processes) 340.9 MiB (42.2 MiB / session avg)
Cross-session CDP & timezone verification 8 / 8 PASS (0 cross-profile leaks)
Orphan processes after SIGTERM 0

4. P0-3: Non-Blocking Headless ↔ Headed Synergy (browser_handoff)

Even when --compact --diff slashes cumulative LLM input tokens by -85.4%, automated flows still hit interactive MFA, passkeys, or human verification walls. Rather than touching CAPTCHA-bypass tooling, sessfork adds MCP tool #20 browser_handoff (start / status / complete / cancel):

  1. start: Captures domain-scoped cookies and live headless isolated-world window.localStorage (preserving in-flight OAuth PKCE code_verifier / CSRF state), writes them into an isolated 0700 --user-data-dir, and pops a desktop Chromium window (1,374.0 ms measured on real macOS Chrome --new-window) without touching your daily Chrome profile.
  2. Non-blocking human interaction: Enforces MAX_ACTIVE_HANDOFFS=1, 2s start cooldown, and bounded timeouts (60..=3600s, default 600s).
  3. complete: Extracts cookies and isolated-world localStorage back into the headless context, strictly filtering to {start_host, end_host} ∪ allowDomains (dropping third-party tracking cookies), optionally persisting 0600 state.json, destroying the temporary 0700 directory, and returning domain counts only (0 raw secrets in MCP replies).

5. Four Real Bugs Caught Before Tagging v0.4.1

Adversarial diff review, scripts/security_verify.py (D1..D13), and the 3-OS release matrix caught four subtle defects before shipping (20fbb38, 06de95f):

  1. Missing on-disk profile.json load validation: create paths rejected malformed domains and unsupported encryption values, whereas load paths in profile.rs and profiles.py trusted existing disk fields. Both now enforce schemaVersion == 1, encryption == "none", valid engine, and public-suffix domain rejection on load.
  2. Duplicate killpg on Drop after explicit cleanup: Added an idempotent terminated: bool guard to ActiveHandoff and ManagedApiSession so explicit cleanup()/wait() prevents Drop from issuing a second libc::killpg.
  3. OAuth PKCE localStorage loss during handoff start: Headless SPAs often store OAuth state or PKCE verifiers in window.localStorage before redirecting to an IdP. Forwarding live headless localStorage into the headed window fixed redirect validation failures (pkce_carried=True asserted in D13.2).
  4. API URL path injection & Windows MSVC Clippy -D warnings errors: Added _clean_profile_ref / _clean_session_id slug guards in SessforkApiClient, and scoped Unix /dev/urandom & cache probe code in api_server.rs cleanly under #[cfg(unix)] alongside a SystemFunction036 Windows CSPRNG path.

6. Verification Matrix & Honest Boundaries

  • Footprint: 1,233,344 bytes (~1.18 MiB) stripped Rust binary; 0 new Rust crates; 0 Python dependencies.
  • Automated Suites: 73 / 73 Rust unit tests (cargo test --locked --all-targets), 0 clippy -- -D warnings issues across macOS/Linux/Windows, 66 / 66 Python unittest cases, and 29 / 29 PASS across all 13 security boundaries (D1..D13 in docs/security-report.md).
  • Known Trade-offs:
    • moli trades ~80.7% Lexbench compatibility against Chrome's 99.9% for extreme memory density; use --engine dual or engine="chrome" in serve-api whenever WebGL, complex Canvas, or full Blink fidelity is required.
    • Sites enforcing strict single-use refresh token rotation can invalidate another active browser session if both refresh concurrently; keep those logins isolated inside a dedicated named vault via browser_handoff.
# Install sessfork + native Rust sessfork-mcp (v0.4.1)
curl --proto '=https' --tlsv1.2 -fsSL \
  https://raw.githubusercontent.com/wasabihu/sessfork/v0.4.1/install.sh \
  | bash -s -- --with-rust-mcp

# Or install the standalone Rust binary via Homebrew
brew install wasabihu/tap/sessfork-mcp
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
metareignity-com profile image
Metareignity •

Especially the separation between browser-context isolation and process-level CDP isolation. The proxy preflight checks and explicit handling of human handoff are thoughtful additions.

One question: how do you handle resource contention or shared limits across multiple isolated profiles when several agents are executing concurrently? Is that managed at the orchestrator level, or does each profile operate independently?

Collapse
 
wasabi_hu_d2b4b4d9b9f6bda profile image
Wasabi •

Great question — we deliberately split it across two layers so sessfork-mcp stays a small primitive while still preventing runaway hosts:

  1. Per-profile process isolation + single-lease guard: Each active named profile in serve-api spawns its own dedicated moli child process, and active_by_profile enforces a single active lease per profile name so concurrent agents can't race on the same profile vault (this also sidesteps hitting a single process's FD_SETSIZE = 1,024 wall under heavy concurrency).
  2. Bounded daemon-level caps + idle reaping inside serve-api: SessionRegistry enforces hard local guardrails — --max-sessions (default 16, capped at 64), MAX_CONCURRENT_HTTP_HANDLERS = 16, bounded HTTP/CDP I/O timeouts (5s / 15s), and an automatic idle reaper (--idle-timeout-secs, default 300s) that tracks activity/load sequences and cleans up idle browser processes (backed by Unix process groups / Win32 Job Objects for zero orphans).
  3. Outer orchestrator responsibility: Host-level CPU/RAM quotas (cgroups/containers), target-site rate limits, and multi-host job queuing stay in the orchestrator layer rather than bloating the ~1.18 MiB MCP binary.