DEV Community

Cover image for Handing Real Logins to Headless AI Agents: Building the Lightpanda Session Bridge
Baptiste Le Bouquin
Baptiste Le Bouquin

Posted on Originally published at raknaos.github.io

Handing Real Logins to Headless AI Agents: Building the Lightpanda Session Bridge

TL;DR: When autonomous AI agents need to interact with modern web dashboards, handing them passwords or session tokens in prompts is a security disaster. I built Lightpanda Session Bridge β€” an open-source MV3 Chrome extension and a hardened loopback relay that safely replicates your live browser session into a local Lightpanda headless runtime via CDP. Zero credentials typed, zero secrets exposed to LLMs.


If you build AI agents that do real work on the modern web, you know the exact wall every developer hits: authentication.

The moment your agent needs to check an AWS billing console, inspect private logs on a SaaS dashboard, or pull data from an internal portal, the demo breaks down. Modern apps don’t live on basic auth; they sit behind Google OAuth, SSO federations, hardware passkeys, and biometric 2FA prompts.

A headless browser cannot tap your security key, answer your phone's authenticator app, or blink at a FaceID prompt.

Faced with this, most builders resort to terrible compromises:

  1. Hardcoding passwords into agent prompts or .env files (which leak into LLM context logs, chat histories, and traces).
  2. Copy-pasting session cookies manually into configs (which expire quickly and offer zero scoping or SSRF protection).
  3. Driving the user’s primary browser via raw CDP (which disrupts real work, risks hijacking other tabs, and introduces scary blast radiuses).

The Lightpanda Session Bridge is built on a different philosophy: keep the authentication ritual with the human, and hand the agent an isolated, authenticated runtime.

+-----------------------------------------------------------------------+
|  HUMAN BROWSER (Chrome / Edge / Comet)                                |
|  User logs in via Passkey / Google OAuth / 2FA                        |
|                                                                       |
|  [ 🐼 Sync Tab ] ---> Extension MV3 extracts strictly scoped cookies   |
+---------------------------------------+-------------------------------+
                                        | POST 127.0.0.1:8765
                                        | (with X-Bridge-Token + CORS check)
                                        v
+-----------------------------------------------------------------------+
|  LOCAL BRIDGE RELAY (relay/server.py)                                 |
|  - Loopback-only (127.0.0.1)                                          |
|  - IdP & Private IP blocking (anti-SSRF + DNS cache)                  |
|  - Cookie normalization (__Host-, __Secure-, RFC 6265bis)             |
+---------------------------------------+-------------------------------+
                                        | WebSocket CDP Protocol
                                        v
+-----------------------------------------------------------------------+
|  HEADLESS RUNTIME (Lightpanda in WSL2 @ :9222)                        |
|  - Isolated V8 / Zig engine                                           |
|  - Instant DOM / JS evaluation                                        |
|                                                                       |
|  AI Agent reads data via SDK (lightpanda_client.py)                   |
+-----------------------------------------------------------------------+
Enter fullscreen mode Exit fullscreen mode

Why Session Transfer Beats Credential Sharing

Passwords and API tokens are the wrong unit of trust for agents. They grant permanent, unrestricted access. Once an LLM agent has your password, you have zero guarantee where that string will travel β€” subagent handoffs, external telemetry, debug dumps, or third-party inference providers.

A session cookie is fundamentally safer:

  • It is ephemeral and expires automatically.
  • It can be instantly revoked from your main browser simply by logging out.
  • It is strictly scoped to a single target origin.

With the bridge, you authenticate once in your familiar browser. When you click Sync, the extension packages only the cookies relevant to that specific origin and pushes them into an isolated headless browser instance.

The LLM never sees your credentials. The relay never logs a cookie value. The machine gets straight to work.


Architecture: The Three Layers

The architecture is purposely minimal, robust, and audit-friendly:

1. The Chrome Extension (Manifest V3)

Designed with a clean, dark Quota Glass interface. It requires only standard scoped permissions (activeTab, cookies, storage). When clicked, it captures cookies for the active domain, normalizes them, and prepares a transfer envelope.

On first launch, it executes an auto-pairing handshake (/v1/bootstrap) with the local relay, storing a shared cryptographic token in local isolated storage without requiring manual copy-pasting.

2. The Hardened Loopback Relay (relay/server.py)

