All skills
Skillintermediate

Architecture

This document explains **why** gstack is built the way it is. For setup and commands, see CLAUDE.md. For contributing, see CONTRIBUTING.md.

Claude Code Knowledge Pack7/10/2026

Overview

Architecture

This document explains why gstack is built the way it is. For setup and commands, see CLAUDE.md. For contributing, see CONTRIBUTING.md.

The core idea

gstack gives Claude Code a persistent browser and a set of opinionated workflow skills. The browser is the hard part — everything else is Markdown.

The key insight: an AI agent interacting with a browser needs sub-second latency and persistent state. If every command cold-starts a browser, you're waiting 3-5 seconds per tool call. If the browser dies between commands, you lose cookies, tabs, and login sessions. So gstack runs a long-lived Chromium daemon that the CLI talks to over localhost HTTP.

Claude Code                     gstack
─────────                      ──────
                               ┌──────────────────────┐
  Tool call: $B snapshot -i    │  CLI (compiled binary)│
  ─────────────────────────→   │  • reads state file   │
                               │  • POST /command      │
                               │    to localhost:PORT   │
                               └──────────┬───────────┘
                                          │ HTTP
                               ┌──────────▼───────────┐
                               │  Server (Bun.serve)   │
                               │  • dispatches command  │
                               │  • talks to Chromium   │
                               │  • returns plain text  │
                               └──────────┬───────────┘
                                          │ CDP
                               ┌──────────▼───────────┐
                               │  Chromium (headless)   │
                               │  • persistent tabs     │
                               │  • cookies carry over  │
                               │  • 30min idle timeout  │
                               └───────────────────────┘

First call starts everything (~3s). Every call after: ~100-200ms.

Why Bun

Node.js would work. Bun is better here for three reasons:

  1. Compiled binaries. bun build --compile produces a single ~58MB executable. No node_modules at runtime, no npx, no PATH configuration. The binary just runs. This matters because gstack installs into ~/.claude/skills/ where users don't expect to manage a Node.js project.

  2. Native SQLite. Cookie decryption reads Chromium's SQLite cookie database directly. Bun has new Database() built in — no better-sqlite3, no native addon compilation, no gyp. One less thing that breaks on different machines.

  3. Native TypeScript. The server runs as bun run server.ts during development. No compilation step, no ts-node, no source maps to debug. The compiled binary is for deployment; source files are for development.

  4. Built-in HTTP server. Bun.serve() is fast, simple, and doesn't need Express or Fastify. The server handles ~10 routes total. A framework would be overhead.

The bottleneck is always Chromium, not the CLI or server. Bun's startup speed (~1ms for the compiled binary vs ~100ms for Node) is nice but not the reason we chose it. The compiled binary and native SQLite are.

The daemon model

Why not start a browser per command?

Playwright can launch Chromium in ~2-3 seconds. For a single screenshot, that's fine. For a QA session with 20+ commands, it's 40+ seconds of browser startup overhead. Worse: you lose all state between commands. Cookies, localStorage, login sessions, open tabs — all gone.

The daemon model means:

  • Persistent state. Log in once, stay logged in. Open a tab, it stays open. localStorage persists across commands.
  • Sub-second commands. After the first call, every command is just an HTTP POST. ~100-200ms round-trip including Chromium's work.
  • Automatic lifecycle. The server auto-starts on first use, auto-shuts down after 30 minutes idle. No process management needed.

State file

The server writes .gstack/browse.json (atomic write via tmp + rename, mode 0o600):

{ "pid": 12345, "port": 34567, "token": "uuid-v4", "startedAt": "...", "binaryVersion": "abc123" }

The CLI reads this file to find the server. If the file is missing or the server fails an HTTP health check, the CLI spawns a new server. On Windows, PID-based process detection is unreliable in Bun binaries, so the health check (GET /health) is the primary liveness signal on all platforms.

Port selection

Random port between 10000-60000 (retry up to 5 on collision). This means 10 Conductor workspaces can each run their own browse daemon with zero configuration and zero port conflicts. The old approach (scanning 9400-9409) broke constantly in multi-workspace setups.

Version auto-restart

The build writes git rev-parse HEAD to browse/dist/.version. On each CLI invocation, if the binary's version doesn't match the running server's binaryVersion, the CLI kills the old server and starts a new one. This prevents the "stale binary" class of bugs entirely — rebuild the binary, next command picks it up automatically.

Security model

Localhost only

The HTTP server binds to 127.0.0.1, not 0.0.0.0. It's not reachable from the network.

