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
How sessfork v0.4.1 packs named Profile Vaults, prompt-injection-safe per-context proxy leak guards, a 3.1 MiB loopback CDP process orchestrator (42.2 MiB/session across 8 isolated Moli instances), and 2-phase headless-to-headed browser_handoff into a zero-Tokio Rust binary.
🌐 阅读中文版本 →On this page
- 1. Ground-Truth CDP Engine Probes (moli 1.1.29 & Chromium)
- 2. P0-1: Named Profile Vaults & Anti-Exfiltration Proxy Guards
- 3. P0-2: serve-api — A 3.1 MiB Pure-std Orchestrator for 42.2 MiB Isolated CDP Sessions
- 4. P0-3: Non-Blocking Headless ↔ Headed Synergy (browser_handoff)
- 5. Four Real Bugs Caught Before Tagging v0.4.1
- 6. Verification Matrix & Honest Boundaries
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:
- Shared state & prompt-injection proxy exfiltration: If all sessions share one
storageStatefile—or if an MCP tool accepts arbitraryproxyServerURLs straight from LLM parameters—a single prompt-injected webpage can trick an agent into routing authenticated requests through an attacker-controlled proxy. - Single-process
FD_SETSIZE=1024ceiling: During high-density probing on lightweight headless engines (see moli #3803), pushing a singlemoliprocess beyond 60 concurrentBrowserContexts pushed open file descriptors past1,024(1,063observed vialsof), triggeringnet::ERR_CONNECTION_REFUSEDon subsequent navigations. - Shared-port CDP cross-session visibility: Even when browser contexts are state-isolated inside one Chromium daemon, exposing
/json/liston a shared port lets external worker A inspect and attach to worker B’s targets. - 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 withERR_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}$(blockingdefault,.., and hidden names). Both Rust and Python check for symlinks before resolving paths and write viaO_NOFOLLOW+0600atomic rename. - No arbitrary MCP
proxyServerarguments:browser_tabsrejectsproxyServer,proxy, andproxyBypassListparameters outright. Only local0600pre-registeredprofilenames are accepted, and named contexts hydrate only their own vault’sstate.json—never leakingdefaultcredentials into a proxied context. - Zero proxy passwords in
ps aux: Authenticated proxies (http://user:pass@host:port) are parsed intoProxySpec, stripped ofuserinfo@in every CLI argument, log line, and error receipt, and answered in memory via CDPFetch.enable({ handleAuthRequests: true })/Fetch.authRequired. - Two-stage preflight guard + zero default telemetry +
--ephemeral: WithrequireProxy: true(default), a3sloopback-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).--ephemeralvaults keep auth state strictly in memory and never writestate.jsonto 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"
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 a0600256-bit token (/dev/urandomon Unix,SystemFunction036on Windows) compared in constant time, enforces strictHost/Origin/Sec-Fetch-Siteanti-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 Conflictwith the owningactiveSessionId. Routes like/cookiesor/stateare deliberately omitted. Every childmoliorchrome-headless-shellprocess is reaped via Unixkillpgor Win32 Job Objects when stopped or onSIGTERM. - Headerless standard CDP attach for external frameworks: Because each session returns a dedicated
cdpWsUrlbound only to that profile’s child process, zero-dependency Pythonapi_client.pypassessess.cdp_ws_urlstraight into Playwright,browser-use(Browser(cdp_url=sess.cdp_ws_url)), oragent-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)
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):
start: Captures domain-scoped cookies and live headless isolated-worldwindow.localStorage(preserving in-flight OAuth PKCEcode_verifier/ CSRF state), writes them into an isolated0700--user-data-dir, and pops a desktop Chromium window (1,374.0 msmeasured on real macOS Chrome--new-window) without touching your daily Chrome profile.- Non-blocking human interaction: Enforces
MAX_ACTIVE_HANDOFFS=1,2sstart cooldown, and bounded timeouts (60..=3600s, default600s). complete: Extracts cookies and isolated-worldlocalStorageback into the headless context, strictly filtering to{start_host, end_host} ∪ allowDomains(dropping third-party tracking cookies), optionally persisting0600state.json, destroying the temporary0700directory, and returning domain counts only (0raw 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):
- Missing on-disk
profile.jsonload validation:createpaths rejected malformed domains and unsupportedencryptionvalues, whereas load paths inprofile.rsandprofiles.pytrusted existing disk fields. Both now enforceschemaVersion == 1,encryption == "none", validengine, and public-suffix domain rejection on load. - Duplicate
killpgonDropafter explicit cleanup: Added an idempotentterminated: boolguard toActiveHandoffandManagedApiSessionso explicitcleanup()/wait()preventsDropfrom issuing a secondlibc::killpg. - OAuth PKCE
localStorageloss duringhandoff start: Headless SPAs often store OAuth state or PKCE verifiers inwindow.localStoragebefore redirecting to an IdP. Forwarding live headlesslocalStorageinto the headed window fixed redirect validation failures (pkce_carried=Trueasserted inD13.2). - API URL path injection & Windows MSVC Clippy
-D warningserrors: Added_clean_profile_ref/_clean_session_idslug guards inSessforkApiClient, and scoped Unix/dev/urandom& cache probe code inapi_server.rscleanly under#[cfg(unix)]alongside aSystemFunction036Windows CSPRNG path.
6. Verification Matrix & Honest Boundaries
- Footprint:
1,233,344bytes (~1.18 MiB) stripped Rust binary;0new Rust crates;0Python dependencies. - Automated Suites:
73 / 73Rust unit tests (cargo test --locked --all-targets),0clippy -- -D warningsissues across macOS/Linux/Windows,66 / 66Pythonunittestcases, and29 / 29 PASSacross all 13 security boundaries (D1..D13indocs/security-report.md). - Known Trade-offs:
molitrades ~80.7% Lexbench compatibility against Chrome’s 99.9% for extreme memory density; use--engine dualorengine="chrome"inserve-apiwhenever 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
- Repository (MIT): https://github.com/wasabihu/sessfork
- v0.4.1 Release & Checksums: https://github.com/wasabihu/sessfork/releases/tag/v0.4.1
More Articles (22)
- 中文 零依赖构建多身份 AI 浏览器隔离池:Per-Context 代理防漏、42 MiB 进程编排与两阶段无头/有头接管实测
- EN From One False-Positive SAST SQL Alert to Six Real P1 Fixes: A Full White-Box Security Audit of sessfork
- 中文 从一条 SAST 假阳性 SQL 告警出发:我们如何对 sessfork 做了全链路白盒安全审计并修掉 6 个真实 P1 缺陷
- EN When a Headless Browser Burns 6 Cores: Debugging a 567% V8 GC Spin and Building a Zero-Tokio MCP Idle Reaper
- 中文 当无头浏览器烧满 6 核 CPU:从 567% V8 GC 死循环到零 Tokio Rust MCP 空闲回收
- EN Why Giving an AI Browser MCP Unrestricted File Upload Leaks Your Cookies — And How We Built Fail-Closed Native Uploads in Rust
- 中文 为什么别给 AI 浏览器 MCP 开全盘文件上传:原生 CDP 零拷贝与 4 道 Fail-Closed 防线
- 中文 拆完 14.5K★ GenericAgent 源码后,我把它的 3 个浏览器实战绝招安全搬进了 913 KB 纯 Rust MCP(17/17 对抗测试全绿)
- 中文 零依赖工程实践:如何在 56ms 冷启动与 0 第三方库约束下,给 claimcite 加上 LaTeX、Git 增量门禁与防注入安全围栏
- EN Zero-Dependency Engineering: Adding BibTeX/LaTeX, Git-Diff Gating, SARIF, and Security Confinement to claimcite Without Losing a Millisecond
- EN Catching Silent AI Citation Hallucinations With Zero-Dependency Deterministic Verification
- 中文 零依赖、可复现地抓出 AI 引文幻觉:从 4 类隐蔽学术造假到本地 xerj:// 字节跨度核验
- EN Hardening an AI Browser MCP Without Stripping CSP: Origin-Guarded Iframes, Fail-Fast Batching & 17 Adversarial Probes
- 中文 AI 浏览器 8 步烧掉 174K Token?我把零布局 AXTree 蒸馏塞进 848 KB 纯 Rust MCP,Token 直降 85.4%
- 中文 我用 Rust + Python 拼了一套完全本地、零云端、可逐字验真的 AI Agent 知识库闭环(开源)
- 中文 24 GB 笔记本零 Swap 并发 160 个 AI 浏览器:换纯 Rust MCP 连 Chrome 也省 503 MB
- EN Cutting AI Browser MCP Tokens by 85.4% (174K -> 25K) & Running 160 Parallel Agents with an 848 KB Zero-Tokio Rust Server
- EN Why Qwen3-Reranker-0.6B Hits Only 20.8% Strict Calibration on Financial Traps — And How We Built a Clean-Room 98.3% Fix + 5.4ms ONNX Drop-In
- 中文 砍掉 Node @playwright/mcp 换 605 KB 纯 Rust 管道:Moli 提速 6×、内存降 90.7%(官方 M4 复现)
- 中文 给 19.4k★ Rust AI 搜索引擎 XERJ 做中文 RAG 评测:不改底层代码,如何把 R@3 从 22.2% 拉到 91.1%