Listening exclusively on 127.0.0.1:8765, the relay is the security gateway. It:

  • Enforces strict origin matching.
  • Translates browser cookie structures into Lightpanda-compliant DevTools protocol messages (including converting lowercase sameSite tags like lax to Lightpanda's PascalCase Lax to avoid -31998 InvalidEnumTag CDP crashes).
  • Normalizes __Host- and __Secure- cookie prefixes per RFC 6265bis.
  • Forwards cookies over CDP WebSockets to the headless engine.

3. Lightpanda Headless Engine

Lightpanda is an ultra-fast, open-source headless browser built in Zig with V8, purpose-built for AI automation. Running Lightpanda in WSL2 isolates it from your Windows host environment while keeping execution blindingly fast with tiny memory footprints compared to full Chromium.


The Security Checklist: Defending Against SSRF & Local Leaks

Treating a local HTTP relay as a trusted boundary is how local privilege escalation happens. Because the relay accepts cookies, I designed it as an adversarial SSRF surface from day one:

  • πŸ›‘οΈ Zero Logging: Cookie names and values are never printed to stdout, logged to disk, or saved in history.
  • πŸ”’ Loopback Only: Hardcoded binding to 127.0.0.1. No routable network interfaces exposed.
  • 🚫 Strict Identity-Provider (IdP) Blacklisting: The relay automatically rejects transfers intended for identity roots β€” accounts.google.com, login.microsoftonline.com, appleid.apple.com, github.com, and auth0.com cannot be targeted.
  • πŸ›‘ SSRF IP & DNS Verification: Target domains must resolve to valid public IPv4/IPv6 addresses. Localhost aliases, 127.0.0.0/8, private subnets (10.0.0.0/8, 192.168.0.0/16), and wildcard DNS tools like nip.io are categorically dropped. DNS lookups are pinned with a 60-second cache to prevent time-of-check to time-of-use (TOCTOU) rebinding.
  • πŸ”‘ Origin-Restricted Handshake: Web pages or rogue local CLI scripts attempting to query /v1/bootstrap receive an immediate 403 Forbidden. Only callers presenting a legitimate chrome-extension:// Origin header can receive the pairing secret.
  • πŸ§ͺ Live Verified: Backed by 9 automated security test suites, validating private IP rejections, CDP payload structures, and token enforcement.

How AI Agents Interact With The Session

Once the session is synced into Lightpanda, your agent script uses the bundled lightweight Python SDK (lightpanda_client.py):

from lightpanda_client import LightpandaClient

# 1. Connect to Lightpanda CDP runtime
client = LightpandaClient(cdp_ws="ws://127.0.0.1:9222/")
client.connect()

# 2. Attach to or spawn the target page (already carrying the synced session)
client.attach_or_create("https://app.example.com/dashboard")

# 3. Evaluate JavaScript inside the authenticated session context
dashboard_data = client.evaluate("""(() => {
    return {
        user: document.querySelector('.user-profile')?.textContent?.trim(),
        quotaRemaining: document.querySelector('.quota-display')?.textContent?.trim(),
        csrfToken: document.querySelector('meta[name="csrf-token"]')?.content
    };
})()""")

print(f"Agent operating as: {dashboard_data['user']}")
print(f"Remaining quota: {dashboard_data['quotaRemaining']}")

client.close()
Enter fullscreen mode Exit fullscreen mode

The agent never asked for a password. The user never risked account takeover.


Quickstart (Under 3 Minutes)

1. Clone & Install Dependencies

git clone https://github.com/Raknaos/lightpanda-session-bridge.git
cd lightpanda-session-bridge
pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

2. Launch Lightpanda & The Bridge Relay

In two PowerShell terminals:

./scripts/start-lightpanda.ps1   # Runs Lightpanda CDP on 127.0.0.1:9222 (WSL2)
./scripts/start-relay.ps1        # Starts relay on 127.0.0.1:8765
Enter fullscreen mode Exit fullscreen mode

3. Load the Extension

  1. Open chrome://extensions in Chrome, Comet, or Edge.
  2. Toggle Developer Mode on.
  3. Click Load unpacked and select the repository's extension/ folder.
  4. Open the popup once while the relay runs β€” it auto-pairs instantly.
  5. Navigate to any authenticated site, click the 🐼 icon, and hit Sync Session.

Honest Limitations

  • Human-in-the-loop: You must click Sync once per session. This is an intentional security design choice, but it means this is built for supervised agent workflows, not headless server farms starting from scratch.
  • Local machine only: The relay strictly refuses remote connections. Your agent script and your browser must reside on the same workstation or dev environment.
  • Zig / WSL2 dependency: Lightpanda currently runs most smoothly on Linux/WSL2; the PowerShell scripts manage this automatically for Windows setups.

Try It Out & Contribute

The project is fully open-source under the MIT license:

If you're building autonomous agents that need to navigate authenticated environments safely, take it for a spin and star the repo! Feedback, issues, and PRs are warmly welcome.

Top comments (4)

Collapse
 
reidmarlow profile image
Reid Marlow

The main trap I hit with cookie-bridged headless sessions is IdP session revocation cascades. When an identity provider binds session cookies to the TLS fingerprint or client user-agent, replaying those cookies in a headless engine with a different TLS Client Hello can trigger anti-fraud heuristics. On strict platforms, that doesn't just drop a 401 on the agent runner; it revokes the active session on the human's primary browser too.

The other edge case is SPAs that hold short-lived access tokens in memory or Web Workers while only keeping the refresh token in an HttpOnly cookie. If the headless runtime only captures cookies at tab sync time, the agent misses the in-memory state and has to trigger a full page reload to rehydrate the client store before it can call backend APIs.

Collapse
 
raknaos profile image
Baptiste Le Bouquin

Thanks a lot for the feedback! You're totally right β€” silent cookie expiration is one of the most frustrating things to debug when an agent suddenly hits a 401.

Showing the shortest TTL / earliest expiry date alongside the origin in the popup (and in the client SDK response) is a great quality-of-life improvement without leaking any actual cookie values.

Putting this on the roadmap for the next release! πŸš€

Collapse
 
p_o_26e854a54d851cd606f08 profile image
P O

The loopback relay and explicit origin checks feel like the right boundary. I’d also show the origin and expiry next to each transferred session, since a stale cookie is easy to mistake for a current login while debugging.

Collapse
 
raknaos profile image
Baptiste Le Bouquin

Thanks a lot for the feedback! You're totally right β€” silent cookie expiration is one of the most frustrating things to debug when an agent suddenly hits a 401.

Showing the shortest TTL / earliest expiry date alongside the origin in the popup (and in the client SDK response) is a great quality-of-life improvement without leaking any actual cookie values.

Putting this on the roadmap for the next minor release!