Dual-listener tunnel architecture (v1.6.0.0)

When a user runs pair-agent --client, the daemon starts an ngrok tunnel so a remote paired agent can drive the browser. Exposing the full daemon surface to the internet (even behind a random ngrok subdomain) meant /health leaked the root token on any Origin spoof, and /cookie-picker embedded the token into HTML that any caller could fetch.

The fix is two HTTP listeners, not one:

  • Local listener (127.0.0.1:LOCAL_PORT) — always bound. Serves bootstrap (/health with token delivery), /cookie-picker, /inspector/*, /welcome, /refs, the sidebar-agent API, and the full command surface. Never forwarded.
  • Tunnel listener (127.0.0.1:TUNNEL_PORT) — bound lazily on /tunnel/start, torn down on /tunnel/stop. Serves a locked allowlist: /connect (pairing ceremony, unauth + rate-limited), /command (scoped tokens only, further restricted to a browser-driving command allowlist), and /sidebar-chat. Everything else 404s.

ngrok forwards only the tunnel port. The security property comes from physical port separation: a tunnel caller cannot reach /health or /cookie-picker because those paths don't exist on that TCP socket. Header inference (check x-forwarded-for, check origin) is unreliable (ngrok header behavior changes; local proxies can add these headers); socket separation isn't.

EndpointLocal listenerTunnel listenerNotes
GET /healthpublic (no token unless headed/extension)404Token bootstrap for extension happens locally only
GET /connectpublic ({alive:true})public ({alive:true})Probe path for tunnel liveness
POST /connectpublic (rate-limited 300/min)public (rate-limited)Setup-key exchange for pair-agent
POST /commandauth (Bearer root OR scoped)auth (scoped only, allowlisted commands)Root token on tunnel = 403
POST /sidebar-chatauthauthLets remote agent post into local sidebar
POST /pairroot-only404Pairing mint — local operator action
POST /tunnel/{start,stop}root-only404Daemon configuration
POST /token, DELETE /token/:idroot-only404Scoped token mint/revoke
GET /cookie-picker, GET /cookie-picker/*public UI, auth API404Local-only — reads local browser DBs
GET /inspector, /inspector/events, etc.auth404Extension callback, local-only
GET /welcomepublic404GStack Browser landing page, local-only
GET /refsauth404Ref map — internal state
GET /activity/streamBearer OR HttpOnly gstack_sse cookie404SSE. ?token= query param no longer accepted
GET /inspector/eventsBearer OR HttpOnly gstack_sse cookie404SSE. Same cookie as /activity/stream
POST /sse-sessionauth (Bearer)404Mints the view-only 30-min SSE session cookie

Tunnel surface denial logs. Every rejection on the tunnel listener (path_not_on_tunnel, root_token_on_tunnel, missing_scoped_token, disallowed_command:*) is recorded asynchronously to ~/.gstack/security/attempts.jsonl with timestamp, source IP (from x-forwarded-for), path, and method. Rate-capped at 60 writes/min globally to prevent log-flood DoS. Shares the attempt log with the prompt-injection scanner.

SSE session cookies. EventSource can't send Authorization headers, so the extension POSTs /sse-session once at bootstrap with the root Bearer and receives a 30-minute view-only cookie (gstack_sse, HttpOnly, SameSite=Strict). The cookie is valid ONLY for /activity/stream and /inspector/events — it is NOT a scoped token and cannot be used on /command. Scope isolation is enforced by the module boundary: sse-session-cookie.ts has no imports from token-registry.ts.

Non-goal in this wave (tracked as #1136): the cookie-import-browser path launches Chrome with --remote-debugging-port=<random>. On Windows with App-Bound Encryption v20, a same-user local process can connect to that port and exfiltrate decrypted v20 cookies — an elevation path relative to reading the SQLite DB directly (which can't decrypt v20 without DPAPI context). Fix direction is --remote-debugging-pipe instead of TCP; requires restructuring the CDP client.

Bearer token auth

Every server session generates a random UUID token, written to the state file with mode 0o600 (owner-only read). Every HTTP request that mutates browser state must include Authorization: Bearer <token>. If the token doesn't match, the server returns 401.

This prevents other processes on the same machine from talking to your browse server. The cookie picker UI (/cookie-picker) and health check (/health) are exempt on the local listener — they're 127.0.0.1-bound and don't execute commands. On the tunnel listener nothing is exempt except /connect.

Cookie security

Cookies are the most sensitive data gstack handles. The design:

  1. Keychain access requires user approval. First cookie import per browser triggers a macOS Keychain dialog. The user must click "Allow" or "Always Allow." gstack never silently accesses credentials.

  2. Decryption happens in-process. Cookie values are decrypted in memory (PBKDF2 + AES-128-CBC), loaded into the Playwright context, and never written to disk in plaintext. The cookie picker UI never displays cookie values — only domain names and counts.

  3. Database is read-only. gstack copies the Chromium cookie DB to a temp file (to avoid SQLite lock conflicts with the running browser) and opens it read-only. It never modifies your real browser's cookie database.

  4. Key caching is per-session. The Keychain password + derived AES key are cached in memory for the server's lifetime. When the server shuts down (idle timeout or explicit stop), the cache is gone.

  5. No cookie values in logs. Console, network, and dialog logs never contain cookie values. The cookies command outputs cookie metadata (domain, name, expiry) but values are truncated.

Shell injection prevention

The browser registry (Comet, Chrome, Arc, Brave, Edge) is hardcoded. Database paths are constructed from known constants, never from user input. Keychain access uses Bun.spawn() with explicit argument arrays, not shell string interpolation.

Prompt injection defense (sidebar agent)

The Chrome sidebar agent has tools (Bash, Read, Glob, Grep, WebFetch) and reads hostile web pages, so it's the part of gstack most exposed to prompt injection. Defense is layered, not single-point.

  1. L1-L3 content security (browse/src/content-security.ts). Runs on every page-content command and every tool output: datamarking, hidden-element strip, ARIA regex, URL blocklist, and a trust-boundary envelope wrapper. Applied at both the server and the agent.

  2. L4 ML classifier — TestSavantAI (browse/src/security-classifier.ts). A 22MB BERT-small ONNX model (int8 quantized) bundled with the agent. Runs locally, no network. Scans every user message and every Read/Glob/Grep/WebFetch tool output before Claude sees it. Opt-in 721MB DeBERTa-v3 ensemble via GSTACK_SECURITY_ENSEMBLE=deberta.

  3. L4b transcript classifier. A Claude Haiku pass that looks at the full conversation shape (user message, tool calls, tool output), not just text. Gated by LOG_ONLY: 0.40 so most clean traffic skips the paid call.

  4. L5 canary token (browse/src/security.ts). A random token injected into the system prompt at session start. Rolling-buffer detection across text_delta and input_json_delta streams catches the token if it shows up anywhere in Claude's output, tool arguments, URLs, or file writes. Deterministic BLOCK — if the token leaks, the attacker convinced Claude to reveal the system prompt, and the session ends.

  5. L6 ensemble combiner (combineVerdict). BLOCK requires agreement from two ML classifiers at >= WARN (0.60), not a single confident hit. This is the Stack Overflow instruction-writing false-positive mitigation. On tool-output scans, single-layer high confidence BLOCKs directly — the content wasn't user-authored, so the FP concern doesn't apply.

Critical constraint: security-classifier.ts runs only in the sidebar-agent process, never in the compiled browse binary. @huggingface/transformers v4 requires onnxruntime-node, which fails dlopen from Bun compile's temp extract directory. Only the pure-string pieces (canary inject/check, verdict combiner, attack log, status) are in security.ts, which is safe to import from server.ts.

Env knobs: GSTACK_SECURITY_OFF=1 is a real kill switch (skips ML scan, canary still injects). Model cache at ~/.gstack/models/testsavant-small/ (112MB, first run) and ~/.gstack/models/deberta-v3-injection/ (721MB, opt-in only). Attack log at ~/.gstack/security/attempts.jsonl (salted sha256 + domain, rotates at 10MB, 5 generations). Per-device salt at ~/.gstack/security/device-salt (0600), cached in-process to survive FS-unwritable environments.

Visibility. The sidebar header shows a shield icon (green/amber/red) polled via /sidebar-chat. A centered banner appears on canary leak or BLOCK verdict with the exact layer scores. bin/gstack-security-dashboard aggregates local attempts; supabase/functions/community-pulse aggregates opt-in community telemetry across users.

The ref system

Refs (@e1, @e2, @c1) are how the agent addresses page elements without writing CSS selectors or XPath.

How it works

1. Agent runs: $B snapshot -i
2. Server calls Playwright's page.accessibility.snapshot()
3. Parser walks the ARIA tree, assigns sequential refs: @e1, @e2, @e3...
4. For each ref, builds a Playwright Locator: getByRole(role, { name }).nth(index)
5. Stores Map<string, RefEntry> on the Browse