ADR-028: A browser reaches the daemon only through a strict gateway in the golem binary
Date: 2026-10-31 Status: accepted. golem now opens the page, and golem web is an alias: ADR-053. Amended: 2026-11-12 (sign-ins are kept on disk, as digests. See Sign-ins on disk) Amended: 2026-11-13 (a phone also reaches the gateway, through a relay, and the gateway then names the device on its daemon connection. See ADR-051)
The idea
The web UI (how it works) is the first client that is not a program you started in your own terminal. It is a page in a browser, and the browser also runs every other website you have open. Any of those sites can try to open a WebSocket to 127.0.0.1. The daemon's rule so far, "the socket file's mode is the login", does not reach into a browser.
So the daemon stays as it is, listening only on its Unix socket, and a gateway stands in front of it. The gateway is part of the golem bun binary (ADR-019), started by golem web. It has three jobs:
- It lets in only the page that
golem webopened. - It passes protocol lines between that page and the daemon, one connection each, without changing them.
- It refuses anything a browser should never send.
All network security lives in this one program. The daemon has no port, no TLS, no cookies, and no login code.
flowchart LR
subgraph browser ["Browser tab"]
page["golem page<br>@golem/client over a WebSocket link"]
other["any other site"]
end
subgraph gw ["golem web: 127.0.0.1:7480"]
auth["login<br>token, cookie, Origin, Host"]
filter["filter<br>one JSON object, allowed method"]
bridge["bridge<br>one daemon connection per WebSocket"]
end
page -->|"HTTP and WebSocket"| auth --> filter --> bridge
other -.->|"refused: Origin, cookie"| auth
bridge -->|"Unix socket, JSON lines"| daemon["Daemon (unchanged)"]
Steps 10.3 and 10.5 build this (#10). This record says how it must work, so both steps start from the same rules.
How it works
Login
sequenceDiagram
participant You
participant CLI as golem web
participant Gw as Gateway
participant Page
CLI->>Gw: start, or find the one in run/web.json
Gw->>Gw: run/web.token (0600, O_EXCL)
CLI->>You: open http://127.0.0.1:7480/#t=TOKEN
Page->>Gw: POST /auth/exchange {token}
Gw->>Gw: check Host, Origin, Sec-Fetch-Site, token
Gw-->>Page: Set-Cookie golem_7480=SECRET (HttpOnly, SameSite=Strict)
Page->>Page: remove #t= from the address
Page->>Gw: WebSocket upgrade, with the cookie
Gw->>Gw: check Host, Origin, cookie
Gw-->>Page: open, or open then close 4401
- The token file is the root of trust.
golem webwrites~/.golem/run/web.tokenwith a random 32-byte value, mode0600, opened withO_EXCLso no other file can be in its place.- The gateway refuses to start when
run/can be written by anyone but the user. - A new token is written each time a gateway starts, and the gateway deletes it when it stops. The token travels only in the address the CLI opens, in the fragment after
#, which a browser never sends in a request line or aReferer, and in the body of/auth/exchange.
- The page trades the token for a cookie.
POST /auth/exchangetakes the token in its body and compares it in constant time.- It sets a cookie with a fresh random secret, not the token. A cookie can leak more ways than a file can: another local server on another port receives it too, because cookies on
127.0.0.1are shared by every port. So the cookie is worth nothing outside this gateway's memory, and its name carries the port (golem_7480), so two gateways never overwrite each other's. - Flags:
HttpOnly,SameSite=Strict,Path=/, andMax-Ageof 30 days. The secrets themselves live only in the cookie. The gateway keeps a SHA-256 of each one on disk, so a restarted gateway still knows them (see Sign-ins on disk).
- Every request and every upgrade is checked:
Hostmust be exactly127.0.0.1:<port>. This stops DNS rebinding, where an outside name later resolves to127.0.0.1.Originmust be exactlyhttp://127.0.0.1:<port>.localhostis a different origin and is refused, so the CLI always opens127.0.0.1. On an upgrade or aPOST, a missingOriginis refused too. Browsers always send it there, so only a program that is not a browser leaves it out, and such a program can use the socket.Sec-Fetch-Site, when present, must besame-originornone.- The cookie must name a live secret. The static page and its assets are served without it, so the page can load and run the exchange, but nothing on them is private.
- A refused upgrade is accepted, then closed with code 4401. This is for a missing or wrong cookie only. A wrong
HostorOrigingets a plain 403 and no WebSocket: the page never sends one, and a foreign site should not get an open socket. A browser reports a refused upgrade only as a generic failure (close code 1006), the same as a network error, and the client would retry forever. Code 4401 lets the client stop and show "Rungolem webfor a fresh link". The 4401 close is sent before any protocol line passes. - The WebSocket path is
/ws.- When the daemon is not running at the upgrade, the socket opens and closes with 1013, so the page can tell "daemon down" from "gateway down".
- A daemon that closes later closes the WebSocket with 1001.
/healthzanswers{"golem":"web","pid":N}. It needs no secret, and it checksHost.
One gateway per user
run/web.jsonholdspid,port, andstarted_at.golem webreads it first. If that pid is a livegolemprocess and/healthzanswers, it reuses that gateway: it readsweb.tokenand opens the same kind of link. The token stays valid while its gateway runs, so no second door is needed to ask for a fresh one. The page removes#t=withhistory.replaceState, so the token does not stay in the browser's history. Otherwise it removes the stale file and starts a new gateway. This is the single-owner rule of ADR-020, and the launchd job of step 10.14 relies on it.- The port is stable: 7480 by default, or
--port N. A random port would change the origin on each start, and with it the cookie, the theme the page remembers, and an installed PWA. A port that is taken fails with a message that names--port. The gateway does not readconfig.toml. It is a TypeScript program, and one flag is simpler than a second TOML reader. golem web --jsonprints{url, port, pid}and opens nothing, for golem desktop later.golem webruns the gateway in the foreground until Ctrl-C. Running always in the background is the launchd job of step 10.14.- A gateway is live only when
/healthzanswers with the pid inweb.json. Anything else is stale: the files are replaced. The gateway starts beforeweb.tokenis written, so a port that is taken never replaces the token of the gateway that holds it. - The browser is opened through
osascriptreading the link on stdin, because process arguments are visible to other users (ps), and the link holds the token. Without--no-openthe terminal shows the address without the token.
Framing
The daemon reads JSON lines and splits on \n (ADR-003). A browser sends whole WebSocket messages. The gateway joins the two without ever building a line the page did not send.
- Browser to daemon: one WebSocket text message is exactly one JSON object.
- It is refused when:
- it is binary
- it is larger than 1 MiB, the daemon's
MAX_LINE_BYTES(also set as Bun'smaxPayloadLength) - it contains
\nor\r JSON.parsefails- the value is not a plain object (an array, a number, or
null) methodis missing or is not a string
- The
\nrule matters most. Without it,{"method":"ping"}\n{"method":"auth.set",…}would pass the method check aspingand reach the daemon as two commands. - The gateway appends the one
\nitself, and forwards the original text unchanged. It never forwards a re-serialized copy, so what the daemon reads is exactly what the page sent.
- It is refused when:
- Daemon to browser: one line is one WebSocket message.
- The gateway decodes the socket's bytes with a streaming UTF-8 decoder, so a character split across two reads stays whole. It then splits on
\nand sends each line as one text message, without the newline. - The daemon's lines are trusted. They are not parsed.
- The gateway decodes the socket's bytes with a streaming UTF-8 decoder, so a character split across two reads stays whole. It then splits on
- Refusals:
- A message that breaks framing means the page has a bug, or is not the page. The gateway closes the WebSocket with 1008 (policy violation), and the daemon connection with it.
- A well-formed request for a method that is not allowed gets a JSON-RPC error with the request's
id, code-32020, and the messagenot allowed from the browser. The connection stays open. - A denied request whose
idis not a string, number, or null (an object or an array) gets no reply, because JSON-RPC has no way to address it.
- The gateway never speaks the protocol itself. It sends no
helloand nopingon a bridged connection. Request ids belong to the page alone, so they cannot collide.
Which methods a browser may call
- Each command in
golem_protocoldeclares whether a browser may call it.just genwrites the list topackages/protocol/gen/browser-methods.ts, which the gateway imports. A test fails when a method the daemon answers (standard_methods()ingolem/server/handlers.py) has no declaration, so a new command such asdaemon.shutdown,skill.trust, orflow.startis never let through by accident. Someone has to decide it. - Denied today:
auth.set: the API key would pass through the page's memory, its devtools, and its wire view.auth.remove: key management stays in the terminal, where the Keychain prompt is.
- Later additions: ADR-037 lets the browser manage MCP servers, send an MCP token, and edit
config.toml, with two daemon checks that keep model provider keys and trust out of its reach. Model provider keys stay denied. - Allowed, with reasons, because these are easy to get wrong:
auth.listnever returns a key, only where each one is stored.policy.update,approval.respond, andmessage.sendare allowed. They are the point of the web UI. Together they can make golem run code on the Mac, which is why the threat below is cross-site scripting (XSS), not secrets.
Liveness and load
- The heartbeat is end to end. The client core in the page keeps its
pingevery 5 s and its 10 s timeout, through the gateway, to the daemon. It is the only check that notices a link that died while the laptop slept. When a tab becomes visible again, the client pings at once, because browsers slow the timers of a hidden tab to about once a minute. - Between the browser and the gateway, Bun's
idleTimeoutandsendPingsclose a dead WebSocket. - A close on either side closes the other. A daemon that restarts closes the WebSocket. The page reconnects, says
hello, and re-attaches from its lastseq(ADR-007). - Backpressure.
- When the browser falls behind,
ws.getBufferedAmount()grows. Above 4 MiB the gateway stops reading the daemon socket, and resumes ondrain. - The daemon's queue for that connection then fills. At
MAX_PENDING_FRAMES(20 000,golem/server/connection.py) the daemon drops the connection, and the page re-attaches fromafter_seq. - This reuses the recovery that already exists, and the gateway never buffers without a limit.
- When the browser falls behind,
- Input for the daemon is bounded. When browser-to-daemon input piles up past 4 MiB unwritten, the gateway closes the WebSocket with 1008.
- At most 16 WebSockets at once. The 17th upgrade gets 503. One person has a handful of tabs, so more than that means something is wrong.
Headers
| Header | Value | Why |
|---|---|---|
Content-Security-Policy | default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self' | No script from anywhere else and no inline script. 'unsafe-inline' for styles only, because Radix's scroll lock injects a <style>. connect-src 'self' covers the WebSocket in current browsers |
X-Content-Type-Options | nosniff | |
Referrer-Policy | no-referrer | |
Cache-Control | no-cache on index.html, public, max-age=31536000, immutable on hashed assets | After brew upgrade, the next load is the new page |
Cross-Origin-Opener-Policy | same-origin | Another window cannot reach into the page |
- The page's files are embedded in
bin/golematjust dist(import … with { type: "file" }). The source ispackages/web/dist, whichjust distbuilds. A checkout serves that folder when it is built, and the placeholder otherwise. A page path without a file extension servesindex.html, so the page's routes reload.
There is no service worker that caches the page. The web app manifest and the icons are plain files served like the rest, so the page can be installed without one. A service worker would show an old page, speaking an old protocol, after an upgrade.
Development
vite dev serves the page on its own port, so the browser's Origin is Vite's. The Vite proxy for /ws and /auth rewrites Origin to the gateway's own origin, so the gateway runs with the same checks in development as in a release. There is no --dev flag that loosens them.
The transport seam in @golem/client
The page and the TUI use the same client core: hello, heartbeat, backoff, request ids, re-attach from seq, and dropping repeats. Only the way bytes move differs, so that part becomes an interface. The core asks for a new link on every reconnect:
type Dial = () => Link;
interface Link {
send(line: string): void; // one protocol line, without "\n"
close(error?: Error): void;
onOpen(listener: () => void): void;
onLine(listener: (line: string) => void): void;
onClose(listener: (error?: Error, code?: number) => void): void;
}unixDial(path)lives in@golem/client/node.wsDial(url)lives in@golem/client, which has nonode:import and is typechecked without Node's types.- A close with code 4401 sets the new connection state
unauthorized, and retries stop, as they do forrejectedtoday.
Threat model
| Threat | What stops it |
|---|---|
A website you visit opens a WebSocket to 127.0.0.1:7480 | Origin is checked exactly, and it has no cookie |
DNS rebinding: an outside name resolves to 127.0.0.1 | Host is checked exactly |
| Another local server, on another port, reads the cookie | The cookie is a secret the gateway keeps only as a SHA-256, and is useless without a matching Origin. The token itself never leaves the file and the address |
A program run as you reads web.token | Out of scope. It can already use the socket. The file mode is the login, as it always was |
A program run as you reads web-sessions | It holds only hashes, which cannot be sent back as a cookie. The program could read web.token and use the socket anyway |
| Another user on the Mac | The token file is 0600, run/ is checked, and the gateway listens only on loopback |
| One message smuggles a second command | One object per message, no \n or \r |
| A new privileged command reaches the browser by default | A generated allowlist, and a test that fails for any method nobody declared |
| XSS from model output, a tool's output, or a file's content | Markdown is sanitized (DOMPurify: no style, SVG, javascript: or data: links, or remote images), a strict CSP, and no dangerouslySetInnerHTML outside the sanitizer (the web stack ADR, ticket 10.1.2) |
| Clickjacking the approval card | frame-ancestors 'none' |
| A slow or stuck tab fills memory | The 4 MiB pause, then the daemon's drop and a re-attach |
| An old page after an upgrade | index.html is no-cache, there is no service worker, and hello refuses a different protocol major |
Sign-ins on disk
Amended 2026-11-12. A gateway that restarts (a reboot, brew upgrade, a crash that launchd restarts) used to forget every cookie, and the page said "This page needs a fresh link". Cookie secrets are now kept on disk, as digests, so they survive a restart.
- The file is
~/.golem/run/web-sessions. It holds JSON:{"version":1,"sessions":[{"sha256":"<64 hex>","expires":<ms since the epoch>}]}. It never holds a secret, only the SHA-256 of each live one and when it ends. - Mode
0600, written atomically. A new file is made next to it withO_EXCLandO_NOFOLLOW(asweb.tokenis), written, synced, and renamed over the old one, so a reader sees the old file or the new one.run/is checked as forweb.token. - The gateway reads it on each check, drops the entries that have ended, and writes it on each new sign-in and each time something was dropped. Reading on each check is what makes
golem web logout, which runs in another process, take effect on the next request. The file is a few lines, and a check happens only on a WebSocket upgrade. - A file that is damaged, has the wrong mode or owner, or is a link, is not trusted. It is replaced with an empty one, and everyone signs in again. A
run/that fails the check means nothing is read or written, so nobody is signed in. - Comparison. The gateway hashes the presented cookie and compares the digest with every entry in constant time, with no early exit. The cap of 64 live sign-ins stays.
- If the file cannot be read or written, the gateway fails closed: a sign-in that is not on disk is not valid, so the browser needs a fresh link. A
run/that fails its checks refuses every sign-in. - Unchanged: the cookie's name (
golem_<port>), its flags, its 30-dayMax-Age, andPOST /auth/exchange. golem web logoutwrites an empty list, and the next request of every browser isunauthorized. A WebSocket that is already open stays open until it closes or the page reloads, because the cookie is checked on the upgrade.- Why the threat model holds. A program running as you can already read
web.tokenand use the daemon's socket, so the file gives it nothing new. A digest cannot be sent back as a cookie, because the gateway hashes what it receives. Another user cannot read the file, orrun/. - One file, because only one gateway runs at a time (
run/web.json).golem webstarted by hand and the launchd job share it.
Tests this record asks for
The gateway's core is plain functions over the standard Request and strings (checkRequest, checkUpgrade, exchangeToken, filterMessage, splitLines), tested with node:test. The thin Bun.serve adapter is covered with bun test and just smoke-dist.
- Framing:
- two objects joined by
\n - a lone
\r - 1 MiB plus one byte
- a binary message
- not JSON
NaN- an array
null- a duplicate
methodkey, whereJSON.parsekeeps the last one and the check reads that same value "auth.set", which parses toauth.setand is refused- an unknown method
- a method with no declaration, which fails
just check
- two objects joined by
- Origin and Host:
Originmissing on an upgradeOrigin: null- another port
http://localhost:7480- upper-case letters
- a trailing slash
Host: 127.0.0.1.nip.io:7480Hostwithout the portSec-Fetch-Site: cross-site
- Login:
- no cookie
- a wrong cookie
- a secret from before a restart
- the file token sent as the cookie
- a wrong token on
/auth/exchange - a token file whose mode is not
0600 run/writable by the group- a stale
run/web.jsonwhose pid is dead or not golem's
- Lifecycle:
- a slow reader pauses the daemon socket, and reading resumes on
drain - a close on either side closes the other
- the daemon is down at the upgrade
- the daemon restarts mid-stream
- the 17th WebSocket gets 503
- a refused upgrade closes with 4401 before any line passes
- a slow reader pauses the daemon socket, and reading resumes on
- Content, in step 10.8:
- an XSS corpus through the sanitizer
- in Playwright, any
securitypolicyviolationevent or console error fails the test
Other shapes that lost
The daemon serves the page and the WebSocket. This removes a hop. It also puts a web server, a port, and login code into the frozen process that holds the state, far from the TypeScript client that has to agree with it. The vision decided against it. The way back stays small: a WebSocket listener that reuses Connection in golem/server/connection.py.
HTTP and server-sent events, like opencode. A second API shape to keep in step with the protocol. The page would need two channels, and after_seq replay would have to be built again. The app API of serve mode can be HTTP and SSE later, behind this same gateway.
A denylist. It is shorter today. Every new privileged command would be open to the browser on the day it lands, until someone remembers.
Using the token as the cookie. One value fewer. But cookies on 127.0.0.1 are shared by every port, so any local dev server you run could read it, then replay it from a page it serves.
A random port each time. Nothing to collide with. But the origin changes on every start, and the cookie, the remembered theme, and an installed PWA go with it.
Refusing a bad upgrade with HTTP 401. It is the usual HTTP answer. A browser shows it only as a failed connection, and the client cannot tell it from the daemon being down.
Parsing and re-serializing every message. It would make framing trivial. It also means the daemon reads something the page did not write, and a subtle encoding difference becomes a bug in the security boundary.
What it costs
- One more process when you use the web UI, and one more hop, which costs microseconds.
- A browser stays signed in for 30 days, across gateway restarts, because the digests are on disk.
golem web logoutends every sign-in. - Port 7480 can be taken by something else.
--portis the way out, and the new origin starts with no cookie. - Each new command needs a browser declaration before
just checkpasses. 'unsafe-inline'for styles is a small hole: injected CSS cannot run script, but it can restyle the page. The sanitizer forbidsstylein model output, which is the main way CSS could get in.